blob: 295a1615b69d3c59a1683eba1a71900227ecd4dc [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"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000022#include "llvm/CodeGen/LiveVariables.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000025#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000027#include "llvm/CodeGen/Passes.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000028#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000029#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000036#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000037using namespace llvm;
38
Dan Gohman844731a2008-05-13 00:00:25 +000039// Hidden options for help debugging.
40static cl::opt<bool> DisableReMat("disable-rematerialization",
41 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000042
Dan Gohman844731a2008-05-13 00:00:25 +000043static cl::opt<bool> SplitAtBB("split-intervals-at-bb",
44 cl::init(true), cl::Hidden);
45static cl::opt<int> SplitLimit("split-limit",
46 cl::init(-1), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000047
Chris Lattnercd3245a2006-12-19 22:41:21 +000048STATISTIC(numIntervals, "Number of original intervals");
49STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
Evan Cheng0cbb1162007-11-29 01:06:25 +000050STATISTIC(numFolds , "Number of loads/stores folded into instructions");
51STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000052
Devang Patel19974732007-05-03 01:11:54 +000053char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000054static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000055
Chris Lattnerf7da2c72006-08-24 22:43:55 +000056void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
David Greene25133302007-06-08 17:18:56 +000057 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000058 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000059 AU.addPreservedID(MachineLoopInfoID);
60 AU.addPreservedID(MachineDominatorsID);
Owen Andersonfcc63502008-05-29 18:35:21 +000061 AU.addPreservedID(PHIEliminationID);
62 AU.addRequiredID(PHIEliminationID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000063 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000064 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000065}
66
Chris Lattnerf7da2c72006-08-24 22:43:55 +000067void LiveIntervals::releaseMemory() {
Evan Cheng3f32d652008-06-04 09:18:41 +000068 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000069 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000070 mi2iMap_.clear();
71 i2miMap_.clear();
72 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000073 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
74 VNInfoAllocator.Reset();
Evan Cheng1ed99222008-07-19 00:37:25 +000075 while (!ClonedMIs.empty()) {
76 MachineInstr *MI = ClonedMIs.back();
77 ClonedMIs.pop_back();
78 mf_->DeleteMachineInstr(MI);
79 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000080}
81
Owen Anderson80b3ce62008-05-28 20:54:50 +000082void LiveIntervals::computeNumbering() {
83 Index2MiMap OldI2MI = i2miMap_;
84
85 Idx2MBBMap.clear();
86 MBB2IdxMap.clear();
87 mi2iMap_.clear();
88 i2miMap_.clear();
89
Owen Andersona1566f22008-07-22 22:46:49 +000090 FunctionSize = 0;
91
Chris Lattner428b92e2006-09-15 03:57:23 +000092 // Number MachineInstrs and MachineBasicBlocks.
93 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +000094 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +000095
96 unsigned MIIndex = 0;
97 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
98 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +000099 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000100
Chris Lattner428b92e2006-09-15 03:57:23 +0000101 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
102 I != E; ++I) {
103 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000104 assert(inserted && "multiple MachineInstr -> index mappings");
Chris Lattner428b92e2006-09-15 03:57:23 +0000105 i2miMap_.push_back(I);
106 MIIndex += InstrSlots::NUM;
Owen Andersona1566f22008-07-22 22:46:49 +0000107
108 FunctionSize++;
Owen Anderson29b03992008-06-19 05:29:34 +0000109 }
110
111 if (StartIdx == MIIndex) {
112 // Empty MBB
Owen Anderson1fbb4542008-06-16 16:58:24 +0000113 MIIndex += InstrSlots::NUM;
114 i2miMap_.push_back(0);
Owen Anderson35578012008-06-16 07:10:49 +0000115 }
Owen Anderson1fbb4542008-06-16 16:58:24 +0000116 // Set the MBB2IdxMap entry for this MBB.
117 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
118 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000119 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000120 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000121
122 if (!OldI2MI.empty())
Owen Anderson29b03992008-06-19 05:29:34 +0000123 for (iterator I = begin(), E = end(); I != E; ++I)
124 for (LiveInterval::iterator LI = I->second.begin(), LE = I->second.end();
125 LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000126
Owen Anderson7eec0c22008-05-29 23:01:22 +0000127 // Remap the start index of the live range to the corresponding new
128 // number, or our best guess at what it _should_ correspond to if the
129 // original instruction has been erased. This is either the following
130 // instruction or its predecessor.
131 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson29b03992008-06-19 05:29:34 +0000132 if (OldI2MI[LI->start / InstrSlots::NUM])
133 LI->start = mi2iMap_[OldI2MI[LI->start / InstrSlots::NUM]] + offset;
134 else {
135 unsigned i = 0;
136 MachineInstr* newInstr = 0;
137 do {
138 newInstr = OldI2MI[LI->start / InstrSlots::NUM + i];
139 i++;
140 } while (!newInstr);
Owen Anderson7eec0c22008-05-29 23:01:22 +0000141
Owen Anderson29b03992008-06-19 05:29:34 +0000142 if (mi2iMap_[newInstr] ==
143 MBB2IdxMap[newInstr->getParent()->getNumber()].first)
144 LI->start = mi2iMap_[newInstr];
145 else
146 LI->start = mi2iMap_[newInstr] - InstrSlots::NUM + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000147 }
148
149 // Remap the ending index in the same way that we remapped the start,
150 // except for the final step where we always map to the immediately
151 // following instruction.
Owen Anderson29b03992008-06-19 05:29:34 +0000152 if (LI->end / InstrSlots::NUM < OldI2MI.size()) {
153 offset = LI->end % InstrSlots::NUM;
154 if (OldI2MI[LI->end / InstrSlots::NUM])
155 LI->end = mi2iMap_[OldI2MI[LI->end / InstrSlots::NUM]] + offset;
156 else {
157 unsigned i = 0;
158 MachineInstr* newInstr = 0;
159 do {
160 newInstr = OldI2MI[LI->end / InstrSlots::NUM + i];
161 i++;
162 } while (!newInstr);
163
164 LI->end = mi2iMap_[newInstr];
165 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000166 } else {
Owen Anderson29b03992008-06-19 05:29:34 +0000167 LI->end = i2miMap_.size() * InstrSlots::NUM;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000168 }
Owen Anderson745825f42008-05-28 22:40:08 +0000169
Owen Anderson7eec0c22008-05-29 23:01:22 +0000170 // Remap the VNInfo def index, which works the same as the
171 // start indices above.
Owen Anderson745825f42008-05-28 22:40:08 +0000172 VNInfo* vni = LI->valno;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000173 offset = vni->def % InstrSlots::NUM;
Owen Anderson29b03992008-06-19 05:29:34 +0000174 if (OldI2MI[vni->def / InstrSlots::NUM])
175 vni->def = mi2iMap_[OldI2MI[vni->def / InstrSlots::NUM]] + offset;
176 else {
177 unsigned i = 0;
178 MachineInstr* newInstr = 0;
179 do {
180 newInstr = OldI2MI[vni->def / InstrSlots::NUM + i];
181 i++;
182 } while (!newInstr);
Owen Anderson7eec0c22008-05-29 23:01:22 +0000183
Owen Anderson29b03992008-06-19 05:29:34 +0000184 if (mi2iMap_[newInstr] ==
185 MBB2IdxMap[newInstr->getParent()->getNumber()].first)
186 vni->def = mi2iMap_[newInstr];
187 else
188 vni->def = mi2iMap_[newInstr] - InstrSlots::NUM + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000189 }
Owen Anderson745825f42008-05-28 22:40:08 +0000190
Owen Anderson7eec0c22008-05-29 23:01:22 +0000191 // Remap the VNInfo kill indices, which works the same as
192 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000193 for (size_t i = 0; i < vni->kills.size(); ++i) {
194 offset = vni->kills[i] % InstrSlots::NUM;
Owen Anderson29b03992008-06-19 05:29:34 +0000195 if (OldI2MI[vni->kills[i] / InstrSlots::NUM])
196 vni->kills[i] = mi2iMap_[OldI2MI[vni->kills[i] / InstrSlots::NUM]] +
197 offset;
198 else {
199 unsigned e = 0;
200 MachineInstr* newInstr = 0;
201 do {
202 newInstr = OldI2MI[vni->kills[i] / InstrSlots::NUM + e];
203 e++;
204 } while (!newInstr);
205
206 vni->kills[i] = mi2iMap_[newInstr];
Owen Anderson7eec0c22008-05-29 23:01:22 +0000207 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000208 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000209 }
210}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000211
Owen Anderson80b3ce62008-05-28 20:54:50 +0000212/// runOnMachineFunction - Register allocate the whole function
213///
214bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
215 mf_ = &fn;
216 mri_ = &mf_->getRegInfo();
217 tm_ = &fn.getTarget();
218 tri_ = tm_->getRegisterInfo();
219 tii_ = tm_->getInstrInfo();
220 lv_ = &getAnalysis<LiveVariables>();
221 allocatableRegs_ = tri_->getAllocatableSet(fn);
222
223 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000224 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000225
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000226 numIntervals += getNumIntervals();
227
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000228 DOUT << "********** INTERVALS **********\n";
229 for (iterator I = begin(), E = end(); I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000230 I->second.print(DOUT, tri_);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000231 DOUT << "\n";
232 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000233
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000234 numIntervalsAfter += getNumIntervals();
Chris Lattner70ca3582004-09-30 15:59:17 +0000235 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000236 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000237}
238
Chris Lattner70ca3582004-09-30 15:59:17 +0000239/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000240void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000241 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000242 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000243 I->second.print(O, tri_);
244 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000245 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000246
247 O << "********** MACHINEINSTRS **********\n";
248 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
249 mbbi != mbbe; ++mbbi) {
250 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
251 for (MachineBasicBlock::iterator mii = mbbi->begin(),
252 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000253 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000254 }
255 }
256}
257
Evan Chengc92da382007-11-03 07:20:12 +0000258/// conflictsWithPhysRegDef - Returns true if the specified register
259/// is defined during the duration of the specified interval.
260bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
261 VirtRegMap &vrm, unsigned reg) {
262 for (LiveInterval::Ranges::const_iterator
263 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
264 for (unsigned index = getBaseIndex(I->start),
265 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
266 index += InstrSlots::NUM) {
267 // skip deleted instructions
268 while (index != end && !getInstructionFromIndex(index))
269 index += InstrSlots::NUM;
270 if (index == end) break;
271
272 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng5d446262007-11-15 08:13:29 +0000273 unsigned SrcReg, DstReg;
274 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
275 if (SrcReg == li.reg || DstReg == li.reg)
276 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000277 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
278 MachineOperand& mop = MI->getOperand(i);
Evan Cheng5d446262007-11-15 08:13:29 +0000279 if (!mop.isRegister())
Evan Chengc92da382007-11-03 07:20:12 +0000280 continue;
281 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000282 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000283 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000284 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000285 if (!vrm.hasPhys(PhysReg))
286 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000287 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000288 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000289 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000290 return true;
291 }
292 }
293 }
294
295 return false;
296}
297
Evan Cheng549f27d32007-08-13 23:45:17 +0000298void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000299 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000300 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000301 else
302 cerr << "%reg" << reg;
303}
304
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000305void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000306 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000307 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000308 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000309 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000310 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000311 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000312
Evan Cheng419852c2008-04-03 16:39:43 +0000313 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
314 DOUT << "is a implicit_def\n";
315 return;
316 }
317
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000318 // Virtual registers may be defined multiple times (due to phi
319 // elimination and 2-addr elimination). Much of what we do only has to be
320 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000321 // time we see a vreg.
322 if (interval.empty()) {
323 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000324 unsigned defIndex = getDefIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000325 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000326 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000327 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000328 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000329 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000330 tii_->isMoveInstr(*mi, SrcReg, DstReg))
331 CopyMI = mi;
332 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000333
334 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000335
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000336 // Loop over all of the blocks that the vreg is defined in. There are
337 // two cases we have to handle here. The most common case is a vreg
338 // whose lifetime is contained within a basic block. In this case there
339 // will be a single kill, in MBB, which comes after the definition.
340 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
341 // FIXME: what about dead vars?
342 unsigned killIdx;
343 if (vi.Kills[0] != mi)
344 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
345 else
346 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000347
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348 // If the kill happens after the definition, we have an intra-block
349 // live range.
350 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000351 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000352 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000353 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000354 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000355 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000356 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000357 return;
358 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000359 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000360
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000361 // The other case we handle is when a virtual register lives to the end
362 // of the defining block, potentially live across some blocks, then is
363 // live into some number of blocks, but gets killed. Start by adding a
364 // range that goes from this definition to the end of the defining block.
Owen Anderson29b03992008-06-19 05:29:34 +0000365 LiveRange NewLR(defIndex,
366 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
367 ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000368 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000369 interval.addRange(NewLR);
370
371 // Iterate over all of the blocks that the variable is completely
372 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
373 // live interval.
374 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
375 if (vi.AliveBlocks[i]) {
Owen Anderson31ec8412008-06-16 19:32:40 +0000376 LiveRange LR(getMBBStartIdx(i),
Evan Chengf26e8552008-06-17 20:13:36 +0000377 getMBBEndIdx(i)+1, // MBB ends at -1.
Owen Anderson31ec8412008-06-16 19:32:40 +0000378 ValNo);
379 interval.addRange(LR);
380 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000381 }
382 }
383
384 // Finally, this virtual register is live from the start of any killing
385 // block to the 'use' slot of the killing instruction.
386 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
387 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000388 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000389 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000390 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000391 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000392 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000393 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000394 }
395
396 } else {
397 // If this is the second time we see a virtual register definition, it
398 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000399 // the result of two address elimination, then the vreg is one of the
400 // def-and-use register operand.
Evan Chengef0732d2008-07-10 07:35:43 +0000401 if (mi->isRegReDefinedByTwoAddr(interval.reg, MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000402 // If this is a two-address definition, then we have already processed
403 // the live range. The only problem is that we didn't realize there
404 // are actually two values in the live interval. Because of this we
405 // need to take the LiveRegion that defines this register and split it
406 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000407 assert(interval.containsOneValue());
408 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000409 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000410
Evan Cheng4f8ff162007-08-11 00:59:19 +0000411 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000412 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000413
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000414 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000415 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000416 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000417
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000418 // Two-address vregs should always only be redefined once. This means
419 // that at this point, there should be exactly one value number in it.
420 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
421
Chris Lattner91725b72006-08-31 05:54:43 +0000422 // The new value number (#1) is defined by the instruction we claimed
423 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000424 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
425 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000426
Chris Lattner91725b72006-08-31 05:54:43 +0000427 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000428 OldValNo->def = RedefIndex;
429 OldValNo->copy = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000430
431 // Add the new live interval which replaces the range for the input copy.
432 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000433 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000434 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000435 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000436
437 // If this redefinition is dead, we need to add a dummy unit live
438 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000439 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000440 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000441
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000442 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000443 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000444
445 } else {
446 // Otherwise, this must be because of phi elimination. If this is the
447 // first redefinition of the vreg that we have seen, go back and change
448 // the live range in the PHI block to be a different value number.
449 if (interval.containsOneValue()) {
450 assert(vi.Kills.size() == 1 &&
451 "PHI elimination vreg should have one kill, the PHI itself!");
452
453 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000454 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000455 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000456 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000457 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000458 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000459 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000460 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000461 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000462 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000463
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000464 // Replace the interval with one of a NEW value number. Note that this
465 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000466 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000467 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000468 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000469 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000470 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000471 }
472
473 // In the case of PHI elimination, each variable definition is only
474 // live until the end of the block. We've already taken care of the
475 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000476 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000477
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000478 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000479 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000480 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000481 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000482 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000483 tii_->isMoveInstr(*mi, SrcReg, DstReg))
484 CopyMI = mi;
485 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000486
Owen Anderson29b03992008-06-19 05:29:34 +0000487 unsigned killIndex = getInstructionIndex(&mbb->back()) + InstrSlots::NUM;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000488 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000489 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000490 interval.addKill(ValNo, killIndex);
491 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000492 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000493 }
494 }
495
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000496 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000497}
498
Chris Lattnerf35fef72004-07-23 21:24:19 +0000499void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000500 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000501 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000502 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000503 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000504 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000505 // A physical register cannot be live across basic block, so its
506 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000507 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000508
Chris Lattner6b128bd2006-09-03 08:07:11 +0000509 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000510 unsigned start = getDefIndex(baseIndex);
511 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000512
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000513 // If it is not used after definition, it is considered dead at
514 // the instruction defining it. Hence its interval is:
515 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000516 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000517 DOUT << " dead";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000518 end = getDefIndex(start) + 1;
519 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000520 }
521
522 // If it is not dead on definition, it must be killed by a
523 // subsequent instruction. Hence its interval is:
524 // [defSlot(def), useSlot(kill)+1)
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000525 while (++mi != MBB->end()) {
Owen Anderson29b03992008-06-19 05:29:34 +0000526 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000527 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000528 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000529 end = getUseIndex(baseIndex) + 1;
530 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000531 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000532 // Another instruction redefines the register before it is ever read.
533 // Then the register is essentially dead at the instruction that defines
534 // it. Hence its interval is:
535 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000536 DOUT << " dead";
Evan Cheng9a1956a2006-11-15 20:54:11 +0000537 end = getDefIndex(start) + 1;
538 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000539 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000540 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000541
542 // The only case we should have a dead physreg here without a killing or
543 // instruction where we know it's dead is if it is live-in to the function
544 // and never used.
Evan Chengc8d044e2008-02-15 18:24:29 +0000545 assert(!CopyMI && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000546 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000547
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000548exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000549 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000550
Evan Cheng24a3cc42007-04-25 07:30:23 +0000551 // Already exists? Extend old live interval.
552 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000553 VNInfo *ValNo = (OldLR != interval.end())
Evan Chengc8d044e2008-02-15 18:24:29 +0000554 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000555 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000556 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000557 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000558 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000559}
560
Chris Lattnerf35fef72004-07-23 21:24:19 +0000561void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
562 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000563 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000564 MachineOperand& MO,
565 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000566 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000567 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000568 getOrCreateInterval(MO.getReg()));
569 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000570 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000571 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000572 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000573 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000574 tii_->isMoveInstr(*MI, SrcReg, DstReg))
575 CopyMI = MI;
Owen Anderson6b098de2008-06-25 23:39:39 +0000576 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
577 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000578 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000579 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000580 // If MI also modifies the sub-register explicitly, avoid processing it
581 // more than once. Do not pass in TRI here so it checks for exact match.
582 if (!MI->modifiesRegister(*AS))
Owen Anderson6b098de2008-06-25 23:39:39 +0000583 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
584 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000585 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000586}
587
Evan Chengb371f452007-02-19 21:49:54 +0000588void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000589 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000590 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000591 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
592
593 // Look for kills, if it reaches a def before it's killed, then it shouldn't
594 // be considered a livein.
595 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000596 unsigned baseIndex = MIIdx;
597 unsigned start = baseIndex;
Evan Chengb371f452007-02-19 21:49:54 +0000598 unsigned end = start;
599 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000600 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000601 DOUT << " killed";
602 end = getUseIndex(baseIndex) + 1;
603 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000604 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000605 // Another instruction redefines the register before it is ever read.
606 // Then the register is essentially dead at the instruction that defines
607 // it. Hence its interval is:
608 // [defSlot(def), defSlot(def)+1)
609 DOUT << " dead";
610 end = getDefIndex(start) + 1;
611 goto exit;
612 }
613
614 baseIndex += InstrSlots::NUM;
615 ++mi;
616 }
617
618exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000619 // Live-in register might not be used at all.
620 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000621 if (isAlias) {
622 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000623 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000624 } else {
625 DOUT << " live through";
626 end = baseIndex;
627 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000628 }
629
Evan Chengf3bb2e62007-09-05 21:46:51 +0000630 LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000631 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000632 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000633 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000634}
635
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000636/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000637/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000638/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000639/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000640void LiveIntervals::computeIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000641 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
642 << "********** Function: "
643 << ((Value*)mf_->getFunction())->getName() << '\n';
Chris Lattner6b128bd2006-09-03 08:07:11 +0000644 // Track the index of the current machine instr.
645 unsigned MIIndex = 0;
Chris Lattner428b92e2006-09-15 03:57:23 +0000646 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
647 MBBI != E; ++MBBI) {
648 MachineBasicBlock *MBB = MBBI;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000649 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000650
Chris Lattner428b92e2006-09-15 03:57:23 +0000651 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000652
Dan Gohmancb406c22007-10-03 19:26:29 +0000653 // Create intervals for live-ins to this BB first.
654 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
655 LE = MBB->livein_end(); LI != LE; ++LI) {
656 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
657 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000658 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000659 if (!hasInterval(*AS))
660 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
661 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000662 }
663
Chris Lattner428b92e2006-09-15 03:57:23 +0000664 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000665 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000666
Evan Cheng438f7bc2006-11-10 08:43:01 +0000667 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000668 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
669 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000670 // handle register defs - build intervals
Chris Lattner428b92e2006-09-15 03:57:23 +0000671 if (MO.isRegister() && MO.getReg() && MO.isDef())
Evan Chengef0732d2008-07-10 07:35:43 +0000672 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000673 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000674
675 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000676 }
Owen Anderson29b03992008-06-19 05:29:34 +0000677
678 if (MBB->begin() == miEnd) MIIndex += InstrSlots::NUM; // Empty MBB
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000679 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000680}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000681
Evan Cheng4ca980e2007-10-17 02:10:22 +0000682bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Chenga5bfc972007-10-17 06:53:44 +0000683 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000684 std::vector<IdxMBBPair>::const_iterator I =
685 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
686
687 bool ResVal = false;
688 while (I != Idx2MBBMap.end()) {
689 if (LR.end <= I->first)
690 break;
691 MBBs.push_back(I->second);
692 ResVal = true;
693 ++I;
694 }
695 return ResVal;
696}
697
698
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000699LiveInterval LiveIntervals::createInterval(unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000700 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000701 HUGE_VALF : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000702 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000703}
Evan Chengf2fbca62007-11-12 06:35:08 +0000704
Evan Chengc8d044e2008-02-15 18:24:29 +0000705/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
706/// copy field and returns the source register that defines it.
707unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
708 if (!VNI->copy)
709 return 0;
710
711 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
712 return VNI->copy->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000713 if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
714 return VNI->copy->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000715 unsigned SrcReg, DstReg;
716 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
717 return SrcReg;
718 assert(0 && "Unrecognized copy instruction!");
719 return 0;
720}
Evan Chengf2fbca62007-11-12 06:35:08 +0000721
722//===----------------------------------------------------------------------===//
723// Register allocator hooks.
724//
725
Evan Chengd70dbb52008-02-22 09:24:50 +0000726/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
727/// allow one) virtual register operand, then its uses are implicitly using
728/// the register. Returns the virtual register.
729unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
730 MachineInstr *MI) const {
731 unsigned RegOp = 0;
732 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
733 MachineOperand &MO = MI->getOperand(i);
734 if (!MO.isRegister() || !MO.isUse())
735 continue;
736 unsigned Reg = MO.getReg();
737 if (Reg == 0 || Reg == li.reg)
738 continue;
739 // FIXME: For now, only remat MI with at most one register operand.
740 assert(!RegOp &&
741 "Can't rematerialize instruction with multiple register operand!");
742 RegOp = MO.getReg();
743 break;
744 }
745 return RegOp;
746}
747
748/// isValNoAvailableAt - Return true if the val# of the specified interval
749/// which reaches the given instruction also reaches the specified use index.
750bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
751 unsigned UseIdx) const {
752 unsigned Index = getInstructionIndex(MI);
753 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
754 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
755 return UI != li.end() && UI->valno == ValNo;
756}
757
Evan Chengf2fbca62007-11-12 06:35:08 +0000758/// isReMaterializable - Returns true if the definition MI of the specified
759/// val# of the specified interval is re-materializable.
760bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000761 const VNInfo *ValNo, MachineInstr *MI,
762 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000763 if (DisableReMat)
764 return false;
765
Evan Cheng5ef3a042007-12-06 00:01:56 +0000766 isLoad = false;
Evan Cheng20ccded2008-03-15 00:19:36 +0000767 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000768 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000769
770 int FrameIdx = 0;
771 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000772 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000773 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
774 // this but remember this is not safe to fold into a two-address
775 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000776 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000777 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000778
Evan Chengd70dbb52008-02-22 09:24:50 +0000779 if (tii_->isTriviallyReMaterializable(MI)) {
Evan Cheng20ccded2008-03-15 00:19:36 +0000780 const TargetInstrDesc &TID = MI->getDesc();
Chris Lattner749c6f62008-01-07 07:27:27 +0000781 isLoad = TID.isSimpleLoad();
Evan Chengd70dbb52008-02-22 09:24:50 +0000782
783 unsigned ImpUse = getReMatImplicitUse(li, MI);
784 if (ImpUse) {
785 const LiveInterval &ImpLi = getInterval(ImpUse);
786 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
787 re = mri_->use_end(); ri != re; ++ri) {
788 MachineInstr *UseMI = &*ri;
789 unsigned UseIdx = getInstructionIndex(UseMI);
790 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
791 continue;
Evan Cheng298bbe82008-02-23 02:14:42 +0000792 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
Evan Chengd70dbb52008-02-22 09:24:50 +0000793 return false;
794 }
795 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000796 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000797 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000798
Evan Chengdd3465e2008-02-23 01:44:27 +0000799 return false;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000800}
801
802/// isReMaterializable - Returns true if every definition of MI of every
803/// val# of the specified interval is re-materializable.
804bool LiveIntervals::isReMaterializable(const LiveInterval &li, bool &isLoad) {
805 isLoad = false;
806 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
807 i != e; ++i) {
808 const VNInfo *VNI = *i;
809 unsigned DefIdx = VNI->def;
810 if (DefIdx == ~1U)
811 continue; // Dead val#.
812 // Is the def for the val# rematerializable?
813 if (DefIdx == ~0u)
814 return false;
815 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
816 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000817 if (!ReMatDefMI ||
818 !isReMaterializable(li, VNI, ReMatDefMI, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +0000819 return false;
820 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +0000821 }
822 return true;
823}
824
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000825/// FilterFoldedOps - Filter out two-address use operands. Return
826/// true if it finds any issue with the operands that ought to prevent
827/// folding.
828static bool FilterFoldedOps(MachineInstr *MI,
829 SmallVector<unsigned, 2> &Ops,
830 unsigned &MRInfo,
831 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000832 const TargetInstrDesc &TID = MI->getDesc();
Evan Cheng6e141fd2007-12-12 23:12:09 +0000833
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000834 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +0000835 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
836 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +0000837 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +0000838 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +0000839 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000840 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +0000841 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +0000842 MRInfo |= (unsigned)VirtRegMap::isMod;
843 else {
844 // Filter out two-address use operand(s).
Evan Chengd70dbb52008-02-22 09:24:50 +0000845 if (!MO.isImplicit() &&
846 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengaee4af62007-12-02 08:30:39 +0000847 MRInfo = VirtRegMap::isModRef;
848 continue;
849 }
850 MRInfo |= (unsigned)VirtRegMap::isRef;
851 }
852 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +0000853 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000854 return false;
855}
856
857
858/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
859/// slot / to reg or any rematerialized load into ith operand of specified
860/// MI. If it is successul, MI is updated with the newly created MI and
861/// returns true.
862bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
863 VirtRegMap &vrm, MachineInstr *DefMI,
864 unsigned InstrIdx,
865 SmallVector<unsigned, 2> &Ops,
866 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000867 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +0000868 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000869 RemoveMachineInstrFromMaps(MI);
870 vrm.RemoveMachineInstrFromMaps(MI);
871 MI->eraseFromParent();
872 ++numFolds;
873 return true;
874 }
875
876 // Filter the list of operand indexes that are to be folded. Abort if
877 // any operand will prevent folding.
878 unsigned MRInfo = 0;
879 SmallVector<unsigned, 2> FoldOps;
880 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
881 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +0000882
Evan Cheng427f4c12008-03-31 23:19:51 +0000883 // The only time it's safe to fold into a two address instruction is when
884 // it's folding reload and spill from / into a spill stack slot.
885 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +0000886 return false;
887
Evan Chengf2f8c2a2008-02-08 22:05:27 +0000888 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
889 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +0000890 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +0000891 // Remember this instruction uses the spill slot.
892 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
893
Evan Chengf2fbca62007-11-12 06:35:08 +0000894 // Attempt to fold the memory reference into the instruction. If
895 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +0000896 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +0000897 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +0000898 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +0000899 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000900 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +0000901 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +0000902 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +0000903 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
904 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +0000905 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000906 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +0000907 return true;
908 }
909 return false;
910}
911
Evan Cheng018f9b02007-12-05 03:22:34 +0000912/// canFoldMemoryOperand - Returns true if the specified load / store
913/// folding is possible.
914bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000915 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +0000916 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000917 // Filter the list of operand indexes that are to be folded. Abort if
918 // any operand will prevent folding.
919 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +0000920 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000921 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
922 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +0000923
Evan Cheng3c75ba82008-04-01 21:37:32 +0000924 // It's only legal to remat for a use, not a def.
925 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000926 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +0000927
Evan Chengd70dbb52008-02-22 09:24:50 +0000928 return tii_->canFoldMemoryOperand(MI, FoldOps);
929}
930
Evan Cheng81a03822007-11-17 00:40:40 +0000931bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
932 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
933 for (LiveInterval::Ranges::const_iterator
934 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
935 std::vector<IdxMBBPair>::const_iterator II =
936 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
937 if (II == Idx2MBBMap.end())
938 continue;
939 if (I->end > II->first) // crossing a MBB.
940 return false;
941 MBBs.insert(II->second);
942 if (MBBs.size() > 1)
943 return false;
944 }
945 return true;
946}
947
Evan Chengd70dbb52008-02-22 09:24:50 +0000948/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
949/// interval on to-be re-materialized operands of MI) with new register.
950void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
951 MachineInstr *MI, unsigned NewVReg,
952 VirtRegMap &vrm) {
953 // There is an implicit use. That means one of the other operand is
954 // being remat'ed and the remat'ed instruction has li.reg as an
955 // use operand. Make sure we rewrite that as well.
956 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
957 MachineOperand &MO = MI->getOperand(i);
958 if (!MO.isRegister())
959 continue;
960 unsigned Reg = MO.getReg();
961 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
962 continue;
963 if (!vrm.isReMaterialized(Reg))
964 continue;
965 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +0000966 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
967 if (UseMO)
968 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +0000969 }
970}
971
Evan Chengf2fbca62007-11-12 06:35:08 +0000972/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
973/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +0000974bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +0000975rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
976 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +0000977 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +0000978 unsigned Slot, int LdSlot,
979 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +0000980 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +0000981 const TargetRegisterClass* rc,
982 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +0000983 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +0000984 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Evan Cheng1953d0c2007-11-29 10:12:14 +0000985 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +0000986 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
987 MachineBasicBlock *MBB = MI->getParent();
988 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng018f9b02007-12-05 03:22:34 +0000989 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +0000990 RestartInstruction:
991 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
992 MachineOperand& mop = MI->getOperand(i);
993 if (!mop.isRegister())
994 continue;
995 unsigned Reg = mop.getReg();
996 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000997 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +0000998 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +0000999 if (Reg != li.reg)
1000 continue;
1001
1002 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001003 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001004 int FoldSlot = Slot;
1005 if (DefIsReMat) {
1006 // If this is the rematerializable definition MI itself and
1007 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001008 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001009 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1010 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001011 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001012 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001013 MI->eraseFromParent();
1014 break;
1015 }
1016
1017 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001018 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001019 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001020 if (isLoad) {
1021 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1022 FoldSS = isLoadSS;
1023 FoldSlot = LdSlot;
1024 }
1025 }
1026
Evan Chengf2fbca62007-11-12 06:35:08 +00001027 // Scan all of the operands of this instruction rewriting operands
1028 // to use NewVReg instead of li.reg as appropriate. We do this for
1029 // two reasons:
1030 //
1031 // 1. If the instr reads the same spilled vreg multiple times, we
1032 // want to reuse the NewVReg.
1033 // 2. If the instr is a two-addr instruction, we are required to
1034 // keep the src/dst regs pinned.
1035 //
1036 // Keep track of whether we replace a use and/or def so that we can
1037 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001038
Evan Cheng81a03822007-11-17 00:40:40 +00001039 HasUse = mop.isUse();
1040 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001041 SmallVector<unsigned, 2> Ops;
1042 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001043 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001044 const MachineOperand &MOj = MI->getOperand(j);
1045 if (!MOj.isRegister())
Evan Chengf2fbca62007-11-12 06:35:08 +00001046 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001047 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001048 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001049 continue;
1050 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001051 Ops.push_back(j);
1052 HasUse |= MOj.isUse();
1053 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001054 }
1055 }
1056
Evan Cheng79a796c2008-07-12 01:56:02 +00001057 if (HasUse && !li.liveAt(getUseIndex(index)))
1058 // Must be defined by an implicit def. It should not be spilled. Note,
1059 // this is for correctness reason. e.g.
1060 // 8 %reg1024<def> = IMPLICIT_DEF
1061 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1062 // The live range [12, 14) are not part of the r1024 live interval since
1063 // it's defined by an implicit def. It will not conflicts with live
1064 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001065 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001066 // the INSERT_SUBREG and both target registers that would overlap.
1067 HasUse = false;
1068
Evan Cheng9c3c2212008-06-06 07:54:39 +00001069 // Update stack slot spill weight if we are splitting.
Evan Chengc3417602008-06-21 06:45:54 +00001070 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001071 if (!TrySplit)
1072 SSWeight += Weight;
1073
1074 if (!TryFold)
1075 CanFold = false;
1076 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001077 // Do not fold load / store here if we are splitting. We'll find an
1078 // optimal point to insert a load / store later.
1079 if (!TrySplit) {
1080 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1081 Ops, FoldSS, FoldSlot, Reg)) {
1082 // Folding the load/store can completely change the instruction in
1083 // unpredictable ways, rescan it from the beginning.
1084 HasUse = false;
1085 HasDef = false;
1086 CanFold = false;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001087 if (isRemoved(MI)) {
1088 SSWeight -= Weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001089 break;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001090 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001091 goto RestartInstruction;
1092 }
1093 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001094 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001095 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001096 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001097 }
Evan Chengcddbb832007-11-30 21:23:43 +00001098
1099 // Create a new virtual register for the spill interval.
1100 bool CreatedNewVReg = false;
1101 if (NewVReg == 0) {
Evan Chengd70dbb52008-02-22 09:24:50 +00001102 NewVReg = mri_->createVirtualRegister(rc);
Evan Chengcddbb832007-11-30 21:23:43 +00001103 vrm.grow();
1104 CreatedNewVReg = true;
1105 }
1106 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001107 if (mop.isImplicit())
1108 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001109
1110 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001111 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1112 MachineOperand &mopj = MI->getOperand(Ops[j]);
1113 mopj.setReg(NewVReg);
1114 if (mopj.isImplicit())
1115 rewriteImplicitOps(li, MI, NewVReg, vrm);
1116 }
Evan Chengcddbb832007-11-30 21:23:43 +00001117
Evan Cheng81a03822007-11-17 00:40:40 +00001118 if (CreatedNewVReg) {
1119 if (DefIsReMat) {
1120 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001121 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001122 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001123 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001124 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001125 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001126 }
1127 if (!CanDelete || (HasUse && HasDef)) {
1128 // If this is a two-addr instruction then its use operands are
1129 // rematerializable but its def is not. It should be assigned a
1130 // stack slot.
1131 vrm.assignVirt2StackSlot(NewVReg, Slot);
1132 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001133 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001134 vrm.assignVirt2StackSlot(NewVReg, Slot);
1135 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001136 } else if (HasUse && HasDef &&
1137 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1138 // If this interval hasn't been assigned a stack slot (because earlier
1139 // def is a deleted remat def), do it now.
1140 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1141 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001142 }
1143
Evan Cheng313d4b82008-02-23 00:33:04 +00001144 // Re-matting an instruction with virtual register use. Add the
1145 // register as an implicit use on the use MI.
1146 if (DefIsReMat && ImpUse)
1147 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1148
Evan Chengf2fbca62007-11-12 06:35:08 +00001149 // create a new register interval for this spill / remat.
1150 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001151 if (CreatedNewVReg) {
1152 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001153 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001154 if (TrySplit)
1155 vrm.setIsSplitFromReg(NewVReg, li.reg);
1156 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001157
1158 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001159 if (CreatedNewVReg) {
1160 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1161 nI.getNextValue(~0U, 0, VNInfoAllocator));
1162 DOUT << " +" << LR;
1163 nI.addRange(LR);
1164 } else {
1165 // Extend the split live interval to this def / use.
1166 unsigned End = getUseIndex(index)+1;
1167 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1168 nI.getValNumInfo(nI.getNumValNums()-1));
1169 DOUT << " +" << LR;
1170 nI.addRange(LR);
1171 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001172 }
1173 if (HasDef) {
1174 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1175 nI.getNextValue(~0U, 0, VNInfoAllocator));
1176 DOUT << " +" << LR;
1177 nI.addRange(LR);
1178 }
Evan Cheng81a03822007-11-17 00:40:40 +00001179
Evan Chengf2fbca62007-11-12 06:35:08 +00001180 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001181 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001182 DOUT << '\n';
1183 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001184 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001185}
Evan Cheng81a03822007-11-17 00:40:40 +00001186bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001187 const VNInfo *VNI,
1188 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001189 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001190 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1191 unsigned KillIdx = VNI->kills[j];
1192 if (KillIdx > Idx && KillIdx < End)
1193 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001194 }
1195 return false;
1196}
1197
Evan Cheng063284c2008-02-21 00:34:19 +00001198/// RewriteInfo - Keep track of machine instrs that will be rewritten
1199/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001200namespace {
1201 struct RewriteInfo {
1202 unsigned Index;
1203 MachineInstr *MI;
1204 bool HasUse;
1205 bool HasDef;
1206 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1207 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1208 };
Evan Cheng063284c2008-02-21 00:34:19 +00001209
Dan Gohman844731a2008-05-13 00:00:25 +00001210 struct RewriteInfoCompare {
1211 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1212 return LHS.Index < RHS.Index;
1213 }
1214 };
1215}
Evan Cheng063284c2008-02-21 00:34:19 +00001216
Evan Chengf2fbca62007-11-12 06:35:08 +00001217void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001218rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001219 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001220 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001221 unsigned Slot, int LdSlot,
1222 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001223 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001224 const TargetRegisterClass* rc,
1225 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001226 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001227 BitVector &SpillMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001228 std::map<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001229 BitVector &RestoreMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001230 std::map<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1231 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001232 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001233 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001234 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001235 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001236 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001237
Evan Cheng063284c2008-02-21 00:34:19 +00001238 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001239 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001240 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001241 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1242 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001243 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001244 MachineOperand &O = ri.getOperand();
1245 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001246 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001247 unsigned index = getInstructionIndex(MI);
1248 if (index < start || index >= end)
1249 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001250 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1251 // Must be defined by an implicit def. It should not be spilled. Note,
1252 // this is for correctness reason. e.g.
1253 // 8 %reg1024<def> = IMPLICIT_DEF
1254 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1255 // The live range [12, 14) are not part of the r1024 live interval since
1256 // it's defined by an implicit def. It will not conflicts with live
1257 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001258 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001259 // the INSERT_SUBREG and both target registers that would overlap.
1260 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001261 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1262 }
1263 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1264
Evan Cheng313d4b82008-02-23 00:33:04 +00001265 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001266 // Now rewrite the defs and uses.
1267 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1268 RewriteInfo &rwi = RewriteMIs[i];
1269 ++i;
1270 unsigned index = rwi.Index;
1271 bool MIHasUse = rwi.HasUse;
1272 bool MIHasDef = rwi.HasDef;
1273 MachineInstr *MI = rwi.MI;
1274 // If MI def and/or use the same register multiple times, then there
1275 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001276 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001277 while (i != e && RewriteMIs[i].MI == MI) {
1278 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001279 bool isUse = RewriteMIs[i].HasUse;
1280 if (isUse) ++NumUses;
1281 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001282 MIHasDef |= RewriteMIs[i].HasDef;
1283 ++i;
1284 }
Evan Cheng81a03822007-11-17 00:40:40 +00001285 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001286
Evan Cheng0a891ed2008-05-23 23:00:04 +00001287 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001288 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001289 // register interval's spill weight to HUGE_VALF to prevent it from
1290 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001291 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001292 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001293 }
1294
Evan Cheng063284c2008-02-21 00:34:19 +00001295 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001296 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001297 if (TrySplit) {
Evan Cheng063284c2008-02-21 00:34:19 +00001298 std::map<unsigned,unsigned>::const_iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001299 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001300 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001301 // One common case:
1302 // x = use
1303 // ...
1304 // ...
1305 // def = ...
1306 // = use
1307 // It's better to start a new interval to avoid artifically
1308 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001309 if (MIHasDef && !MIHasUse) {
1310 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001311 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001312 }
1313 }
Evan Chengcada2452007-11-28 01:28:46 +00001314 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001315
1316 bool IsNew = ThisVReg == 0;
1317 if (IsNew) {
1318 // This ends the previous live interval. If all of its def / use
1319 // can be folded, give it a low spill weight.
1320 if (NewVReg && TrySplit && AllCanFold) {
1321 LiveInterval &nI = getOrCreateInterval(NewVReg);
1322 nI.weight /= 10.0F;
1323 }
1324 AllCanFold = true;
1325 }
1326 NewVReg = ThisVReg;
1327
Evan Cheng81a03822007-11-17 00:40:40 +00001328 bool HasDef = false;
1329 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001330 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001331 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1332 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1333 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1334 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001335 if (!HasDef && !HasUse)
1336 continue;
1337
Evan Cheng018f9b02007-12-05 03:22:34 +00001338 AllCanFold &= CanFold;
1339
Evan Cheng81a03822007-11-17 00:40:40 +00001340 // Update weight of spill interval.
1341 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001342 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001343 // The spill weight is now infinity as it cannot be spilled again.
1344 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001345 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001346 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001347
1348 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001349 if (HasDef) {
1350 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001351 bool HasKill = false;
1352 if (!HasUse)
1353 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1354 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001355 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001356 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001357 if (VNI)
1358 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1359 }
Evan Chenge3110d02007-12-01 04:42:39 +00001360 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
1361 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001362 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001363 if (SII == SpillIdxes.end()) {
1364 std::vector<SRInfo> S;
1365 S.push_back(SRInfo(index, NewVReg, true));
1366 SpillIdxes.insert(std::make_pair(MBBId, S));
1367 } else if (SII->second.back().vreg != NewVReg) {
1368 SII->second.push_back(SRInfo(index, NewVReg, true));
1369 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001370 // If there is an earlier def and this is a two-address
1371 // instruction, then it's not possible to fold the store (which
1372 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001373 SRInfo &Info = SII->second.back();
1374 Info.index = index;
1375 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001376 }
1377 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001378 } else if (SII != SpillIdxes.end() &&
1379 SII->second.back().vreg == NewVReg &&
1380 (int)index > SII->second.back().index) {
1381 // There is an earlier def that's not killed (must be two-address).
1382 // The spill is no longer needed.
1383 SII->second.pop_back();
1384 if (SII->second.empty()) {
1385 SpillIdxes.erase(MBBId);
1386 SpillMBBs.reset(MBBId);
1387 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001388 }
1389 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001390 }
1391
1392 if (HasUse) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001393 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001394 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001395 if (SII != SpillIdxes.end() &&
1396 SII->second.back().vreg == NewVReg &&
1397 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001398 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001399 SII->second.back().canFold = false;
1400 std::map<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001401 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001402 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001403 // If we are splitting live intervals, only fold if it's the first
1404 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001405 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001406 else if (IsNew) {
1407 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001408 if (RII == RestoreIdxes.end()) {
1409 std::vector<SRInfo> Infos;
1410 Infos.push_back(SRInfo(index, NewVReg, true));
1411 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1412 } else {
1413 RII->second.push_back(SRInfo(index, NewVReg, true));
1414 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001415 RestoreMBBs.set(MBBId);
1416 }
1417 }
1418
1419 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001420 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001421 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001422 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001423
1424 if (NewVReg && TrySplit && AllCanFold) {
1425 // If all of its def / use can be folded, give it a low spill weight.
1426 LiveInterval &nI = getOrCreateInterval(NewVReg);
1427 nI.weight /= 10.0F;
1428 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001429}
1430
Evan Cheng1953d0c2007-11-29 10:12:14 +00001431bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1432 BitVector &RestoreMBBs,
1433 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1434 if (!RestoreMBBs[Id])
1435 return false;
1436 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1437 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1438 if (Restores[i].index == index &&
1439 Restores[i].vreg == vr &&
1440 Restores[i].canFold)
1441 return true;
1442 return false;
1443}
1444
1445void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1446 BitVector &RestoreMBBs,
1447 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1448 if (!RestoreMBBs[Id])
1449 return;
1450 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1451 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1452 if (Restores[i].index == index && Restores[i].vreg)
1453 Restores[i].index = -1;
1454}
Evan Cheng81a03822007-11-17 00:40:40 +00001455
Evan Cheng4cce6b42008-04-11 17:53:36 +00001456/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1457/// spilled and create empty intervals for their uses.
1458void
1459LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1460 const TargetRegisterClass* rc,
1461 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001462 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1463 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001464 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001465 MachineInstr *MI = &*ri;
1466 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001467 if (O.isDef()) {
1468 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1469 "Register def was not rewritten?");
1470 RemoveMachineInstrFromMaps(MI);
1471 vrm.RemoveMachineInstrFromMaps(MI);
1472 MI->eraseFromParent();
1473 } else {
1474 // This must be an use of an implicit_def so it's not part of the live
1475 // interval. Create a new empty live interval for it.
1476 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1477 unsigned NewVReg = mri_->createVirtualRegister(rc);
1478 vrm.grow();
1479 vrm.setIsImplicitlyDefined(NewVReg);
1480 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1481 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1482 MachineOperand &MO = MI->getOperand(i);
1483 if (MO.isReg() && MO.getReg() == li.reg)
1484 MO.setReg(NewVReg);
1485 }
1486 }
Evan Cheng419852c2008-04-03 16:39:43 +00001487 }
1488}
1489
Evan Cheng81a03822007-11-17 00:40:40 +00001490
Evan Chengf2fbca62007-11-12 06:35:08 +00001491std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001492addIntervalsForSpills(const LiveInterval &li,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001493 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1494 float &SSWeight) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001495 assert(li.weight != HUGE_VALF &&
1496 "attempt to spill already spilled interval!");
1497
1498 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001499 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001500 DOUT << '\n';
1501
Evan Cheng9c3c2212008-06-06 07:54:39 +00001502 // Spill slot weight.
1503 SSWeight = 0.0f;
1504
Evan Cheng81a03822007-11-17 00:40:40 +00001505 // Each bit specify whether it a spill is required in the MBB.
1506 BitVector SpillMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001507 std::map<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001508 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001509 std::map<unsigned, std::vector<SRInfo> > RestoreIdxes;
1510 std::map<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001511 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001512 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001513
1514 unsigned NumValNums = li.getNumValNums();
1515 SmallVector<MachineInstr*, 4> ReMatDefs;
1516 ReMatDefs.resize(NumValNums, NULL);
1517 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1518 ReMatOrigDefs.resize(NumValNums, NULL);
1519 SmallVector<int, 4> ReMatIds;
1520 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1521 BitVector ReMatDelete(NumValNums);
1522 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1523
Evan Cheng81a03822007-11-17 00:40:40 +00001524 // Spilling a split live interval. It cannot be split any further. Also,
1525 // it's also guaranteed to be a single val# / range interval.
1526 if (vrm.getPreSplitReg(li.reg)) {
1527 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001528 // Unset the split kill marker on the last use.
1529 unsigned KillIdx = vrm.getKillPoint(li.reg);
1530 if (KillIdx) {
1531 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1532 assert(KillMI && "Last use disappeared?");
1533 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1534 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001535 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001536 }
Evan Chengadf85902007-12-05 09:51:10 +00001537 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001538 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1539 Slot = vrm.getStackSlot(li.reg);
1540 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1541 MachineInstr *ReMatDefMI = DefIsReMat ?
1542 vrm.getReMaterializedMI(li.reg) : NULL;
1543 int LdSlot = 0;
1544 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1545 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001546 (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001547 bool IsFirstRange = true;
1548 for (LiveInterval::Ranges::const_iterator
1549 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1550 // If this is a split live interval with multiple ranges, it means there
1551 // are two-address instructions that re-defined the value. Only the
1552 // first def can be rematerialized!
1553 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001554 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001555 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1556 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001557 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001558 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001559 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001560 } else {
1561 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1562 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001563 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001564 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001565 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001566 }
1567 IsFirstRange = false;
1568 }
Evan Cheng419852c2008-04-03 16:39:43 +00001569
Evan Cheng9c3c2212008-06-06 07:54:39 +00001570 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng4cce6b42008-04-11 17:53:36 +00001571 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001572 return NewLIs;
1573 }
1574
1575 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001576 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1577 TrySplit = false;
1578 if (TrySplit)
1579 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001580 bool NeedStackSlot = false;
1581 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1582 i != e; ++i) {
1583 const VNInfo *VNI = *i;
1584 unsigned VN = VNI->id;
1585 unsigned DefIdx = VNI->def;
1586 if (DefIdx == ~1U)
1587 continue; // Dead val#.
1588 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001589 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1590 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001591 bool dummy;
1592 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001593 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001594 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001595 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001596 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1597 ClonedMIs.push_back(Clone);
1598 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001599
1600 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001601 if (VNI->hasPHIKill) {
1602 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001603 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001604 CanDelete = false;
1605 // Need a stack slot if there is any live range where uses cannot be
1606 // rematerialized.
1607 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001608 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001609 if (CanDelete)
1610 ReMatDelete.set(VN);
1611 } else {
1612 // Need a stack slot if there is any live range where uses cannot be
1613 // rematerialized.
1614 NeedStackSlot = true;
1615 }
1616 }
1617
1618 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001619 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001620 Slot = vrm.assignVirt2StackSlot(li.reg);
1621
1622 // Create new intervals and rewrite defs and uses.
1623 for (LiveInterval::Ranges::const_iterator
1624 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001625 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1626 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1627 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001628 bool CanDelete = ReMatDelete[I->valno->id];
1629 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001630 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001631 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001632 (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001633 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001634 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001635 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001636 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001637 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengf2fbca62007-11-12 06:35:08 +00001638 }
1639
Evan Cheng0cbb1162007-11-29 01:06:25 +00001640 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001641 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001642 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001643 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00001644 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001645
Evan Chengb50bb8c2007-12-05 08:16:32 +00001646 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001647 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001648 if (NeedStackSlot) {
1649 int Id = SpillMBBs.find_first();
1650 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001651 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1652 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001653 std::vector<SRInfo> &spills = SpillIdxes[Id];
1654 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1655 int index = spills[i].index;
1656 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001657 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001658 bool isReMat = vrm.isReMaterialized(VReg);
1659 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001660 bool CanFold = false;
1661 bool FoundUse = false;
1662 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001663 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001664 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001665 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1666 MachineOperand &MO = MI->getOperand(j);
1667 if (!MO.isRegister() || MO.getReg() != VReg)
1668 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001669
1670 Ops.push_back(j);
1671 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001672 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001673 if (isReMat ||
1674 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1675 RestoreMBBs, RestoreIdxes))) {
1676 // MI has two-address uses of the same register. If the use
1677 // isn't the first and only use in the BB, then we can't fold
1678 // it. FIXME: Move this to rewriteInstructionsForSpills.
1679 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001680 break;
1681 }
Evan Chengaee4af62007-12-02 08:30:39 +00001682 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001683 }
1684 }
1685 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001686 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001687 if (CanFold && !Ops.empty()) {
1688 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001689 Folded = true;
Evan Chengf38d14f2007-12-05 09:05:34 +00001690 if (FoundUse > 0) {
Evan Chengaee4af62007-12-02 08:30:39 +00001691 // Also folded uses, do not issue a load.
1692 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00001693 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
1694 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001695 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00001696 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001697 }
1698
Evan Cheng7e073ba2008-04-09 20:57:25 +00001699 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00001700 if (!Folded) {
1701 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
1702 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00001703 if (!MI->registerDefIsDead(nI.reg))
1704 // No need to spill a dead def.
1705 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001706 if (isKill)
1707 AddedKill.insert(&nI);
1708 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001709
1710 // Update spill slot weight.
1711 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001712 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001713 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001714 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001715 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001716 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001717
Evan Cheng1953d0c2007-11-29 10:12:14 +00001718 int Id = RestoreMBBs.find_first();
1719 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001720 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1721 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
1722
Evan Cheng1953d0c2007-11-29 10:12:14 +00001723 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1724 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
1725 int index = restores[i].index;
1726 if (index == -1)
1727 continue;
1728 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001729 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001730 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001731 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001732 bool CanFold = false;
1733 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001734 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001735 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001736 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1737 MachineOperand &MO = MI->getOperand(j);
1738 if (!MO.isRegister() || MO.getReg() != VReg)
1739 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001740
Evan Cheng0cbb1162007-11-29 01:06:25 +00001741 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00001742 // If this restore were to be folded, it would have been folded
1743 // already.
1744 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00001745 break;
1746 }
Evan Chengaee4af62007-12-02 08:30:39 +00001747 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00001748 }
1749 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001750
1751 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001752 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001753 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001754 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00001755 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
1756 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001757 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
1758 int LdSlot = 0;
1759 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1760 // If the rematerializable def is a load, also try to fold it.
Chris Lattner749c6f62008-01-07 07:27:27 +00001761 if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00001762 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1763 Ops, isLoadSS, LdSlot, VReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001764 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
1765 if (ImpUse) {
1766 // Re-matting an instruction with virtual register use. Add the
1767 // register as an implicit use on the use MI and update the register
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001768 // interval's spill weight to HUGE_VALF to prevent it from being
1769 // spilled.
Evan Chengd70dbb52008-02-22 09:24:50 +00001770 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001771 ImpLi.weight = HUGE_VALF;
Evan Chengd70dbb52008-02-22 09:24:50 +00001772 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1773 }
Evan Chengaee4af62007-12-02 08:30:39 +00001774 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001775 }
1776 // If folding is not possible / failed, then tell the spiller to issue a
1777 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00001778 if (Folded)
1779 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001780 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00001781 vrm.addRestorePoint(VReg, MI);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001782
1783 // Update spill slot weight.
1784 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001785 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Cheng81a03822007-11-17 00:40:40 +00001786 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001787 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00001788 }
1789
Evan Chengb50bb8c2007-12-05 08:16:32 +00001790 // Finalize intervals: add kills, finalize spill weights, and filter out
1791 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00001792 std::vector<LiveInterval*> RetNewLIs;
1793 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
1794 LiveInterval *LI = NewLIs[i];
1795 if (!LI->empty()) {
Owen Andersona1566f22008-07-22 22:46:49 +00001796 LI->weight /= getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001797 if (!AddedKill.count(LI)) {
1798 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00001799 unsigned LastUseIdx = getBaseIndex(LR->end);
1800 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00001801 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001802 assert(UseIdx != -1);
Evan Chengd70dbb52008-02-22 09:24:50 +00001803 if (LastUse->getOperand(UseIdx).isImplicit() ||
1804 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chengb50bb8c2007-12-05 08:16:32 +00001805 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00001806 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00001807 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00001808 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001809 RetNewLIs.push_back(LI);
1810 }
1811 }
Evan Cheng81a03822007-11-17 00:40:40 +00001812
Evan Cheng4cce6b42008-04-11 17:53:36 +00001813 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00001814 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00001815}
Evan Cheng676dd7c2008-03-11 07:19:34 +00001816
1817/// hasAllocatableSuperReg - Return true if the specified physical register has
1818/// any super register that's allocatable.
1819bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
1820 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
1821 if (allocatableRegs_[*AS] && hasInterval(*AS))
1822 return true;
1823 return false;
1824}
1825
1826/// getRepresentativeReg - Find the largest super register of the specified
1827/// physical register.
1828unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
1829 // Find the largest super-register that is allocatable.
1830 unsigned BestReg = Reg;
1831 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
1832 unsigned SuperReg = *AS;
1833 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
1834 BestReg = SuperReg;
1835 break;
1836 }
1837 }
1838 return BestReg;
1839}
1840
1841/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
1842/// specified interval that conflicts with the specified physical register.
1843unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
1844 unsigned PhysReg) const {
1845 unsigned NumConflicts = 0;
1846 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
1847 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1848 E = mri_->reg_end(); I != E; ++I) {
1849 MachineOperand &O = I.getOperand();
1850 MachineInstr *MI = O.getParent();
1851 unsigned Index = getInstructionIndex(MI);
1852 if (pli.liveAt(Index))
1853 ++NumConflicts;
1854 }
1855 return NumConflicts;
1856}
1857
1858/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
1859/// around all defs and uses of the specified interval.
1860void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
1861 unsigned PhysReg, VirtRegMap &vrm) {
1862 unsigned SpillReg = getRepresentativeReg(PhysReg);
1863
1864 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
1865 // If there are registers which alias PhysReg, but which are not a
1866 // sub-register of the chosen representative super register. Assert
1867 // since we can't handle it yet.
1868 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
1869 tri_->isSuperRegister(*AS, SpillReg));
1870
1871 LiveInterval &pli = getInterval(SpillReg);
1872 SmallPtrSet<MachineInstr*, 8> SeenMIs;
1873 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1874 E = mri_->reg_end(); I != E; ++I) {
1875 MachineOperand &O = I.getOperand();
1876 MachineInstr *MI = O.getParent();
1877 if (SeenMIs.count(MI))
1878 continue;
1879 SeenMIs.insert(MI);
1880 unsigned Index = getInstructionIndex(MI);
1881 if (pli.liveAt(Index)) {
1882 vrm.addEmergencySpill(SpillReg, MI);
1883 pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1884 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
1885 if (!hasInterval(*AS))
1886 continue;
1887 LiveInterval &spli = getInterval(*AS);
1888 if (spli.liveAt(Index))
1889 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1890 }
1891 }
1892 }
1893}
Owen Andersonc4dc1322008-06-05 17:15:43 +00001894
1895LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1896 MachineInstr* startInst) {
1897 LiveInterval& Interval = getOrCreateInterval(reg);
1898 VNInfo* VN = Interval.getNextValue(
1899 getInstructionIndex(startInst) + InstrSlots::DEF,
1900 startInst, getVNInfoAllocator());
1901 VN->hasPHIKill = true;
1902 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
1903 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
1904 getMBBEndIdx(startInst->getParent()) + 1, VN);
1905 Interval.addRange(LR);
1906
1907 return LR;
1908}