blob: 9bd003724456c1370c477cadc6be253250248a99 [file] [log] [blame]
Chris Lattnera3b8b5c2004-07-23 17:56:30 +00001//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveInterval analysis pass which is used
11// by the Linear Scan Register allocator. This pass linearizes the
12// basic blocks of the function in DFS order and uses the
13// LiveVariables pass to conservatively compute live intervals for
14// each virtual and physical register.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "liveintervals"
Chris Lattner3c3fe462005-09-21 04:19:09 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Misha Brukman08a6c762004-09-03 18:25:53 +000020#include "VirtRegMap.h"
Chris Lattner015959e2004-05-01 21:24:39 +000021#include "llvm/Value.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000022#include "llvm/Analysis/AliasAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000023#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000028#include "llvm/CodeGen/Passes.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000029#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000030#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000037#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000038#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000039using namespace llvm;
40
Dan Gohman844731a2008-05-13 00:00:25 +000041// Hidden options for help debugging.
42static cl::opt<bool> DisableReMat("disable-rematerialization",
43 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000044
Dan Gohman844731a2008-05-13 00:00:25 +000045static cl::opt<bool> SplitAtBB("split-intervals-at-bb",
46 cl::init(true), cl::Hidden);
47static cl::opt<int> SplitLimit("split-limit",
48 cl::init(-1), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000049
Dan Gohman4c8f8702008-07-25 15:08:37 +000050static cl::opt<bool> EnableAggressiveRemat("aggressive-remat", cl::Hidden);
51
Chris Lattnercd3245a2006-12-19 22:41:21 +000052STATISTIC(numIntervals, "Number of original intervals");
53STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
Evan Cheng0cbb1162007-11-29 01:06:25 +000054STATISTIC(numFolds , "Number of loads/stores folded into instructions");
55STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000056
Devang Patel19974732007-05-03 01:11:54 +000057char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000058static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000059
Chris Lattnerf7da2c72006-08-24 22:43:55 +000060void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman6d69ba82008-07-25 00:02:30 +000061 AU.addRequired<AliasAnalysis>();
62 AU.addPreserved<AliasAnalysis>();
David Greene25133302007-06-08 17:18:56 +000063 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000064 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000065 AU.addPreservedID(MachineLoopInfoID);
66 AU.addPreservedID(MachineDominatorsID);
Owen Andersonfcc63502008-05-29 18:35:21 +000067 AU.addPreservedID(PHIEliminationID);
68 AU.addRequiredID(PHIEliminationID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000069 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000070 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000071}
72
Chris Lattnerf7da2c72006-08-24 22:43:55 +000073void LiveIntervals::releaseMemory() {
Evan Cheng3f32d652008-06-04 09:18:41 +000074 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000075 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 mi2iMap_.clear();
77 i2miMap_.clear();
78 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000079 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
80 VNInfoAllocator.Reset();
Evan Cheng1ed99222008-07-19 00:37:25 +000081 while (!ClonedMIs.empty()) {
82 MachineInstr *MI = ClonedMIs.back();
83 ClonedMIs.pop_back();
84 mf_->DeleteMachineInstr(MI);
85 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000086}
87
Owen Anderson80b3ce62008-05-28 20:54:50 +000088void LiveIntervals::computeNumbering() {
89 Index2MiMap OldI2MI = i2miMap_;
Owen Anderson7fbad272008-07-23 21:37:49 +000090 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Anderson80b3ce62008-05-28 20:54:50 +000091
92 Idx2MBBMap.clear();
93 MBB2IdxMap.clear();
94 mi2iMap_.clear();
95 i2miMap_.clear();
96
Owen Andersona1566f22008-07-22 22:46:49 +000097 FunctionSize = 0;
98
Chris Lattner428b92e2006-09-15 03:57:23 +000099 // Number MachineInstrs and MachineBasicBlocks.
100 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +0000101 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +0000102
103 unsigned MIIndex = 0;
104 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
105 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000106 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000107
Owen Anderson7fbad272008-07-23 21:37:49 +0000108 // Insert an empty slot at the beginning of each block.
109 MIIndex += InstrSlots::NUM;
110 i2miMap_.push_back(0);
111
Chris Lattner428b92e2006-09-15 03:57:23 +0000112 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
113 I != E; ++I) {
114 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000115 assert(inserted && "multiple MachineInstr -> index mappings");
Chris Lattner428b92e2006-09-15 03:57:23 +0000116 i2miMap_.push_back(I);
117 MIIndex += InstrSlots::NUM;
Owen Andersona1566f22008-07-22 22:46:49 +0000118 FunctionSize++;
Owen Anderson7fbad272008-07-23 21:37:49 +0000119
120 // Insert an empty slot after every instruction.
Owen Anderson1fbb4542008-06-16 16:58:24 +0000121 MIIndex += InstrSlots::NUM;
122 i2miMap_.push_back(0);
Owen Anderson35578012008-06-16 07:10:49 +0000123 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000124
Owen Anderson1fbb4542008-06-16 16:58:24 +0000125 // Set the MBB2IdxMap entry for this MBB.
126 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
127 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000128 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000129 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000130
131 if (!OldI2MI.empty())
Owen Anderson7fbad272008-07-23 21:37:49 +0000132 for (iterator OI = begin(), OE = end(); OI != OE; ++OI)
133 for (LiveInterval::iterator LI = OI->second.begin(),
134 LE = OI->second.end(); LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000135
Owen Anderson7eec0c22008-05-29 23:01:22 +0000136 // Remap the start index of the live range to the corresponding new
137 // number, or our best guess at what it _should_ correspond to if the
138 // original instruction has been erased. This is either the following
139 // instruction or its predecessor.
Owen Anderson7fbad272008-07-23 21:37:49 +0000140 unsigned index = LI->start / InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000141 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000142 if (offset == InstrSlots::LOAD) {
143 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000144 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->start);
Owen Anderson7fbad272008-07-23 21:37:49 +0000145 // Take the pair containing the index
146 std::vector<IdxMBBPair>::const_iterator J =
147 ((I != OldI2MBB.end() && I->first > index) ||
148 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000149
Owen Anderson7fbad272008-07-23 21:37:49 +0000150 LI->start = getMBBStartIdx(J->second);
151 } else {
152 LI->start = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000153 }
154
155 // Remap the ending index in the same way that we remapped the start,
156 // except for the final step where we always map to the immediately
157 // following instruction.
Owen Andersond7dcbec2008-07-25 19:50:48 +0000158 index = (LI->end - 1) / InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000159 offset = LI->end % InstrSlots::NUM;
Owen Andersond7dcbec2008-07-25 19:50:48 +0000160 if (offset == InstrSlots::USE) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000161 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000162 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end);
Owen Anderson7fbad272008-07-23 21:37:49 +0000163 // Take the pair containing the index
164 std::vector<IdxMBBPair>::const_iterator J =
165 ((I != OldI2MBB.end() && I->first > index) ||
166 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
167
168 LI->end = getMBBEndIdx(J->second) + 1;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000169 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000170 unsigned idx = index;
171 while (!OldI2MI[index]) ++index;
172 LI->end = mi2iMap_[OldI2MI[index]] + (idx == index ? offset : 0);
Owen Anderson4b5b2092008-05-29 18:15:49 +0000173 }
Owen Anderson745825f42008-05-28 22:40:08 +0000174
Owen Anderson7eec0c22008-05-29 23:01:22 +0000175 // Remap the VNInfo def index, which works the same as the
176 // start indices above.
Owen Anderson745825f42008-05-28 22:40:08 +0000177 VNInfo* vni = LI->valno;
Owen Anderson7fbad272008-07-23 21:37:49 +0000178 index = vni->def / InstrSlots::NUM;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000179 offset = vni->def % InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000180 if (offset == InstrSlots::LOAD) {
181 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000182 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->def);
Owen Anderson7fbad272008-07-23 21:37:49 +0000183 // Take the pair containing the index
184 std::vector<IdxMBBPair>::const_iterator J =
185 ((I != OldI2MBB.end() && I->first > index) ||
186 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000187
Owen Anderson7fbad272008-07-23 21:37:49 +0000188 vni->def = getMBBStartIdx(J->second);
189
190 } else {
191 vni->def = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000192 }
Owen Anderson745825f42008-05-28 22:40:08 +0000193
Owen Anderson7eec0c22008-05-29 23:01:22 +0000194 // Remap the VNInfo kill indices, which works the same as
195 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000196 for (size_t i = 0; i < vni->kills.size(); ++i) {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000197 index = (vni->kills[i]-1) / InstrSlots::NUM;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000198 offset = vni->kills[i] % InstrSlots::NUM;
Owen Andersond7dcbec2008-07-25 19:50:48 +0000199 if (offset == InstrSlots::USE) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000200 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000201 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->kills[i]);
Owen Anderson7fbad272008-07-23 21:37:49 +0000202 // Take the pair containing the index
203 std::vector<IdxMBBPair>::const_iterator J =
204 ((I != OldI2MBB.end() && I->first > index) ||
205 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
206
207 vni->kills[i] = getMBBEndIdx(J->second) + 1;
208 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000209 unsigned idx = index;
210 while (!OldI2MI[index]) ++index;
211 vni->kills[i] = mi2iMap_[OldI2MI[index]] +
212 (idx == index ? offset : 0);
Owen Anderson7eec0c22008-05-29 23:01:22 +0000213 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000214 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000215 }
216}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000217
Owen Anderson80b3ce62008-05-28 20:54:50 +0000218/// runOnMachineFunction - Register allocate the whole function
219///
220bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
221 mf_ = &fn;
222 mri_ = &mf_->getRegInfo();
223 tm_ = &fn.getTarget();
224 tri_ = tm_->getRegisterInfo();
225 tii_ = tm_->getInstrInfo();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000226 aa_ = &getAnalysis<AliasAnalysis>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000227 lv_ = &getAnalysis<LiveVariables>();
228 allocatableRegs_ = tri_->getAllocatableSet(fn);
229
230 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000231 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000232
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000233 numIntervals += getNumIntervals();
234
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000235 DOUT << "********** INTERVALS **********\n";
236 for (iterator I = begin(), E = end(); I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000237 I->second.print(DOUT, tri_);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000238 DOUT << "\n";
239 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000240
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000241 numIntervalsAfter += getNumIntervals();
Chris Lattner70ca3582004-09-30 15:59:17 +0000242 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000243 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000244}
245
Chris Lattner70ca3582004-09-30 15:59:17 +0000246/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000247void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000248 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000249 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000250 I->second.print(O, tri_);
251 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000252 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000253
254 O << "********** MACHINEINSTRS **********\n";
255 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
256 mbbi != mbbe; ++mbbi) {
257 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
258 for (MachineBasicBlock::iterator mii = mbbi->begin(),
259 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000260 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000261 }
262 }
263}
264
Evan Chengc92da382007-11-03 07:20:12 +0000265/// conflictsWithPhysRegDef - Returns true if the specified register
266/// is defined during the duration of the specified interval.
267bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
268 VirtRegMap &vrm, unsigned reg) {
269 for (LiveInterval::Ranges::const_iterator
270 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
271 for (unsigned index = getBaseIndex(I->start),
272 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
273 index += InstrSlots::NUM) {
274 // skip deleted instructions
275 while (index != end && !getInstructionFromIndex(index))
276 index += InstrSlots::NUM;
277 if (index == end) break;
278
279 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng5d446262007-11-15 08:13:29 +0000280 unsigned SrcReg, DstReg;
281 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
282 if (SrcReg == li.reg || DstReg == li.reg)
283 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000284 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
285 MachineOperand& mop = MI->getOperand(i);
Evan Cheng5d446262007-11-15 08:13:29 +0000286 if (!mop.isRegister())
Evan Chengc92da382007-11-03 07:20:12 +0000287 continue;
288 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000289 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000290 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000291 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000292 if (!vrm.hasPhys(PhysReg))
293 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000294 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000295 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000296 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000297 return true;
298 }
299 }
300 }
301
302 return false;
303}
304
Evan Cheng549f27d32007-08-13 23:45:17 +0000305void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000306 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000307 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000308 else
309 cerr << "%reg" << reg;
310}
311
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000312void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000313 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000314 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000315 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000316 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000317 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000318 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000319
Evan Cheng419852c2008-04-03 16:39:43 +0000320 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
321 DOUT << "is a implicit_def\n";
322 return;
323 }
324
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000325 // Virtual registers may be defined multiple times (due to phi
326 // elimination and 2-addr elimination). Much of what we do only has to be
327 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000328 // time we see a vreg.
329 if (interval.empty()) {
330 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000331 unsigned defIndex = getDefIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000332 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000333 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000334 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000335 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000336 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000337 tii_->isMoveInstr(*mi, SrcReg, DstReg))
338 CopyMI = mi;
339 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000340
341 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000342
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000343 // Loop over all of the blocks that the vreg is defined in. There are
344 // two cases we have to handle here. The most common case is a vreg
345 // whose lifetime is contained within a basic block. In this case there
346 // will be a single kill, in MBB, which comes after the definition.
347 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
348 // FIXME: what about dead vars?
349 unsigned killIdx;
350 if (vi.Kills[0] != mi)
351 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
352 else
353 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000354
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000355 // If the kill happens after the definition, we have an intra-block
356 // live range.
357 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000358 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000359 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000360 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000361 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000362 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000363 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000364 return;
365 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000366 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000367
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000368 // The other case we handle is when a virtual register lives to the end
369 // of the defining block, potentially live across some blocks, then is
370 // live into some number of blocks, but gets killed. Start by adding a
371 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000372 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000373 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000374 interval.addRange(NewLR);
375
376 // Iterate over all of the blocks that the variable is completely
377 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
378 // live interval.
379 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
380 if (vi.AliveBlocks[i]) {
Owen Anderson31ec8412008-06-16 19:32:40 +0000381 LiveRange LR(getMBBStartIdx(i),
Evan Chengf26e8552008-06-17 20:13:36 +0000382 getMBBEndIdx(i)+1, // MBB ends at -1.
Owen Anderson31ec8412008-06-16 19:32:40 +0000383 ValNo);
384 interval.addRange(LR);
385 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000386 }
387 }
388
389 // Finally, this virtual register is live from the start of any killing
390 // block to the 'use' slot of the killing instruction.
391 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
392 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000393 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000394 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000395 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000396 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000397 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000398 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000399 }
400
401 } else {
402 // If this is the second time we see a virtual register definition, it
403 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000404 // the result of two address elimination, then the vreg is one of the
405 // def-and-use register operand.
Evan Chengef0732d2008-07-10 07:35:43 +0000406 if (mi->isRegReDefinedByTwoAddr(interval.reg, MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000407 // If this is a two-address definition, then we have already processed
408 // the live range. The only problem is that we didn't realize there
409 // are actually two values in the live interval. Because of this we
410 // need to take the LiveRegion that defines this register and split it
411 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000412 assert(interval.containsOneValue());
413 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000414 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000415
Evan Cheng4f8ff162007-08-11 00:59:19 +0000416 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000417 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000418
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000419 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000420 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000421 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000422
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000423 // Two-address vregs should always only be redefined once. This means
424 // that at this point, there should be exactly one value number in it.
425 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
426
Chris Lattner91725b72006-08-31 05:54:43 +0000427 // The new value number (#1) is defined by the instruction we claimed
428 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000429 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
430 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000431
Chris Lattner91725b72006-08-31 05:54:43 +0000432 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000433 OldValNo->def = RedefIndex;
434 OldValNo->copy = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000435
436 // Add the new live interval which replaces the range for the input copy.
437 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000438 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000439 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000440 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000441
442 // If this redefinition is dead, we need to add a dummy unit live
443 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000444 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000445 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000446
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000447 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000448 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000449
450 } else {
451 // Otherwise, this must be because of phi elimination. If this is the
452 // first redefinition of the vreg that we have seen, go back and change
453 // the live range in the PHI block to be a different value number.
454 if (interval.containsOneValue()) {
455 assert(vi.Kills.size() == 1 &&
456 "PHI elimination vreg should have one kill, the PHI itself!");
457
458 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000459 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000460 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000461 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000462 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000463 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000464 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000465 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000466 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000467 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000468
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000469 // Replace the interval with one of a NEW value number. Note that this
470 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000471 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000472 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000473 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000474 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000475 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000476 }
477
478 // In the case of PHI elimination, each variable definition is only
479 // live until the end of the block. We've already taken care of the
480 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000481 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000482
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000483 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000484 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000485 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000486 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000487 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000488 tii_->isMoveInstr(*mi, SrcReg, DstReg))
489 CopyMI = mi;
490 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000491
Owen Anderson7fbad272008-07-23 21:37:49 +0000492 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000493 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000494 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000495 interval.addKill(ValNo, killIndex);
496 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000497 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000498 }
499 }
500
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000501 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000502}
503
Chris Lattnerf35fef72004-07-23 21:24:19 +0000504void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000505 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000506 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000507 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000508 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000509 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000510 // A physical register cannot be live across basic block, so its
511 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000512 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000513
Chris Lattner6b128bd2006-09-03 08:07:11 +0000514 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000515 unsigned start = getDefIndex(baseIndex);
516 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000517
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000518 // If it is not used after definition, it is considered dead at
519 // the instruction defining it. Hence its interval is:
520 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000521 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000522 DOUT << " dead";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000523 end = getDefIndex(start) + 1;
524 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000525 }
526
527 // If it is not dead on definition, it must be killed by a
528 // subsequent instruction. Hence its interval is:
529 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000530 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000531 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000532 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
533 getInstructionFromIndex(baseIndex) == 0)
534 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000535 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000536 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000537 end = getUseIndex(baseIndex) + 1;
538 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000539 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000540 // Another instruction redefines the register before it is ever read.
541 // Then the register is essentially dead at the instruction that defines
542 // it. Hence its interval is:
543 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000544 DOUT << " dead";
Evan Cheng9a1956a2006-11-15 20:54:11 +0000545 end = getDefIndex(start) + 1;
546 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000547 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000548
549 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000550 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000551
552 // The only case we should have a dead physreg here without a killing or
553 // instruction where we know it's dead is if it is live-in to the function
554 // and never used.
Evan Chengc8d044e2008-02-15 18:24:29 +0000555 assert(!CopyMI && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000556 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000557
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000558exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000559 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000560
Evan Cheng24a3cc42007-04-25 07:30:23 +0000561 // Already exists? Extend old live interval.
562 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000563 VNInfo *ValNo = (OldLR != interval.end())
Evan Chengc8d044e2008-02-15 18:24:29 +0000564 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000565 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000566 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000567 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000568 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000569}
570
Chris Lattnerf35fef72004-07-23 21:24:19 +0000571void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
572 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000573 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000574 MachineOperand& MO,
575 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000576 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000577 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000578 getOrCreateInterval(MO.getReg()));
579 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000580 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000581 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000582 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000583 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000584 tii_->isMoveInstr(*MI, SrcReg, DstReg))
585 CopyMI = MI;
Owen Anderson6b098de2008-06-25 23:39:39 +0000586 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
587 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000588 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000589 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000590 // If MI also modifies the sub-register explicitly, avoid processing it
591 // more than once. Do not pass in TRI here so it checks for exact match.
592 if (!MI->modifiesRegister(*AS))
Owen Anderson6b098de2008-06-25 23:39:39 +0000593 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
594 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000595 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000596}
597
Evan Chengb371f452007-02-19 21:49:54 +0000598void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000599 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000600 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000601 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
602
603 // Look for kills, if it reaches a def before it's killed, then it shouldn't
604 // be considered a livein.
605 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000606 unsigned baseIndex = MIIdx;
607 unsigned start = baseIndex;
Evan Chengb371f452007-02-19 21:49:54 +0000608 unsigned end = start;
609 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000610 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000611 DOUT << " killed";
612 end = getUseIndex(baseIndex) + 1;
613 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000614 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000615 // Another instruction redefines the register before it is ever read.
616 // Then the register is essentially dead at the instruction that defines
617 // it. Hence its interval is:
618 // [defSlot(def), defSlot(def)+1)
619 DOUT << " dead";
620 end = getDefIndex(start) + 1;
621 goto exit;
622 }
623
624 baseIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000625 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
626 getInstructionFromIndex(baseIndex) == 0)
627 baseIndex += InstrSlots::NUM;
Evan Chengb371f452007-02-19 21:49:54 +0000628 ++mi;
629 }
630
631exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000632 // Live-in register might not be used at all.
633 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000634 if (isAlias) {
635 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000636 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000637 } else {
638 DOUT << " live through";
639 end = baseIndex;
640 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000641 }
642
Evan Chengf3bb2e62007-09-05 21:46:51 +0000643 LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000644 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000645 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000646 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000647}
648
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000649/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000650/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000651/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000652/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000653void LiveIntervals::computeIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000654 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
655 << "********** Function: "
656 << ((Value*)mf_->getFunction())->getName() << '\n';
Chris Lattner6b128bd2006-09-03 08:07:11 +0000657 // Track the index of the current machine instr.
658 unsigned MIIndex = 0;
Owen Anderson7fbad272008-07-23 21:37:49 +0000659
660 // Skip over empty initial indices.
661 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
662 getInstructionFromIndex(MIIndex) == 0)
663 MIIndex += InstrSlots::NUM;
664
Chris Lattner428b92e2006-09-15 03:57:23 +0000665 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
666 MBBI != E; ++MBBI) {
667 MachineBasicBlock *MBB = MBBI;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000668 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000669
Chris Lattner428b92e2006-09-15 03:57:23 +0000670 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000671
Dan Gohmancb406c22007-10-03 19:26:29 +0000672 // Create intervals for live-ins to this BB first.
673 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
674 LE = MBB->livein_end(); LI != LE; ++LI) {
675 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
676 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000677 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000678 if (!hasInterval(*AS))
679 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
680 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000681 }
682
Chris Lattner428b92e2006-09-15 03:57:23 +0000683 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000684 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000685
Evan Cheng438f7bc2006-11-10 08:43:01 +0000686 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000687 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
688 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000689 // handle register defs - build intervals
Chris Lattner428b92e2006-09-15 03:57:23 +0000690 if (MO.isRegister() && MO.getReg() && MO.isDef())
Evan Chengef0732d2008-07-10 07:35:43 +0000691 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000692 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000693
694 MIIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000695
696 // Skip over empty indices.
697 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
698 getInstructionFromIndex(MIIndex) == 0)
699 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000700 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000701 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000702}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000703
Evan Cheng4ca980e2007-10-17 02:10:22 +0000704bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Chenga5bfc972007-10-17 06:53:44 +0000705 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000706 std::vector<IdxMBBPair>::const_iterator I =
707 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
708
709 bool ResVal = false;
710 while (I != Idx2MBBMap.end()) {
711 if (LR.end <= I->first)
712 break;
713 MBBs.push_back(I->second);
714 ResVal = true;
715 ++I;
716 }
717 return ResVal;
718}
719
720
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000721LiveInterval LiveIntervals::createInterval(unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000722 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000723 HUGE_VALF : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000724 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000725}
Evan Chengf2fbca62007-11-12 06:35:08 +0000726
Evan Chengc8d044e2008-02-15 18:24:29 +0000727/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
728/// copy field and returns the source register that defines it.
729unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
730 if (!VNI->copy)
731 return 0;
732
733 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
734 return VNI->copy->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000735 if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
736 return VNI->copy->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000737 unsigned SrcReg, DstReg;
738 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
739 return SrcReg;
740 assert(0 && "Unrecognized copy instruction!");
741 return 0;
742}
Evan Chengf2fbca62007-11-12 06:35:08 +0000743
744//===----------------------------------------------------------------------===//
745// Register allocator hooks.
746//
747
Evan Chengd70dbb52008-02-22 09:24:50 +0000748/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
749/// allow one) virtual register operand, then its uses are implicitly using
750/// the register. Returns the virtual register.
751unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
752 MachineInstr *MI) const {
753 unsigned RegOp = 0;
754 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
755 MachineOperand &MO = MI->getOperand(i);
756 if (!MO.isRegister() || !MO.isUse())
757 continue;
758 unsigned Reg = MO.getReg();
759 if (Reg == 0 || Reg == li.reg)
760 continue;
761 // FIXME: For now, only remat MI with at most one register operand.
762 assert(!RegOp &&
763 "Can't rematerialize instruction with multiple register operand!");
764 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000765#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +0000766 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000767#endif
Evan Chengd70dbb52008-02-22 09:24:50 +0000768 }
769 return RegOp;
770}
771
772/// isValNoAvailableAt - Return true if the val# of the specified interval
773/// which reaches the given instruction also reaches the specified use index.
774bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
775 unsigned UseIdx) const {
776 unsigned Index = getInstructionIndex(MI);
777 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
778 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
779 return UI != li.end() && UI->valno == ValNo;
780}
781
Evan Chengf2fbca62007-11-12 06:35:08 +0000782/// isReMaterializable - Returns true if the definition MI of the specified
783/// val# of the specified interval is re-materializable.
784bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000785 const VNInfo *ValNo, MachineInstr *MI,
786 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000787 if (DisableReMat)
788 return false;
789
Evan Cheng20ccded2008-03-15 00:19:36 +0000790 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000791 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000792
793 int FrameIdx = 0;
794 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000795 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000796 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
797 // this but remember this is not safe to fold into a two-address
798 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000799 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000800 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000801
Dan Gohman6d69ba82008-07-25 00:02:30 +0000802 // If the target-specific rules don't identify an instruction as
803 // being trivially rematerializable, use some target-independent
804 // rules.
805 if (!MI->getDesc().isRematerializable() ||
806 !tii_->isTriviallyReMaterializable(MI)) {
Dan Gohman4c8f8702008-07-25 15:08:37 +0000807 if (!EnableAggressiveRemat)
808 return false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000809
Dan Gohman6d69ba82008-07-25 00:02:30 +0000810 // If the instruction access memory but the memoperands have been lost,
811 // we can't analyze it.
812 const TargetInstrDesc &TID = MI->getDesc();
813 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
814 return false;
815
816 // Avoid instructions obviously unsafe for remat.
817 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
818 return false;
819
820 // If the instruction accesses memory and the memory could be non-constant,
821 // assume the instruction is not rematerializable.
822 for (alist<MachineMemOperand>::const_iterator I = MI->memoperands_begin(),
823 E = MI->memoperands_end(); I != E; ++I) {
824 const MachineMemOperand &MMO = *I;
825 if (MMO.isVolatile() || MMO.isStore())
826 return false;
827 const Value *V = MMO.getValue();
828 if (!V)
829 return false;
830 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
831 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chengd70dbb52008-02-22 09:24:50 +0000832 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000833 } else if (!aa_->pointsToConstantMemory(V))
834 return false;
835 }
836
837 // If any of the registers accessed are non-constant, conservatively assume
838 // the instruction is not rematerializable.
839 unsigned ImpUse = 0;
840 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
841 const MachineOperand &MO = MI->getOperand(i);
842 if (MO.isReg()) {
843 unsigned Reg = MO.getReg();
844 if (Reg == 0)
845 continue;
846 if (TargetRegisterInfo::isPhysicalRegister(Reg))
847 return false;
848
849 // Only allow one def, and that in the first operand.
850 if (MO.isDef() != (i == 0))
851 return false;
852
853 // Only allow constant-valued registers.
854 bool IsLiveIn = mri_->isLiveIn(Reg);
855 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
856 E = mri_->def_end();
857
858 // For the def, it should be the only def.
859 if (MO.isDef() && (next(I) != E || IsLiveIn))
860 return false;
861
862 if (MO.isUse()) {
863 // Only allow one use other register use, as that's all the
864 // remat mechanisms support currently.
865 if (Reg != li.reg) {
866 if (ImpUse == 0)
867 ImpUse = Reg;
868 else if (Reg != ImpUse)
869 return false;
870 }
871 // For uses, there should be only one associate def.
872 if (I != E && (next(I) != E || IsLiveIn))
873 return false;
874 }
Evan Chengd70dbb52008-02-22 09:24:50 +0000875 }
876 }
Evan Cheng5ef3a042007-12-06 00:01:56 +0000877 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000878
Dan Gohman6d69ba82008-07-25 00:02:30 +0000879 unsigned ImpUse = getReMatImplicitUse(li, MI);
880 if (ImpUse) {
881 const LiveInterval &ImpLi = getInterval(ImpUse);
882 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
883 re = mri_->use_end(); ri != re; ++ri) {
884 MachineInstr *UseMI = &*ri;
885 unsigned UseIdx = getInstructionIndex(UseMI);
886 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
887 continue;
888 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
889 return false;
890 }
891 }
892 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000893}
894
895/// isReMaterializable - Returns true if every definition of MI of every
896/// val# of the specified interval is re-materializable.
897bool LiveIntervals::isReMaterializable(const LiveInterval &li, bool &isLoad) {
898 isLoad = false;
899 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
900 i != e; ++i) {
901 const VNInfo *VNI = *i;
902 unsigned DefIdx = VNI->def;
903 if (DefIdx == ~1U)
904 continue; // Dead val#.
905 // Is the def for the val# rematerializable?
906 if (DefIdx == ~0u)
907 return false;
908 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
909 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000910 if (!ReMatDefMI ||
911 !isReMaterializable(li, VNI, ReMatDefMI, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +0000912 return false;
913 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +0000914 }
915 return true;
916}
917
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000918/// FilterFoldedOps - Filter out two-address use operands. Return
919/// true if it finds any issue with the operands that ought to prevent
920/// folding.
921static bool FilterFoldedOps(MachineInstr *MI,
922 SmallVector<unsigned, 2> &Ops,
923 unsigned &MRInfo,
924 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000925 const TargetInstrDesc &TID = MI->getDesc();
Evan Cheng6e141fd2007-12-12 23:12:09 +0000926
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000927 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +0000928 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
929 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +0000930 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +0000931 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +0000932 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000933 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +0000934 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +0000935 MRInfo |= (unsigned)VirtRegMap::isMod;
936 else {
937 // Filter out two-address use operand(s).
Evan Chengd70dbb52008-02-22 09:24:50 +0000938 if (!MO.isImplicit() &&
939 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengaee4af62007-12-02 08:30:39 +0000940 MRInfo = VirtRegMap::isModRef;
941 continue;
942 }
943 MRInfo |= (unsigned)VirtRegMap::isRef;
944 }
945 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +0000946 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000947 return false;
948}
949
950
951/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
952/// slot / to reg or any rematerialized load into ith operand of specified
953/// MI. If it is successul, MI is updated with the newly created MI and
954/// returns true.
955bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
956 VirtRegMap &vrm, MachineInstr *DefMI,
957 unsigned InstrIdx,
958 SmallVector<unsigned, 2> &Ops,
959 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000960 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +0000961 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000962 RemoveMachineInstrFromMaps(MI);
963 vrm.RemoveMachineInstrFromMaps(MI);
964 MI->eraseFromParent();
965 ++numFolds;
966 return true;
967 }
968
969 // Filter the list of operand indexes that are to be folded. Abort if
970 // any operand will prevent folding.
971 unsigned MRInfo = 0;
972 SmallVector<unsigned, 2> FoldOps;
973 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
974 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +0000975
Evan Cheng427f4c12008-03-31 23:19:51 +0000976 // The only time it's safe to fold into a two address instruction is when
977 // it's folding reload and spill from / into a spill stack slot.
978 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +0000979 return false;
980
Evan Chengf2f8c2a2008-02-08 22:05:27 +0000981 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
982 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +0000983 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +0000984 // Remember this instruction uses the spill slot.
985 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
986
Evan Chengf2fbca62007-11-12 06:35:08 +0000987 // Attempt to fold the memory reference into the instruction. If
988 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +0000989 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +0000990 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +0000991 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +0000992 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000993 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +0000994 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +0000995 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +0000996 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
997 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +0000998 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000999 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +00001000 return true;
1001 }
1002 return false;
1003}
1004
Evan Cheng018f9b02007-12-05 03:22:34 +00001005/// canFoldMemoryOperand - Returns true if the specified load / store
1006/// folding is possible.
1007bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001008 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001009 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001010 // Filter the list of operand indexes that are to be folded. Abort if
1011 // any operand will prevent folding.
1012 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001013 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001014 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1015 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001016
Evan Cheng3c75ba82008-04-01 21:37:32 +00001017 // It's only legal to remat for a use, not a def.
1018 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001019 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001020
Evan Chengd70dbb52008-02-22 09:24:50 +00001021 return tii_->canFoldMemoryOperand(MI, FoldOps);
1022}
1023
Evan Cheng81a03822007-11-17 00:40:40 +00001024bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1025 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1026 for (LiveInterval::Ranges::const_iterator
1027 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1028 std::vector<IdxMBBPair>::const_iterator II =
1029 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1030 if (II == Idx2MBBMap.end())
1031 continue;
1032 if (I->end > II->first) // crossing a MBB.
1033 return false;
1034 MBBs.insert(II->second);
1035 if (MBBs.size() > 1)
1036 return false;
1037 }
1038 return true;
1039}
1040
Evan Chengd70dbb52008-02-22 09:24:50 +00001041/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1042/// interval on to-be re-materialized operands of MI) with new register.
1043void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1044 MachineInstr *MI, unsigned NewVReg,
1045 VirtRegMap &vrm) {
1046 // There is an implicit use. That means one of the other operand is
1047 // being remat'ed and the remat'ed instruction has li.reg as an
1048 // use operand. Make sure we rewrite that as well.
1049 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1050 MachineOperand &MO = MI->getOperand(i);
1051 if (!MO.isRegister())
1052 continue;
1053 unsigned Reg = MO.getReg();
1054 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1055 continue;
1056 if (!vrm.isReMaterialized(Reg))
1057 continue;
1058 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001059 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1060 if (UseMO)
1061 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001062 }
1063}
1064
Evan Chengf2fbca62007-11-12 06:35:08 +00001065/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1066/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001067bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001068rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1069 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001070 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001071 unsigned Slot, int LdSlot,
1072 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001073 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001074 const TargetRegisterClass* rc,
1075 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001076 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001077 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001078 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001079 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
1080 MachineBasicBlock *MBB = MI->getParent();
1081 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng018f9b02007-12-05 03:22:34 +00001082 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001083 RestartInstruction:
1084 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1085 MachineOperand& mop = MI->getOperand(i);
1086 if (!mop.isRegister())
1087 continue;
1088 unsigned Reg = mop.getReg();
1089 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001090 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001091 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001092 if (Reg != li.reg)
1093 continue;
1094
1095 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001096 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001097 int FoldSlot = Slot;
1098 if (DefIsReMat) {
1099 // If this is the rematerializable definition MI itself and
1100 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001101 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001102 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1103 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001104 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001105 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001106 MI->eraseFromParent();
1107 break;
1108 }
1109
1110 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001111 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001112 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001113 if (isLoad) {
1114 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1115 FoldSS = isLoadSS;
1116 FoldSlot = LdSlot;
1117 }
1118 }
1119
Evan Chengf2fbca62007-11-12 06:35:08 +00001120 // Scan all of the operands of this instruction rewriting operands
1121 // to use NewVReg instead of li.reg as appropriate. We do this for
1122 // two reasons:
1123 //
1124 // 1. If the instr reads the same spilled vreg multiple times, we
1125 // want to reuse the NewVReg.
1126 // 2. If the instr is a two-addr instruction, we are required to
1127 // keep the src/dst regs pinned.
1128 //
1129 // Keep track of whether we replace a use and/or def so that we can
1130 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001131
Evan Cheng81a03822007-11-17 00:40:40 +00001132 HasUse = mop.isUse();
1133 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001134 SmallVector<unsigned, 2> Ops;
1135 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001136 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001137 const MachineOperand &MOj = MI->getOperand(j);
1138 if (!MOj.isRegister())
Evan Chengf2fbca62007-11-12 06:35:08 +00001139 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001140 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001141 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001142 continue;
1143 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001144 Ops.push_back(j);
1145 HasUse |= MOj.isUse();
1146 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001147 }
1148 }
1149
Evan Cheng79a796c2008-07-12 01:56:02 +00001150 if (HasUse && !li.liveAt(getUseIndex(index)))
1151 // Must be defined by an implicit def. It should not be spilled. Note,
1152 // this is for correctness reason. e.g.
1153 // 8 %reg1024<def> = IMPLICIT_DEF
1154 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1155 // The live range [12, 14) are not part of the r1024 live interval since
1156 // it's defined by an implicit def. It will not conflicts with live
1157 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001158 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001159 // the INSERT_SUBREG and both target registers that would overlap.
1160 HasUse = false;
1161
Evan Cheng9c3c2212008-06-06 07:54:39 +00001162 // Update stack slot spill weight if we are splitting.
Evan Chengc3417602008-06-21 06:45:54 +00001163 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001164 if (!TrySplit)
1165 SSWeight += Weight;
1166
1167 if (!TryFold)
1168 CanFold = false;
1169 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001170 // Do not fold load / store here if we are splitting. We'll find an
1171 // optimal point to insert a load / store later.
1172 if (!TrySplit) {
1173 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1174 Ops, FoldSS, FoldSlot, Reg)) {
1175 // Folding the load/store can completely change the instruction in
1176 // unpredictable ways, rescan it from the beginning.
1177 HasUse = false;
1178 HasDef = false;
1179 CanFold = false;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001180 if (isRemoved(MI)) {
1181 SSWeight -= Weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001182 break;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001183 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001184 goto RestartInstruction;
1185 }
1186 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001187 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001188 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001189 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001190 }
Evan Chengcddbb832007-11-30 21:23:43 +00001191
1192 // Create a new virtual register for the spill interval.
1193 bool CreatedNewVReg = false;
1194 if (NewVReg == 0) {
Evan Chengd70dbb52008-02-22 09:24:50 +00001195 NewVReg = mri_->createVirtualRegister(rc);
Evan Chengcddbb832007-11-30 21:23:43 +00001196 vrm.grow();
1197 CreatedNewVReg = true;
1198 }
1199 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001200 if (mop.isImplicit())
1201 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001202
1203 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001204 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1205 MachineOperand &mopj = MI->getOperand(Ops[j]);
1206 mopj.setReg(NewVReg);
1207 if (mopj.isImplicit())
1208 rewriteImplicitOps(li, MI, NewVReg, vrm);
1209 }
Evan Chengcddbb832007-11-30 21:23:43 +00001210
Evan Cheng81a03822007-11-17 00:40:40 +00001211 if (CreatedNewVReg) {
1212 if (DefIsReMat) {
1213 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001214 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001215 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001216 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001217 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001218 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001219 }
1220 if (!CanDelete || (HasUse && HasDef)) {
1221 // If this is a two-addr instruction then its use operands are
1222 // rematerializable but its def is not. It should be assigned a
1223 // stack slot.
1224 vrm.assignVirt2StackSlot(NewVReg, Slot);
1225 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001226 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001227 vrm.assignVirt2StackSlot(NewVReg, Slot);
1228 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001229 } else if (HasUse && HasDef &&
1230 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1231 // If this interval hasn't been assigned a stack slot (because earlier
1232 // def is a deleted remat def), do it now.
1233 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1234 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001235 }
1236
Evan Cheng313d4b82008-02-23 00:33:04 +00001237 // Re-matting an instruction with virtual register use. Add the
1238 // register as an implicit use on the use MI.
1239 if (DefIsReMat && ImpUse)
1240 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1241
Evan Chengf2fbca62007-11-12 06:35:08 +00001242 // create a new register interval for this spill / remat.
1243 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001244 if (CreatedNewVReg) {
1245 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001246 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001247 if (TrySplit)
1248 vrm.setIsSplitFromReg(NewVReg, li.reg);
1249 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001250
1251 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001252 if (CreatedNewVReg) {
1253 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1254 nI.getNextValue(~0U, 0, VNInfoAllocator));
1255 DOUT << " +" << LR;
1256 nI.addRange(LR);
1257 } else {
1258 // Extend the split live interval to this def / use.
1259 unsigned End = getUseIndex(index)+1;
1260 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1261 nI.getValNumInfo(nI.getNumValNums()-1));
1262 DOUT << " +" << LR;
1263 nI.addRange(LR);
1264 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001265 }
1266 if (HasDef) {
1267 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1268 nI.getNextValue(~0U, 0, VNInfoAllocator));
1269 DOUT << " +" << LR;
1270 nI.addRange(LR);
1271 }
Evan Cheng81a03822007-11-17 00:40:40 +00001272
Evan Chengf2fbca62007-11-12 06:35:08 +00001273 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001274 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001275 DOUT << '\n';
1276 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001277 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001278}
Evan Cheng81a03822007-11-17 00:40:40 +00001279bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001280 const VNInfo *VNI,
1281 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001282 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001283 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1284 unsigned KillIdx = VNI->kills[j];
1285 if (KillIdx > Idx && KillIdx < End)
1286 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001287 }
1288 return false;
1289}
1290
Evan Cheng063284c2008-02-21 00:34:19 +00001291/// RewriteInfo - Keep track of machine instrs that will be rewritten
1292/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001293namespace {
1294 struct RewriteInfo {
1295 unsigned Index;
1296 MachineInstr *MI;
1297 bool HasUse;
1298 bool HasDef;
1299 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1300 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1301 };
Evan Cheng063284c2008-02-21 00:34:19 +00001302
Dan Gohman844731a2008-05-13 00:00:25 +00001303 struct RewriteInfoCompare {
1304 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1305 return LHS.Index < RHS.Index;
1306 }
1307 };
1308}
Evan Cheng063284c2008-02-21 00:34:19 +00001309
Evan Chengf2fbca62007-11-12 06:35:08 +00001310void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001311rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001312 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001313 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001314 unsigned Slot, int LdSlot,
1315 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001316 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001317 const TargetRegisterClass* rc,
1318 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001319 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001320 BitVector &SpillMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001321 std::map<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001322 BitVector &RestoreMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001323 std::map<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1324 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001325 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001326 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001327 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001328 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001329 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001330
Evan Cheng063284c2008-02-21 00:34:19 +00001331 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001332 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001333 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001334 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1335 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001336 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001337 MachineOperand &O = ri.getOperand();
1338 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001339 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001340 unsigned index = getInstructionIndex(MI);
1341 if (index < start || index >= end)
1342 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001343 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1344 // Must be defined by an implicit def. It should not be spilled. Note,
1345 // this is for correctness reason. e.g.
1346 // 8 %reg1024<def> = IMPLICIT_DEF
1347 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1348 // The live range [12, 14) are not part of the r1024 live interval since
1349 // it's defined by an implicit def. It will not conflicts with live
1350 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001351 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001352 // the INSERT_SUBREG and both target registers that would overlap.
1353 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001354 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1355 }
1356 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1357
Evan Cheng313d4b82008-02-23 00:33:04 +00001358 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001359 // Now rewrite the defs and uses.
1360 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1361 RewriteInfo &rwi = RewriteMIs[i];
1362 ++i;
1363 unsigned index = rwi.Index;
1364 bool MIHasUse = rwi.HasUse;
1365 bool MIHasDef = rwi.HasDef;
1366 MachineInstr *MI = rwi.MI;
1367 // If MI def and/or use the same register multiple times, then there
1368 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001369 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001370 while (i != e && RewriteMIs[i].MI == MI) {
1371 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001372 bool isUse = RewriteMIs[i].HasUse;
1373 if (isUse) ++NumUses;
1374 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001375 MIHasDef |= RewriteMIs[i].HasDef;
1376 ++i;
1377 }
Evan Cheng81a03822007-11-17 00:40:40 +00001378 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001379
Evan Cheng0a891ed2008-05-23 23:00:04 +00001380 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001381 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001382 // register interval's spill weight to HUGE_VALF to prevent it from
1383 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001384 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001385 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001386 }
1387
Evan Cheng063284c2008-02-21 00:34:19 +00001388 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001389 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001390 if (TrySplit) {
Evan Cheng063284c2008-02-21 00:34:19 +00001391 std::map<unsigned,unsigned>::const_iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001392 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001393 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001394 // One common case:
1395 // x = use
1396 // ...
1397 // ...
1398 // def = ...
1399 // = use
1400 // It's better to start a new interval to avoid artifically
1401 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001402 if (MIHasDef && !MIHasUse) {
1403 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001404 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001405 }
1406 }
Evan Chengcada2452007-11-28 01:28:46 +00001407 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001408
1409 bool IsNew = ThisVReg == 0;
1410 if (IsNew) {
1411 // This ends the previous live interval. If all of its def / use
1412 // can be folded, give it a low spill weight.
1413 if (NewVReg && TrySplit && AllCanFold) {
1414 LiveInterval &nI = getOrCreateInterval(NewVReg);
1415 nI.weight /= 10.0F;
1416 }
1417 AllCanFold = true;
1418 }
1419 NewVReg = ThisVReg;
1420
Evan Cheng81a03822007-11-17 00:40:40 +00001421 bool HasDef = false;
1422 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001423 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001424 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1425 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1426 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1427 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001428 if (!HasDef && !HasUse)
1429 continue;
1430
Evan Cheng018f9b02007-12-05 03:22:34 +00001431 AllCanFold &= CanFold;
1432
Evan Cheng81a03822007-11-17 00:40:40 +00001433 // Update weight of spill interval.
1434 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001435 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001436 // The spill weight is now infinity as it cannot be spilled again.
1437 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001438 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001439 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001440
1441 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001442 if (HasDef) {
1443 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001444 bool HasKill = false;
1445 if (!HasUse)
1446 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1447 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001448 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001449 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001450 if (VNI)
1451 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1452 }
Evan Chenge3110d02007-12-01 04:42:39 +00001453 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
1454 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001455 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001456 if (SII == SpillIdxes.end()) {
1457 std::vector<SRInfo> S;
1458 S.push_back(SRInfo(index, NewVReg, true));
1459 SpillIdxes.insert(std::make_pair(MBBId, S));
1460 } else if (SII->second.back().vreg != NewVReg) {
1461 SII->second.push_back(SRInfo(index, NewVReg, true));
1462 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001463 // If there is an earlier def and this is a two-address
1464 // instruction, then it's not possible to fold the store (which
1465 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001466 SRInfo &Info = SII->second.back();
1467 Info.index = index;
1468 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001469 }
1470 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001471 } else if (SII != SpillIdxes.end() &&
1472 SII->second.back().vreg == NewVReg &&
1473 (int)index > SII->second.back().index) {
1474 // There is an earlier def that's not killed (must be two-address).
1475 // The spill is no longer needed.
1476 SII->second.pop_back();
1477 if (SII->second.empty()) {
1478 SpillIdxes.erase(MBBId);
1479 SpillMBBs.reset(MBBId);
1480 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001481 }
1482 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001483 }
1484
1485 if (HasUse) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001486 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001487 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001488 if (SII != SpillIdxes.end() &&
1489 SII->second.back().vreg == NewVReg &&
1490 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001491 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001492 SII->second.back().canFold = false;
1493 std::map<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001494 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001495 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001496 // If we are splitting live intervals, only fold if it's the first
1497 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001498 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001499 else if (IsNew) {
1500 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001501 if (RII == RestoreIdxes.end()) {
1502 std::vector<SRInfo> Infos;
1503 Infos.push_back(SRInfo(index, NewVReg, true));
1504 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1505 } else {
1506 RII->second.push_back(SRInfo(index, NewVReg, true));
1507 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001508 RestoreMBBs.set(MBBId);
1509 }
1510 }
1511
1512 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001513 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001514 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001515 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001516
1517 if (NewVReg && TrySplit && AllCanFold) {
1518 // If all of its def / use can be folded, give it a low spill weight.
1519 LiveInterval &nI = getOrCreateInterval(NewVReg);
1520 nI.weight /= 10.0F;
1521 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001522}
1523
Evan Cheng1953d0c2007-11-29 10:12:14 +00001524bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1525 BitVector &RestoreMBBs,
1526 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1527 if (!RestoreMBBs[Id])
1528 return false;
1529 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1530 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1531 if (Restores[i].index == index &&
1532 Restores[i].vreg == vr &&
1533 Restores[i].canFold)
1534 return true;
1535 return false;
1536}
1537
1538void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1539 BitVector &RestoreMBBs,
1540 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1541 if (!RestoreMBBs[Id])
1542 return;
1543 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1544 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1545 if (Restores[i].index == index && Restores[i].vreg)
1546 Restores[i].index = -1;
1547}
Evan Cheng81a03822007-11-17 00:40:40 +00001548
Evan Cheng4cce6b42008-04-11 17:53:36 +00001549/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1550/// spilled and create empty intervals for their uses.
1551void
1552LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1553 const TargetRegisterClass* rc,
1554 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001555 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1556 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001557 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001558 MachineInstr *MI = &*ri;
1559 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001560 if (O.isDef()) {
1561 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1562 "Register def was not rewritten?");
1563 RemoveMachineInstrFromMaps(MI);
1564 vrm.RemoveMachineInstrFromMaps(MI);
1565 MI->eraseFromParent();
1566 } else {
1567 // This must be an use of an implicit_def so it's not part of the live
1568 // interval. Create a new empty live interval for it.
1569 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1570 unsigned NewVReg = mri_->createVirtualRegister(rc);
1571 vrm.grow();
1572 vrm.setIsImplicitlyDefined(NewVReg);
1573 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1574 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1575 MachineOperand &MO = MI->getOperand(i);
1576 if (MO.isReg() && MO.getReg() == li.reg)
1577 MO.setReg(NewVReg);
1578 }
1579 }
Evan Cheng419852c2008-04-03 16:39:43 +00001580 }
1581}
1582
Evan Cheng81a03822007-11-17 00:40:40 +00001583
Evan Chengf2fbca62007-11-12 06:35:08 +00001584std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001585addIntervalsForSpills(const LiveInterval &li,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001586 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1587 float &SSWeight) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001588 assert(li.weight != HUGE_VALF &&
1589 "attempt to spill already spilled interval!");
1590
1591 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001592 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001593 DOUT << '\n';
1594
Evan Cheng9c3c2212008-06-06 07:54:39 +00001595 // Spill slot weight.
1596 SSWeight = 0.0f;
1597
Evan Cheng81a03822007-11-17 00:40:40 +00001598 // Each bit specify whether it a spill is required in the MBB.
1599 BitVector SpillMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001600 std::map<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001601 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001602 std::map<unsigned, std::vector<SRInfo> > RestoreIdxes;
1603 std::map<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001604 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001605 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001606
1607 unsigned NumValNums = li.getNumValNums();
1608 SmallVector<MachineInstr*, 4> ReMatDefs;
1609 ReMatDefs.resize(NumValNums, NULL);
1610 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1611 ReMatOrigDefs.resize(NumValNums, NULL);
1612 SmallVector<int, 4> ReMatIds;
1613 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1614 BitVector ReMatDelete(NumValNums);
1615 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1616
Evan Cheng81a03822007-11-17 00:40:40 +00001617 // Spilling a split live interval. It cannot be split any further. Also,
1618 // it's also guaranteed to be a single val# / range interval.
1619 if (vrm.getPreSplitReg(li.reg)) {
1620 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001621 // Unset the split kill marker on the last use.
1622 unsigned KillIdx = vrm.getKillPoint(li.reg);
1623 if (KillIdx) {
1624 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1625 assert(KillMI && "Last use disappeared?");
1626 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1627 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001628 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001629 }
Evan Chengadf85902007-12-05 09:51:10 +00001630 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001631 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1632 Slot = vrm.getStackSlot(li.reg);
1633 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1634 MachineInstr *ReMatDefMI = DefIsReMat ?
1635 vrm.getReMaterializedMI(li.reg) : NULL;
1636 int LdSlot = 0;
1637 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1638 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001639 (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001640 bool IsFirstRange = true;
1641 for (LiveInterval::Ranges::const_iterator
1642 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1643 // If this is a split live interval with multiple ranges, it means there
1644 // are two-address instructions that re-defined the value. Only the
1645 // first def can be rematerialized!
1646 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001647 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001648 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1649 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001650 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001651 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001652 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001653 } else {
1654 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1655 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001656 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001657 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001658 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001659 }
1660 IsFirstRange = false;
1661 }
Evan Cheng419852c2008-04-03 16:39:43 +00001662
Evan Cheng9c3c2212008-06-06 07:54:39 +00001663 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng4cce6b42008-04-11 17:53:36 +00001664 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001665 return NewLIs;
1666 }
1667
1668 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001669 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1670 TrySplit = false;
1671 if (TrySplit)
1672 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001673 bool NeedStackSlot = false;
1674 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1675 i != e; ++i) {
1676 const VNInfo *VNI = *i;
1677 unsigned VN = VNI->id;
1678 unsigned DefIdx = VNI->def;
1679 if (DefIdx == ~1U)
1680 continue; // Dead val#.
1681 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001682 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1683 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001684 bool dummy;
1685 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001686 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001687 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001688 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001689 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1690 ClonedMIs.push_back(Clone);
1691 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001692
1693 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001694 if (VNI->hasPHIKill) {
1695 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001696 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001697 CanDelete = false;
1698 // Need a stack slot if there is any live range where uses cannot be
1699 // rematerialized.
1700 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001701 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001702 if (CanDelete)
1703 ReMatDelete.set(VN);
1704 } else {
1705 // Need a stack slot if there is any live range where uses cannot be
1706 // rematerialized.
1707 NeedStackSlot = true;
1708 }
1709 }
1710
1711 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001712 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001713 Slot = vrm.assignVirt2StackSlot(li.reg);
1714
1715 // Create new intervals and rewrite defs and uses.
1716 for (LiveInterval::Ranges::const_iterator
1717 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001718 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1719 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1720 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001721 bool CanDelete = ReMatDelete[I->valno->id];
1722 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001723 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001724 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001725 (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001726 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001727 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001728 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001729 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001730 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengf2fbca62007-11-12 06:35:08 +00001731 }
1732
Evan Cheng0cbb1162007-11-29 01:06:25 +00001733 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001734 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001735 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001736 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00001737 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001738
Evan Chengb50bb8c2007-12-05 08:16:32 +00001739 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001740 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001741 if (NeedStackSlot) {
1742 int Id = SpillMBBs.find_first();
1743 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001744 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1745 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001746 std::vector<SRInfo> &spills = SpillIdxes[Id];
1747 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1748 int index = spills[i].index;
1749 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001750 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001751 bool isReMat = vrm.isReMaterialized(VReg);
1752 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001753 bool CanFold = false;
1754 bool FoundUse = false;
1755 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001756 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001757 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001758 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1759 MachineOperand &MO = MI->getOperand(j);
1760 if (!MO.isRegister() || MO.getReg() != VReg)
1761 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001762
1763 Ops.push_back(j);
1764 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001765 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001766 if (isReMat ||
1767 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1768 RestoreMBBs, RestoreIdxes))) {
1769 // MI has two-address uses of the same register. If the use
1770 // isn't the first and only use in the BB, then we can't fold
1771 // it. FIXME: Move this to rewriteInstructionsForSpills.
1772 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001773 break;
1774 }
Evan Chengaee4af62007-12-02 08:30:39 +00001775 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001776 }
1777 }
1778 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001779 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001780 if (CanFold && !Ops.empty()) {
1781 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001782 Folded = true;
Evan Chengf38d14f2007-12-05 09:05:34 +00001783 if (FoundUse > 0) {
Evan Chengaee4af62007-12-02 08:30:39 +00001784 // Also folded uses, do not issue a load.
1785 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00001786 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
1787 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001788 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00001789 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001790 }
1791
Evan Cheng7e073ba2008-04-09 20:57:25 +00001792 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00001793 if (!Folded) {
1794 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
1795 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00001796 if (!MI->registerDefIsDead(nI.reg))
1797 // No need to spill a dead def.
1798 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001799 if (isKill)
1800 AddedKill.insert(&nI);
1801 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001802
1803 // Update spill slot weight.
1804 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001805 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001806 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001807 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001808 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001809 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001810
Evan Cheng1953d0c2007-11-29 10:12:14 +00001811 int Id = RestoreMBBs.find_first();
1812 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001813 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1814 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
1815
Evan Cheng1953d0c2007-11-29 10:12:14 +00001816 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1817 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
1818 int index = restores[i].index;
1819 if (index == -1)
1820 continue;
1821 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001822 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001823 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001824 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001825 bool CanFold = false;
1826 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001827 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001828 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001829 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1830 MachineOperand &MO = MI->getOperand(j);
1831 if (!MO.isRegister() || MO.getReg() != VReg)
1832 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001833
Evan Cheng0cbb1162007-11-29 01:06:25 +00001834 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00001835 // If this restore were to be folded, it would have been folded
1836 // already.
1837 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00001838 break;
1839 }
Evan Chengaee4af62007-12-02 08:30:39 +00001840 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00001841 }
1842 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001843
1844 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001845 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001846 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001847 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00001848 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
1849 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001850 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
1851 int LdSlot = 0;
1852 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1853 // If the rematerializable def is a load, also try to fold it.
Chris Lattner749c6f62008-01-07 07:27:27 +00001854 if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00001855 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1856 Ops, isLoadSS, LdSlot, VReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001857 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
1858 if (ImpUse) {
1859 // Re-matting an instruction with virtual register use. Add the
1860 // register as an implicit use on the use MI and update the register
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001861 // interval's spill weight to HUGE_VALF to prevent it from being
1862 // spilled.
Evan Chengd70dbb52008-02-22 09:24:50 +00001863 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001864 ImpLi.weight = HUGE_VALF;
Evan Chengd70dbb52008-02-22 09:24:50 +00001865 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1866 }
Evan Chengaee4af62007-12-02 08:30:39 +00001867 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001868 }
1869 // If folding is not possible / failed, then tell the spiller to issue a
1870 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00001871 if (Folded)
1872 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001873 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00001874 vrm.addRestorePoint(VReg, MI);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001875
1876 // Update spill slot weight.
1877 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001878 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Cheng81a03822007-11-17 00:40:40 +00001879 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001880 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00001881 }
1882
Evan Chengb50bb8c2007-12-05 08:16:32 +00001883 // Finalize intervals: add kills, finalize spill weights, and filter out
1884 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00001885 std::vector<LiveInterval*> RetNewLIs;
1886 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
1887 LiveInterval *LI = NewLIs[i];
1888 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00001889 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001890 if (!AddedKill.count(LI)) {
1891 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00001892 unsigned LastUseIdx = getBaseIndex(LR->end);
1893 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00001894 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001895 assert(UseIdx != -1);
Evan Chengd70dbb52008-02-22 09:24:50 +00001896 if (LastUse->getOperand(UseIdx).isImplicit() ||
1897 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chengb50bb8c2007-12-05 08:16:32 +00001898 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00001899 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00001900 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00001901 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001902 RetNewLIs.push_back(LI);
1903 }
1904 }
Evan Cheng81a03822007-11-17 00:40:40 +00001905
Evan Cheng4cce6b42008-04-11 17:53:36 +00001906 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00001907 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00001908}
Evan Cheng676dd7c2008-03-11 07:19:34 +00001909
1910/// hasAllocatableSuperReg - Return true if the specified physical register has
1911/// any super register that's allocatable.
1912bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
1913 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
1914 if (allocatableRegs_[*AS] && hasInterval(*AS))
1915 return true;
1916 return false;
1917}
1918
1919/// getRepresentativeReg - Find the largest super register of the specified
1920/// physical register.
1921unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
1922 // Find the largest super-register that is allocatable.
1923 unsigned BestReg = Reg;
1924 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
1925 unsigned SuperReg = *AS;
1926 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
1927 BestReg = SuperReg;
1928 break;
1929 }
1930 }
1931 return BestReg;
1932}
1933
1934/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
1935/// specified interval that conflicts with the specified physical register.
1936unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
1937 unsigned PhysReg) const {
1938 unsigned NumConflicts = 0;
1939 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
1940 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1941 E = mri_->reg_end(); I != E; ++I) {
1942 MachineOperand &O = I.getOperand();
1943 MachineInstr *MI = O.getParent();
1944 unsigned Index = getInstructionIndex(MI);
1945 if (pli.liveAt(Index))
1946 ++NumConflicts;
1947 }
1948 return NumConflicts;
1949}
1950
1951/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
1952/// around all defs and uses of the specified interval.
1953void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
1954 unsigned PhysReg, VirtRegMap &vrm) {
1955 unsigned SpillReg = getRepresentativeReg(PhysReg);
1956
1957 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
1958 // If there are registers which alias PhysReg, but which are not a
1959 // sub-register of the chosen representative super register. Assert
1960 // since we can't handle it yet.
1961 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
1962 tri_->isSuperRegister(*AS, SpillReg));
1963
1964 LiveInterval &pli = getInterval(SpillReg);
1965 SmallPtrSet<MachineInstr*, 8> SeenMIs;
1966 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1967 E = mri_->reg_end(); I != E; ++I) {
1968 MachineOperand &O = I.getOperand();
1969 MachineInstr *MI = O.getParent();
1970 if (SeenMIs.count(MI))
1971 continue;
1972 SeenMIs.insert(MI);
1973 unsigned Index = getInstructionIndex(MI);
1974 if (pli.liveAt(Index)) {
1975 vrm.addEmergencySpill(SpillReg, MI);
1976 pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1977 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
1978 if (!hasInterval(*AS))
1979 continue;
1980 LiveInterval &spli = getInterval(*AS);
1981 if (spli.liveAt(Index))
1982 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1983 }
1984 }
1985 }
1986}
Owen Andersonc4dc1322008-06-05 17:15:43 +00001987
1988LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1989 MachineInstr* startInst) {
1990 LiveInterval& Interval = getOrCreateInterval(reg);
1991 VNInfo* VN = Interval.getNextValue(
1992 getInstructionIndex(startInst) + InstrSlots::DEF,
1993 startInst, getVNInfoAllocator());
1994 VN->hasPHIKill = true;
1995 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
1996 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
1997 getMBBEndIdx(startInst->getParent()) + 1, VN);
1998 Interval.addRange(LR);
1999
2000 return LR;
2001}