blob: 1f29055e2f745d3ba8aebaeecc38f7356e7beac1 [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_;
Owen Anderson7fbad272008-07-23 21:37:49 +000084 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Anderson80b3ce62008-05-28 20:54:50 +000085
86 Idx2MBBMap.clear();
87 MBB2IdxMap.clear();
88 mi2iMap_.clear();
89 i2miMap_.clear();
90
Owen Andersona1566f22008-07-22 22:46:49 +000091 FunctionSize = 0;
92
Chris Lattner428b92e2006-09-15 03:57:23 +000093 // Number MachineInstrs and MachineBasicBlocks.
94 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +000095 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +000096
97 unsigned MIIndex = 0;
98 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
99 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000100 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000101
Owen Anderson7fbad272008-07-23 21:37:49 +0000102 // Insert an empty slot at the beginning of each block.
103 MIIndex += InstrSlots::NUM;
104 i2miMap_.push_back(0);
105
Chris Lattner428b92e2006-09-15 03:57:23 +0000106 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
107 I != E; ++I) {
108 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000109 assert(inserted && "multiple MachineInstr -> index mappings");
Chris Lattner428b92e2006-09-15 03:57:23 +0000110 i2miMap_.push_back(I);
111 MIIndex += InstrSlots::NUM;
Owen Andersona1566f22008-07-22 22:46:49 +0000112 FunctionSize++;
Owen Anderson7fbad272008-07-23 21:37:49 +0000113
114 // Insert an empty slot after every instruction.
Owen Anderson1fbb4542008-06-16 16:58:24 +0000115 MIIndex += InstrSlots::NUM;
116 i2miMap_.push_back(0);
Owen Anderson35578012008-06-16 07:10:49 +0000117 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000118
Owen Anderson1fbb4542008-06-16 16:58:24 +0000119 // Set the MBB2IdxMap entry for this MBB.
120 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
121 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000122 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000123 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000124
125 if (!OldI2MI.empty())
Owen Anderson7fbad272008-07-23 21:37:49 +0000126 for (iterator OI = begin(), OE = end(); OI != OE; ++OI)
127 for (LiveInterval::iterator LI = OI->second.begin(),
128 LE = OI->second.end(); LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000129
Owen Anderson7eec0c22008-05-29 23:01:22 +0000130 // Remap the start index of the live range to the corresponding new
131 // number, or our best guess at what it _should_ correspond to if the
132 // original instruction has been erased. This is either the following
133 // instruction or its predecessor.
Owen Anderson7fbad272008-07-23 21:37:49 +0000134 unsigned index = LI->start / InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000135 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000136 if (offset == InstrSlots::LOAD) {
137 std::vector<IdxMBBPair>::const_iterator I =
138 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
139 // Take the pair containing the index
140 std::vector<IdxMBBPair>::const_iterator J =
141 ((I != OldI2MBB.end() && I->first > index) ||
142 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000143
Owen Anderson7fbad272008-07-23 21:37:49 +0000144 LI->start = getMBBStartIdx(J->second);
145 } else {
146 LI->start = mi2iMap_[OldI2MI[index]] + 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 Anderson7fbad272008-07-23 21:37:49 +0000152 index = LI->end / InstrSlots::NUM;
153 offset = LI->end % InstrSlots::NUM;
154 if (offset == InstrSlots::STORE) {
155 std::vector<IdxMBBPair>::const_iterator I =
156 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
157 // Take the pair containing the index
158 std::vector<IdxMBBPair>::const_iterator J =
159 ((I != OldI2MBB.end() && I->first > index) ||
160 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
161
162 LI->end = getMBBEndIdx(J->second) + 1;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000163 } else {
Owen Anderson7fbad272008-07-23 21:37:49 +0000164 LI->end = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000165 }
Owen Anderson745825f42008-05-28 22:40:08 +0000166
Owen Anderson7eec0c22008-05-29 23:01:22 +0000167 // Remap the VNInfo def index, which works the same as the
168 // start indices above.
Owen Anderson745825f42008-05-28 22:40:08 +0000169 VNInfo* vni = LI->valno;
Owen Anderson7fbad272008-07-23 21:37:49 +0000170 index = vni->def / InstrSlots::NUM;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000171 offset = vni->def % InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000172 if (offset == InstrSlots::LOAD) {
173 std::vector<IdxMBBPair>::const_iterator I =
174 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
175 // Take the pair containing the index
176 std::vector<IdxMBBPair>::const_iterator J =
177 ((I != OldI2MBB.end() && I->first > index) ||
178 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000179
Owen Anderson7fbad272008-07-23 21:37:49 +0000180 vni->def = getMBBStartIdx(J->second);
181
182 } else {
183 vni->def = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000184 }
Owen Anderson745825f42008-05-28 22:40:08 +0000185
Owen Anderson7eec0c22008-05-29 23:01:22 +0000186 // Remap the VNInfo kill indices, which works the same as
187 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000188 for (size_t i = 0; i < vni->kills.size(); ++i) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000189 index = vni->kills[i] / InstrSlots::NUM;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000190 offset = vni->kills[i] % InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000191 if (OldI2MI[vni->kills[i] / InstrSlots::NUM]) {
192 std::vector<IdxMBBPair>::const_iterator I =
193 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
194 // Take the pair containing the index
195 std::vector<IdxMBBPair>::const_iterator J =
196 ((I != OldI2MBB.end() && I->first > index) ||
197 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
198
199 vni->kills[i] = getMBBEndIdx(J->second) + 1;
200 } else {
201 vni->kills[i] = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000202 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000203 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000204 }
205}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000206
Owen Anderson80b3ce62008-05-28 20:54:50 +0000207/// runOnMachineFunction - Register allocate the whole function
208///
209bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
210 mf_ = &fn;
211 mri_ = &mf_->getRegInfo();
212 tm_ = &fn.getTarget();
213 tri_ = tm_->getRegisterInfo();
214 tii_ = tm_->getInstrInfo();
215 lv_ = &getAnalysis<LiveVariables>();
216 allocatableRegs_ = tri_->getAllocatableSet(fn);
217
218 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000219 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000220
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000221 numIntervals += getNumIntervals();
222
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000223 DOUT << "********** INTERVALS **********\n";
224 for (iterator I = begin(), E = end(); I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000225 I->second.print(DOUT, tri_);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000226 DOUT << "\n";
227 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000228
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000229 numIntervalsAfter += getNumIntervals();
Chris Lattner70ca3582004-09-30 15:59:17 +0000230 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000231 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000232}
233
Chris Lattner70ca3582004-09-30 15:59:17 +0000234/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000235void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000236 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000237 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000238 I->second.print(O, tri_);
239 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000240 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000241
242 O << "********** MACHINEINSTRS **********\n";
243 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
244 mbbi != mbbe; ++mbbi) {
245 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
246 for (MachineBasicBlock::iterator mii = mbbi->begin(),
247 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000248 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000249 }
250 }
251}
252
Evan Chengc92da382007-11-03 07:20:12 +0000253/// conflictsWithPhysRegDef - Returns true if the specified register
254/// is defined during the duration of the specified interval.
255bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
256 VirtRegMap &vrm, unsigned reg) {
257 for (LiveInterval::Ranges::const_iterator
258 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
259 for (unsigned index = getBaseIndex(I->start),
260 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
261 index += InstrSlots::NUM) {
262 // skip deleted instructions
263 while (index != end && !getInstructionFromIndex(index))
264 index += InstrSlots::NUM;
265 if (index == end) break;
266
267 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng5d446262007-11-15 08:13:29 +0000268 unsigned SrcReg, DstReg;
269 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
270 if (SrcReg == li.reg || DstReg == li.reg)
271 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000272 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
273 MachineOperand& mop = MI->getOperand(i);
Evan Cheng5d446262007-11-15 08:13:29 +0000274 if (!mop.isRegister())
Evan Chengc92da382007-11-03 07:20:12 +0000275 continue;
276 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000277 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000278 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000279 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000280 if (!vrm.hasPhys(PhysReg))
281 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000282 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000283 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000284 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000285 return true;
286 }
287 }
288 }
289
290 return false;
291}
292
Evan Cheng549f27d32007-08-13 23:45:17 +0000293void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000294 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000295 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000296 else
297 cerr << "%reg" << reg;
298}
299
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000300void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000301 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000302 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000303 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000304 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000305 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000306 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000307
Evan Cheng419852c2008-04-03 16:39:43 +0000308 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
309 DOUT << "is a implicit_def\n";
310 return;
311 }
312
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000313 // Virtual registers may be defined multiple times (due to phi
314 // elimination and 2-addr elimination). Much of what we do only has to be
315 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000316 // time we see a vreg.
317 if (interval.empty()) {
318 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000319 unsigned defIndex = getDefIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000320 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000321 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000322 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000323 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000324 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000325 tii_->isMoveInstr(*mi, SrcReg, DstReg))
326 CopyMI = mi;
327 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000328
329 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000330
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000331 // Loop over all of the blocks that the vreg is defined in. There are
332 // two cases we have to handle here. The most common case is a vreg
333 // whose lifetime is contained within a basic block. In this case there
334 // will be a single kill, in MBB, which comes after the definition.
335 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
336 // FIXME: what about dead vars?
337 unsigned killIdx;
338 if (vi.Kills[0] != mi)
339 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
340 else
341 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000342
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000343 // If the kill happens after the definition, we have an intra-block
344 // live range.
345 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000346 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000347 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000348 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000349 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000350 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000351 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000352 return;
353 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000354 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000355
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000356 // The other case we handle is when a virtual register lives to the end
357 // of the defining block, potentially live across some blocks, then is
358 // live into some number of blocks, but gets killed. Start by adding a
359 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000360 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000361 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000362 interval.addRange(NewLR);
363
364 // Iterate over all of the blocks that the variable is completely
365 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
366 // live interval.
367 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
368 if (vi.AliveBlocks[i]) {
Owen Anderson31ec8412008-06-16 19:32:40 +0000369 LiveRange LR(getMBBStartIdx(i),
Evan Chengf26e8552008-06-17 20:13:36 +0000370 getMBBEndIdx(i)+1, // MBB ends at -1.
Owen Anderson31ec8412008-06-16 19:32:40 +0000371 ValNo);
372 interval.addRange(LR);
373 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000374 }
375 }
376
377 // Finally, this virtual register is live from the start of any killing
378 // block to the 'use' slot of the killing instruction.
379 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
380 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000381 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000382 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000383 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000384 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000385 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000386 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000387 }
388
389 } else {
390 // If this is the second time we see a virtual register definition, it
391 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000392 // the result of two address elimination, then the vreg is one of the
393 // def-and-use register operand.
Evan Chengef0732d2008-07-10 07:35:43 +0000394 if (mi->isRegReDefinedByTwoAddr(interval.reg, MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000395 // If this is a two-address definition, then we have already processed
396 // the live range. The only problem is that we didn't realize there
397 // are actually two values in the live interval. Because of this we
398 // need to take the LiveRegion that defines this register and split it
399 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000400 assert(interval.containsOneValue());
401 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000402 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000403
Evan Cheng4f8ff162007-08-11 00:59:19 +0000404 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000405 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000406
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000407 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000408 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000409 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000410
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000411 // Two-address vregs should always only be redefined once. This means
412 // that at this point, there should be exactly one value number in it.
413 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
414
Chris Lattner91725b72006-08-31 05:54:43 +0000415 // The new value number (#1) is defined by the instruction we claimed
416 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000417 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
418 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000419
Chris Lattner91725b72006-08-31 05:54:43 +0000420 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000421 OldValNo->def = RedefIndex;
422 OldValNo->copy = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000423
424 // Add the new live interval which replaces the range for the input copy.
425 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000426 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000427 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000428 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000429
430 // If this redefinition is dead, we need to add a dummy unit live
431 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000432 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000433 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000434
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000435 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000436 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000437
438 } else {
439 // Otherwise, this must be because of phi elimination. If this is the
440 // first redefinition of the vreg that we have seen, go back and change
441 // the live range in the PHI block to be a different value number.
442 if (interval.containsOneValue()) {
443 assert(vi.Kills.size() == 1 &&
444 "PHI elimination vreg should have one kill, the PHI itself!");
445
446 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000447 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000448 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000449 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000450 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000451 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000452 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000453 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000454 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000455 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000456
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000457 // Replace the interval with one of a NEW value number. Note that this
458 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000459 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000460 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000461 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000462 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000463 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000464 }
465
466 // In the case of PHI elimination, each variable definition is only
467 // live until the end of the block. We've already taken care of the
468 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000469 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000470
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000471 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000472 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000473 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000474 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000475 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000476 tii_->isMoveInstr(*mi, SrcReg, DstReg))
477 CopyMI = mi;
478 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000479
Owen Anderson7fbad272008-07-23 21:37:49 +0000480 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000481 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000482 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000483 interval.addKill(ValNo, killIndex);
484 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000485 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000486 }
487 }
488
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000489 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000490}
491
Chris Lattnerf35fef72004-07-23 21:24:19 +0000492void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000493 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000494 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000495 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000496 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000497 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000498 // A physical register cannot be live across basic block, so its
499 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000500 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000501
Chris Lattner6b128bd2006-09-03 08:07:11 +0000502 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000503 unsigned start = getDefIndex(baseIndex);
504 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000505
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000506 // If it is not used after definition, it is considered dead at
507 // the instruction defining it. Hence its interval is:
508 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000509 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000510 DOUT << " dead";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000511 end = getDefIndex(start) + 1;
512 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000513 }
514
515 // If it is not dead on definition, it must be killed by a
516 // subsequent instruction. Hence its interval is:
517 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000518 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000519 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000520 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
521 getInstructionFromIndex(baseIndex) == 0)
522 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000523 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000524 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000525 end = getUseIndex(baseIndex) + 1;
526 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000527 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000528 // Another instruction redefines the register before it is ever read.
529 // Then the register is essentially dead at the instruction that defines
530 // it. Hence its interval is:
531 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000532 DOUT << " dead";
Evan Cheng9a1956a2006-11-15 20:54:11 +0000533 end = getDefIndex(start) + 1;
534 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000535 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000536
537 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000538 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000539
540 // The only case we should have a dead physreg here without a killing or
541 // instruction where we know it's dead is if it is live-in to the function
542 // and never used.
Evan Chengc8d044e2008-02-15 18:24:29 +0000543 assert(!CopyMI && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000544 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000545
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000546exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000547 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000548
Evan Cheng24a3cc42007-04-25 07:30:23 +0000549 // Already exists? Extend old live interval.
550 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000551 VNInfo *ValNo = (OldLR != interval.end())
Evan Chengc8d044e2008-02-15 18:24:29 +0000552 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000553 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000554 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000555 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000556 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000557}
558
Chris Lattnerf35fef72004-07-23 21:24:19 +0000559void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
560 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000561 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000562 MachineOperand& MO,
563 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000564 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000565 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000566 getOrCreateInterval(MO.getReg()));
567 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000568 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000569 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000570 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000571 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000572 tii_->isMoveInstr(*MI, SrcReg, DstReg))
573 CopyMI = MI;
Owen Anderson6b098de2008-06-25 23:39:39 +0000574 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
575 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000576 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000577 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000578 // If MI also modifies the sub-register explicitly, avoid processing it
579 // more than once. Do not pass in TRI here so it checks for exact match.
580 if (!MI->modifiesRegister(*AS))
Owen Anderson6b098de2008-06-25 23:39:39 +0000581 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
582 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000583 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000584}
585
Evan Chengb371f452007-02-19 21:49:54 +0000586void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000587 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000588 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000589 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
590
591 // Look for kills, if it reaches a def before it's killed, then it shouldn't
592 // be considered a livein.
593 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000594 unsigned baseIndex = MIIdx;
595 unsigned start = baseIndex;
Evan Chengb371f452007-02-19 21:49:54 +0000596 unsigned end = start;
597 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000598 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000599 DOUT << " killed";
600 end = getUseIndex(baseIndex) + 1;
601 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000602 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000603 // Another instruction redefines the register before it is ever read.
604 // Then the register is essentially dead at the instruction that defines
605 // it. Hence its interval is:
606 // [defSlot(def), defSlot(def)+1)
607 DOUT << " dead";
608 end = getDefIndex(start) + 1;
609 goto exit;
610 }
611
612 baseIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000613 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
614 getInstructionFromIndex(baseIndex) == 0)
615 baseIndex += InstrSlots::NUM;
Evan Chengb371f452007-02-19 21:49:54 +0000616 ++mi;
617 }
618
619exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000620 // Live-in register might not be used at all.
621 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000622 if (isAlias) {
623 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000624 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000625 } else {
626 DOUT << " live through";
627 end = baseIndex;
628 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000629 }
630
Evan Chengf3bb2e62007-09-05 21:46:51 +0000631 LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000632 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000633 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000634 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000635}
636
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000637/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000638/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000639/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000640/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000641void LiveIntervals::computeIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000642 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
643 << "********** Function: "
644 << ((Value*)mf_->getFunction())->getName() << '\n';
Chris Lattner6b128bd2006-09-03 08:07:11 +0000645 // Track the index of the current machine instr.
646 unsigned MIIndex = 0;
Owen Anderson7fbad272008-07-23 21:37:49 +0000647
648 // Skip over empty initial indices.
649 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
650 getInstructionFromIndex(MIIndex) == 0)
651 MIIndex += InstrSlots::NUM;
652
Chris Lattner428b92e2006-09-15 03:57:23 +0000653 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
654 MBBI != E; ++MBBI) {
655 MachineBasicBlock *MBB = MBBI;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000656 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000657
Chris Lattner428b92e2006-09-15 03:57:23 +0000658 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000659
Dan Gohmancb406c22007-10-03 19:26:29 +0000660 // Create intervals for live-ins to this BB first.
661 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
662 LE = MBB->livein_end(); LI != LE; ++LI) {
663 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
664 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000665 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000666 if (!hasInterval(*AS))
667 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
668 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000669 }
670
Chris Lattner428b92e2006-09-15 03:57:23 +0000671 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000672 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000673
Evan Cheng438f7bc2006-11-10 08:43:01 +0000674 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000675 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
676 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000677 // handle register defs - build intervals
Chris Lattner428b92e2006-09-15 03:57:23 +0000678 if (MO.isRegister() && MO.getReg() && MO.isDef())
Evan Chengef0732d2008-07-10 07:35:43 +0000679 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000680 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000681
682 MIIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000683
684 // Skip over empty indices.
685 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
686 getInstructionFromIndex(MIIndex) == 0)
687 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000688 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000689 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000690}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000691
Evan Cheng4ca980e2007-10-17 02:10:22 +0000692bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Chenga5bfc972007-10-17 06:53:44 +0000693 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000694 std::vector<IdxMBBPair>::const_iterator I =
695 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
696
697 bool ResVal = false;
698 while (I != Idx2MBBMap.end()) {
699 if (LR.end <= I->first)
700 break;
701 MBBs.push_back(I->second);
702 ResVal = true;
703 ++I;
704 }
705 return ResVal;
706}
707
708
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000709LiveInterval LiveIntervals::createInterval(unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000710 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000711 HUGE_VALF : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000712 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000713}
Evan Chengf2fbca62007-11-12 06:35:08 +0000714
Evan Chengc8d044e2008-02-15 18:24:29 +0000715/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
716/// copy field and returns the source register that defines it.
717unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
718 if (!VNI->copy)
719 return 0;
720
721 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
722 return VNI->copy->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000723 if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
724 return VNI->copy->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000725 unsigned SrcReg, DstReg;
726 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
727 return SrcReg;
728 assert(0 && "Unrecognized copy instruction!");
729 return 0;
730}
Evan Chengf2fbca62007-11-12 06:35:08 +0000731
732//===----------------------------------------------------------------------===//
733// Register allocator hooks.
734//
735
Evan Chengd70dbb52008-02-22 09:24:50 +0000736/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
737/// allow one) virtual register operand, then its uses are implicitly using
738/// the register. Returns the virtual register.
739unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
740 MachineInstr *MI) const {
741 unsigned RegOp = 0;
742 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
743 MachineOperand &MO = MI->getOperand(i);
744 if (!MO.isRegister() || !MO.isUse())
745 continue;
746 unsigned Reg = MO.getReg();
747 if (Reg == 0 || Reg == li.reg)
748 continue;
749 // FIXME: For now, only remat MI with at most one register operand.
750 assert(!RegOp &&
751 "Can't rematerialize instruction with multiple register operand!");
752 RegOp = MO.getReg();
753 break;
754 }
755 return RegOp;
756}
757
758/// isValNoAvailableAt - Return true if the val# of the specified interval
759/// which reaches the given instruction also reaches the specified use index.
760bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
761 unsigned UseIdx) const {
762 unsigned Index = getInstructionIndex(MI);
763 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
764 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
765 return UI != li.end() && UI->valno == ValNo;
766}
767
Evan Chengf2fbca62007-11-12 06:35:08 +0000768/// isReMaterializable - Returns true if the definition MI of the specified
769/// val# of the specified interval is re-materializable.
770bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000771 const VNInfo *ValNo, MachineInstr *MI,
772 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000773 if (DisableReMat)
774 return false;
775
Evan Cheng5ef3a042007-12-06 00:01:56 +0000776 isLoad = false;
Evan Cheng20ccded2008-03-15 00:19:36 +0000777 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000778 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000779
780 int FrameIdx = 0;
781 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000782 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000783 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
784 // this but remember this is not safe to fold into a two-address
785 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000786 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000787 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000788
Evan Chengd70dbb52008-02-22 09:24:50 +0000789 if (tii_->isTriviallyReMaterializable(MI)) {
Evan Cheng20ccded2008-03-15 00:19:36 +0000790 const TargetInstrDesc &TID = MI->getDesc();
Chris Lattner749c6f62008-01-07 07:27:27 +0000791 isLoad = TID.isSimpleLoad();
Evan Chengd70dbb52008-02-22 09:24:50 +0000792
793 unsigned ImpUse = getReMatImplicitUse(li, MI);
794 if (ImpUse) {
795 const LiveInterval &ImpLi = getInterval(ImpUse);
796 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
797 re = mri_->use_end(); ri != re; ++ri) {
798 MachineInstr *UseMI = &*ri;
799 unsigned UseIdx = getInstructionIndex(UseMI);
800 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
801 continue;
Evan Cheng298bbe82008-02-23 02:14:42 +0000802 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
Evan Chengd70dbb52008-02-22 09:24:50 +0000803 return false;
804 }
805 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000806 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000807 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000808
Evan Chengdd3465e2008-02-23 01:44:27 +0000809 return false;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000810}
811
812/// isReMaterializable - Returns true if every definition of MI of every
813/// val# of the specified interval is re-materializable.
814bool LiveIntervals::isReMaterializable(const LiveInterval &li, bool &isLoad) {
815 isLoad = false;
816 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
817 i != e; ++i) {
818 const VNInfo *VNI = *i;
819 unsigned DefIdx = VNI->def;
820 if (DefIdx == ~1U)
821 continue; // Dead val#.
822 // Is the def for the val# rematerializable?
823 if (DefIdx == ~0u)
824 return false;
825 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
826 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000827 if (!ReMatDefMI ||
828 !isReMaterializable(li, VNI, ReMatDefMI, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +0000829 return false;
830 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +0000831 }
832 return true;
833}
834
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000835/// FilterFoldedOps - Filter out two-address use operands. Return
836/// true if it finds any issue with the operands that ought to prevent
837/// folding.
838static bool FilterFoldedOps(MachineInstr *MI,
839 SmallVector<unsigned, 2> &Ops,
840 unsigned &MRInfo,
841 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000842 const TargetInstrDesc &TID = MI->getDesc();
Evan Cheng6e141fd2007-12-12 23:12:09 +0000843
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000844 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +0000845 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
846 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +0000847 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +0000848 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +0000849 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000850 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +0000851 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +0000852 MRInfo |= (unsigned)VirtRegMap::isMod;
853 else {
854 // Filter out two-address use operand(s).
Evan Chengd70dbb52008-02-22 09:24:50 +0000855 if (!MO.isImplicit() &&
856 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengaee4af62007-12-02 08:30:39 +0000857 MRInfo = VirtRegMap::isModRef;
858 continue;
859 }
860 MRInfo |= (unsigned)VirtRegMap::isRef;
861 }
862 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +0000863 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000864 return false;
865}
866
867
868/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
869/// slot / to reg or any rematerialized load into ith operand of specified
870/// MI. If it is successul, MI is updated with the newly created MI and
871/// returns true.
872bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
873 VirtRegMap &vrm, MachineInstr *DefMI,
874 unsigned InstrIdx,
875 SmallVector<unsigned, 2> &Ops,
876 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000877 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +0000878 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000879 RemoveMachineInstrFromMaps(MI);
880 vrm.RemoveMachineInstrFromMaps(MI);
881 MI->eraseFromParent();
882 ++numFolds;
883 return true;
884 }
885
886 // Filter the list of operand indexes that are to be folded. Abort if
887 // any operand will prevent folding.
888 unsigned MRInfo = 0;
889 SmallVector<unsigned, 2> FoldOps;
890 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
891 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +0000892
Evan Cheng427f4c12008-03-31 23:19:51 +0000893 // The only time it's safe to fold into a two address instruction is when
894 // it's folding reload and spill from / into a spill stack slot.
895 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +0000896 return false;
897
Evan Chengf2f8c2a2008-02-08 22:05:27 +0000898 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
899 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +0000900 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +0000901 // Remember this instruction uses the spill slot.
902 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
903
Evan Chengf2fbca62007-11-12 06:35:08 +0000904 // Attempt to fold the memory reference into the instruction. If
905 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +0000906 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +0000907 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +0000908 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +0000909 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000910 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +0000911 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +0000912 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +0000913 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
914 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +0000915 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000916 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +0000917 return true;
918 }
919 return false;
920}
921
Evan Cheng018f9b02007-12-05 03:22:34 +0000922/// canFoldMemoryOperand - Returns true if the specified load / store
923/// folding is possible.
924bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000925 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +0000926 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000927 // Filter the list of operand indexes that are to be folded. Abort if
928 // any operand will prevent folding.
929 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +0000930 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000931 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
932 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +0000933
Evan Cheng3c75ba82008-04-01 21:37:32 +0000934 // It's only legal to remat for a use, not a def.
935 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000936 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +0000937
Evan Chengd70dbb52008-02-22 09:24:50 +0000938 return tii_->canFoldMemoryOperand(MI, FoldOps);
939}
940
Evan Cheng81a03822007-11-17 00:40:40 +0000941bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
942 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
943 for (LiveInterval::Ranges::const_iterator
944 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
945 std::vector<IdxMBBPair>::const_iterator II =
946 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
947 if (II == Idx2MBBMap.end())
948 continue;
949 if (I->end > II->first) // crossing a MBB.
950 return false;
951 MBBs.insert(II->second);
952 if (MBBs.size() > 1)
953 return false;
954 }
955 return true;
956}
957
Evan Chengd70dbb52008-02-22 09:24:50 +0000958/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
959/// interval on to-be re-materialized operands of MI) with new register.
960void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
961 MachineInstr *MI, unsigned NewVReg,
962 VirtRegMap &vrm) {
963 // There is an implicit use. That means one of the other operand is
964 // being remat'ed and the remat'ed instruction has li.reg as an
965 // use operand. Make sure we rewrite that as well.
966 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
967 MachineOperand &MO = MI->getOperand(i);
968 if (!MO.isRegister())
969 continue;
970 unsigned Reg = MO.getReg();
971 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
972 continue;
973 if (!vrm.isReMaterialized(Reg))
974 continue;
975 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +0000976 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
977 if (UseMO)
978 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +0000979 }
980}
981
Evan Chengf2fbca62007-11-12 06:35:08 +0000982/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
983/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +0000984bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +0000985rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
986 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +0000987 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +0000988 unsigned Slot, int LdSlot,
989 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +0000990 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +0000991 const TargetRegisterClass* rc,
992 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +0000993 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +0000994 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Evan Cheng1953d0c2007-11-29 10:12:14 +0000995 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +0000996 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
997 MachineBasicBlock *MBB = MI->getParent();
998 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng018f9b02007-12-05 03:22:34 +0000999 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001000 RestartInstruction:
1001 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1002 MachineOperand& mop = MI->getOperand(i);
1003 if (!mop.isRegister())
1004 continue;
1005 unsigned Reg = mop.getReg();
1006 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001007 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001008 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001009 if (Reg != li.reg)
1010 continue;
1011
1012 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001013 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001014 int FoldSlot = Slot;
1015 if (DefIsReMat) {
1016 // If this is the rematerializable definition MI itself and
1017 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001018 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001019 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1020 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001021 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001022 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001023 MI->eraseFromParent();
1024 break;
1025 }
1026
1027 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001028 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001029 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001030 if (isLoad) {
1031 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1032 FoldSS = isLoadSS;
1033 FoldSlot = LdSlot;
1034 }
1035 }
1036
Evan Chengf2fbca62007-11-12 06:35:08 +00001037 // Scan all of the operands of this instruction rewriting operands
1038 // to use NewVReg instead of li.reg as appropriate. We do this for
1039 // two reasons:
1040 //
1041 // 1. If the instr reads the same spilled vreg multiple times, we
1042 // want to reuse the NewVReg.
1043 // 2. If the instr is a two-addr instruction, we are required to
1044 // keep the src/dst regs pinned.
1045 //
1046 // Keep track of whether we replace a use and/or def so that we can
1047 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001048
Evan Cheng81a03822007-11-17 00:40:40 +00001049 HasUse = mop.isUse();
1050 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001051 SmallVector<unsigned, 2> Ops;
1052 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001053 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001054 const MachineOperand &MOj = MI->getOperand(j);
1055 if (!MOj.isRegister())
Evan Chengf2fbca62007-11-12 06:35:08 +00001056 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001057 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001058 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001059 continue;
1060 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001061 Ops.push_back(j);
1062 HasUse |= MOj.isUse();
1063 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001064 }
1065 }
1066
Evan Cheng79a796c2008-07-12 01:56:02 +00001067 if (HasUse && !li.liveAt(getUseIndex(index)))
1068 // Must be defined by an implicit def. It should not be spilled. Note,
1069 // this is for correctness reason. e.g.
1070 // 8 %reg1024<def> = IMPLICIT_DEF
1071 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1072 // The live range [12, 14) are not part of the r1024 live interval since
1073 // it's defined by an implicit def. It will not conflicts with live
1074 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001075 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001076 // the INSERT_SUBREG and both target registers that would overlap.
1077 HasUse = false;
1078
Evan Cheng9c3c2212008-06-06 07:54:39 +00001079 // Update stack slot spill weight if we are splitting.
Evan Chengc3417602008-06-21 06:45:54 +00001080 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001081 if (!TrySplit)
1082 SSWeight += Weight;
1083
1084 if (!TryFold)
1085 CanFold = false;
1086 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001087 // Do not fold load / store here if we are splitting. We'll find an
1088 // optimal point to insert a load / store later.
1089 if (!TrySplit) {
1090 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1091 Ops, FoldSS, FoldSlot, Reg)) {
1092 // Folding the load/store can completely change the instruction in
1093 // unpredictable ways, rescan it from the beginning.
1094 HasUse = false;
1095 HasDef = false;
1096 CanFold = false;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001097 if (isRemoved(MI)) {
1098 SSWeight -= Weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001099 break;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001100 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001101 goto RestartInstruction;
1102 }
1103 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001104 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001105 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001106 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001107 }
Evan Chengcddbb832007-11-30 21:23:43 +00001108
1109 // Create a new virtual register for the spill interval.
1110 bool CreatedNewVReg = false;
1111 if (NewVReg == 0) {
Evan Chengd70dbb52008-02-22 09:24:50 +00001112 NewVReg = mri_->createVirtualRegister(rc);
Evan Chengcddbb832007-11-30 21:23:43 +00001113 vrm.grow();
1114 CreatedNewVReg = true;
1115 }
1116 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001117 if (mop.isImplicit())
1118 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001119
1120 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001121 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1122 MachineOperand &mopj = MI->getOperand(Ops[j]);
1123 mopj.setReg(NewVReg);
1124 if (mopj.isImplicit())
1125 rewriteImplicitOps(li, MI, NewVReg, vrm);
1126 }
Evan Chengcddbb832007-11-30 21:23:43 +00001127
Evan Cheng81a03822007-11-17 00:40:40 +00001128 if (CreatedNewVReg) {
1129 if (DefIsReMat) {
1130 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001131 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001132 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001133 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001134 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001135 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001136 }
1137 if (!CanDelete || (HasUse && HasDef)) {
1138 // If this is a two-addr instruction then its use operands are
1139 // rematerializable but its def is not. It should be assigned a
1140 // stack slot.
1141 vrm.assignVirt2StackSlot(NewVReg, Slot);
1142 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001143 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001144 vrm.assignVirt2StackSlot(NewVReg, Slot);
1145 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001146 } else if (HasUse && HasDef &&
1147 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1148 // If this interval hasn't been assigned a stack slot (because earlier
1149 // def is a deleted remat def), do it now.
1150 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1151 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001152 }
1153
Evan Cheng313d4b82008-02-23 00:33:04 +00001154 // Re-matting an instruction with virtual register use. Add the
1155 // register as an implicit use on the use MI.
1156 if (DefIsReMat && ImpUse)
1157 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1158
Evan Chengf2fbca62007-11-12 06:35:08 +00001159 // create a new register interval for this spill / remat.
1160 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001161 if (CreatedNewVReg) {
1162 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001163 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001164 if (TrySplit)
1165 vrm.setIsSplitFromReg(NewVReg, li.reg);
1166 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001167
1168 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001169 if (CreatedNewVReg) {
1170 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1171 nI.getNextValue(~0U, 0, VNInfoAllocator));
1172 DOUT << " +" << LR;
1173 nI.addRange(LR);
1174 } else {
1175 // Extend the split live interval to this def / use.
1176 unsigned End = getUseIndex(index)+1;
1177 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1178 nI.getValNumInfo(nI.getNumValNums()-1));
1179 DOUT << " +" << LR;
1180 nI.addRange(LR);
1181 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001182 }
1183 if (HasDef) {
1184 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1185 nI.getNextValue(~0U, 0, VNInfoAllocator));
1186 DOUT << " +" << LR;
1187 nI.addRange(LR);
1188 }
Evan Cheng81a03822007-11-17 00:40:40 +00001189
Evan Chengf2fbca62007-11-12 06:35:08 +00001190 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001191 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001192 DOUT << '\n';
1193 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001194 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001195}
Evan Cheng81a03822007-11-17 00:40:40 +00001196bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001197 const VNInfo *VNI,
1198 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001199 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001200 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1201 unsigned KillIdx = VNI->kills[j];
1202 if (KillIdx > Idx && KillIdx < End)
1203 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001204 }
1205 return false;
1206}
1207
Evan Cheng063284c2008-02-21 00:34:19 +00001208/// RewriteInfo - Keep track of machine instrs that will be rewritten
1209/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001210namespace {
1211 struct RewriteInfo {
1212 unsigned Index;
1213 MachineInstr *MI;
1214 bool HasUse;
1215 bool HasDef;
1216 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1217 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1218 };
Evan Cheng063284c2008-02-21 00:34:19 +00001219
Dan Gohman844731a2008-05-13 00:00:25 +00001220 struct RewriteInfoCompare {
1221 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1222 return LHS.Index < RHS.Index;
1223 }
1224 };
1225}
Evan Cheng063284c2008-02-21 00:34:19 +00001226
Evan Chengf2fbca62007-11-12 06:35:08 +00001227void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001228rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001229 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001230 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001231 unsigned Slot, int LdSlot,
1232 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001233 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001234 const TargetRegisterClass* rc,
1235 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001236 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001237 BitVector &SpillMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001238 std::map<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001239 BitVector &RestoreMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001240 std::map<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1241 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001242 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001243 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001244 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001245 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001246 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001247
Evan Cheng063284c2008-02-21 00:34:19 +00001248 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001249 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001250 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001251 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1252 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001253 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001254 MachineOperand &O = ri.getOperand();
1255 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001256 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001257 unsigned index = getInstructionIndex(MI);
1258 if (index < start || index >= end)
1259 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001260 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1261 // Must be defined by an implicit def. It should not be spilled. Note,
1262 // this is for correctness reason. e.g.
1263 // 8 %reg1024<def> = IMPLICIT_DEF
1264 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1265 // The live range [12, 14) are not part of the r1024 live interval since
1266 // it's defined by an implicit def. It will not conflicts with live
1267 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001268 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001269 // the INSERT_SUBREG and both target registers that would overlap.
1270 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001271 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1272 }
1273 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1274
Evan Cheng313d4b82008-02-23 00:33:04 +00001275 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001276 // Now rewrite the defs and uses.
1277 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1278 RewriteInfo &rwi = RewriteMIs[i];
1279 ++i;
1280 unsigned index = rwi.Index;
1281 bool MIHasUse = rwi.HasUse;
1282 bool MIHasDef = rwi.HasDef;
1283 MachineInstr *MI = rwi.MI;
1284 // If MI def and/or use the same register multiple times, then there
1285 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001286 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001287 while (i != e && RewriteMIs[i].MI == MI) {
1288 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001289 bool isUse = RewriteMIs[i].HasUse;
1290 if (isUse) ++NumUses;
1291 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001292 MIHasDef |= RewriteMIs[i].HasDef;
1293 ++i;
1294 }
Evan Cheng81a03822007-11-17 00:40:40 +00001295 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001296
Evan Cheng0a891ed2008-05-23 23:00:04 +00001297 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001298 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001299 // register interval's spill weight to HUGE_VALF to prevent it from
1300 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001301 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001302 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001303 }
1304
Evan Cheng063284c2008-02-21 00:34:19 +00001305 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001306 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001307 if (TrySplit) {
Evan Cheng063284c2008-02-21 00:34:19 +00001308 std::map<unsigned,unsigned>::const_iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001309 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001310 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001311 // One common case:
1312 // x = use
1313 // ...
1314 // ...
1315 // def = ...
1316 // = use
1317 // It's better to start a new interval to avoid artifically
1318 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001319 if (MIHasDef && !MIHasUse) {
1320 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001321 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001322 }
1323 }
Evan Chengcada2452007-11-28 01:28:46 +00001324 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001325
1326 bool IsNew = ThisVReg == 0;
1327 if (IsNew) {
1328 // This ends the previous live interval. If all of its def / use
1329 // can be folded, give it a low spill weight.
1330 if (NewVReg && TrySplit && AllCanFold) {
1331 LiveInterval &nI = getOrCreateInterval(NewVReg);
1332 nI.weight /= 10.0F;
1333 }
1334 AllCanFold = true;
1335 }
1336 NewVReg = ThisVReg;
1337
Evan Cheng81a03822007-11-17 00:40:40 +00001338 bool HasDef = false;
1339 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001340 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001341 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1342 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1343 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1344 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001345 if (!HasDef && !HasUse)
1346 continue;
1347
Evan Cheng018f9b02007-12-05 03:22:34 +00001348 AllCanFold &= CanFold;
1349
Evan Cheng81a03822007-11-17 00:40:40 +00001350 // Update weight of spill interval.
1351 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001352 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001353 // The spill weight is now infinity as it cannot be spilled again.
1354 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001355 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001356 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001357
1358 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001359 if (HasDef) {
1360 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001361 bool HasKill = false;
1362 if (!HasUse)
1363 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1364 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001365 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001366 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001367 if (VNI)
1368 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1369 }
Evan Chenge3110d02007-12-01 04:42:39 +00001370 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
1371 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001372 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001373 if (SII == SpillIdxes.end()) {
1374 std::vector<SRInfo> S;
1375 S.push_back(SRInfo(index, NewVReg, true));
1376 SpillIdxes.insert(std::make_pair(MBBId, S));
1377 } else if (SII->second.back().vreg != NewVReg) {
1378 SII->second.push_back(SRInfo(index, NewVReg, true));
1379 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001380 // If there is an earlier def and this is a two-address
1381 // instruction, then it's not possible to fold the store (which
1382 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001383 SRInfo &Info = SII->second.back();
1384 Info.index = index;
1385 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001386 }
1387 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001388 } else if (SII != SpillIdxes.end() &&
1389 SII->second.back().vreg == NewVReg &&
1390 (int)index > SII->second.back().index) {
1391 // There is an earlier def that's not killed (must be two-address).
1392 // The spill is no longer needed.
1393 SII->second.pop_back();
1394 if (SII->second.empty()) {
1395 SpillIdxes.erase(MBBId);
1396 SpillMBBs.reset(MBBId);
1397 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001398 }
1399 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001400 }
1401
1402 if (HasUse) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001403 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001404 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001405 if (SII != SpillIdxes.end() &&
1406 SII->second.back().vreg == NewVReg &&
1407 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001408 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001409 SII->second.back().canFold = false;
1410 std::map<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001411 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001412 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001413 // If we are splitting live intervals, only fold if it's the first
1414 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001415 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001416 else if (IsNew) {
1417 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001418 if (RII == RestoreIdxes.end()) {
1419 std::vector<SRInfo> Infos;
1420 Infos.push_back(SRInfo(index, NewVReg, true));
1421 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1422 } else {
1423 RII->second.push_back(SRInfo(index, NewVReg, true));
1424 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001425 RestoreMBBs.set(MBBId);
1426 }
1427 }
1428
1429 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001430 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001431 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001432 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001433
1434 if (NewVReg && TrySplit && AllCanFold) {
1435 // If all of its def / use can be folded, give it a low spill weight.
1436 LiveInterval &nI = getOrCreateInterval(NewVReg);
1437 nI.weight /= 10.0F;
1438 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001439}
1440
Evan Cheng1953d0c2007-11-29 10:12:14 +00001441bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1442 BitVector &RestoreMBBs,
1443 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1444 if (!RestoreMBBs[Id])
1445 return false;
1446 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1447 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1448 if (Restores[i].index == index &&
1449 Restores[i].vreg == vr &&
1450 Restores[i].canFold)
1451 return true;
1452 return false;
1453}
1454
1455void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1456 BitVector &RestoreMBBs,
1457 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1458 if (!RestoreMBBs[Id])
1459 return;
1460 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1461 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1462 if (Restores[i].index == index && Restores[i].vreg)
1463 Restores[i].index = -1;
1464}
Evan Cheng81a03822007-11-17 00:40:40 +00001465
Evan Cheng4cce6b42008-04-11 17:53:36 +00001466/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1467/// spilled and create empty intervals for their uses.
1468void
1469LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1470 const TargetRegisterClass* rc,
1471 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001472 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1473 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001474 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001475 MachineInstr *MI = &*ri;
1476 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001477 if (O.isDef()) {
1478 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1479 "Register def was not rewritten?");
1480 RemoveMachineInstrFromMaps(MI);
1481 vrm.RemoveMachineInstrFromMaps(MI);
1482 MI->eraseFromParent();
1483 } else {
1484 // This must be an use of an implicit_def so it's not part of the live
1485 // interval. Create a new empty live interval for it.
1486 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1487 unsigned NewVReg = mri_->createVirtualRegister(rc);
1488 vrm.grow();
1489 vrm.setIsImplicitlyDefined(NewVReg);
1490 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1491 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1492 MachineOperand &MO = MI->getOperand(i);
1493 if (MO.isReg() && MO.getReg() == li.reg)
1494 MO.setReg(NewVReg);
1495 }
1496 }
Evan Cheng419852c2008-04-03 16:39:43 +00001497 }
1498}
1499
Evan Cheng81a03822007-11-17 00:40:40 +00001500
Evan Chengf2fbca62007-11-12 06:35:08 +00001501std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001502addIntervalsForSpills(const LiveInterval &li,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001503 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1504 float &SSWeight) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001505 assert(li.weight != HUGE_VALF &&
1506 "attempt to spill already spilled interval!");
1507
1508 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001509 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001510 DOUT << '\n';
1511
Evan Cheng9c3c2212008-06-06 07:54:39 +00001512 // Spill slot weight.
1513 SSWeight = 0.0f;
1514
Evan Cheng81a03822007-11-17 00:40:40 +00001515 // Each bit specify whether it a spill is required in the MBB.
1516 BitVector SpillMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001517 std::map<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001518 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001519 std::map<unsigned, std::vector<SRInfo> > RestoreIdxes;
1520 std::map<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001521 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001522 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001523
1524 unsigned NumValNums = li.getNumValNums();
1525 SmallVector<MachineInstr*, 4> ReMatDefs;
1526 ReMatDefs.resize(NumValNums, NULL);
1527 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1528 ReMatOrigDefs.resize(NumValNums, NULL);
1529 SmallVector<int, 4> ReMatIds;
1530 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1531 BitVector ReMatDelete(NumValNums);
1532 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1533
Evan Cheng81a03822007-11-17 00:40:40 +00001534 // Spilling a split live interval. It cannot be split any further. Also,
1535 // it's also guaranteed to be a single val# / range interval.
1536 if (vrm.getPreSplitReg(li.reg)) {
1537 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001538 // Unset the split kill marker on the last use.
1539 unsigned KillIdx = vrm.getKillPoint(li.reg);
1540 if (KillIdx) {
1541 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1542 assert(KillMI && "Last use disappeared?");
1543 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1544 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001545 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001546 }
Evan Chengadf85902007-12-05 09:51:10 +00001547 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001548 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1549 Slot = vrm.getStackSlot(li.reg);
1550 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1551 MachineInstr *ReMatDefMI = DefIsReMat ?
1552 vrm.getReMaterializedMI(li.reg) : NULL;
1553 int LdSlot = 0;
1554 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1555 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001556 (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001557 bool IsFirstRange = true;
1558 for (LiveInterval::Ranges::const_iterator
1559 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1560 // If this is a split live interval with multiple ranges, it means there
1561 // are two-address instructions that re-defined the value. Only the
1562 // first def can be rematerialized!
1563 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001564 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001565 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1566 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001567 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001568 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001569 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001570 } else {
1571 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1572 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001573 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001574 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001575 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001576 }
1577 IsFirstRange = false;
1578 }
Evan Cheng419852c2008-04-03 16:39:43 +00001579
Evan Cheng9c3c2212008-06-06 07:54:39 +00001580 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng4cce6b42008-04-11 17:53:36 +00001581 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001582 return NewLIs;
1583 }
1584
1585 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001586 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1587 TrySplit = false;
1588 if (TrySplit)
1589 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001590 bool NeedStackSlot = false;
1591 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1592 i != e; ++i) {
1593 const VNInfo *VNI = *i;
1594 unsigned VN = VNI->id;
1595 unsigned DefIdx = VNI->def;
1596 if (DefIdx == ~1U)
1597 continue; // Dead val#.
1598 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001599 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1600 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001601 bool dummy;
1602 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001603 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001604 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001605 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001606 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1607 ClonedMIs.push_back(Clone);
1608 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001609
1610 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001611 if (VNI->hasPHIKill) {
1612 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001613 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001614 CanDelete = false;
1615 // Need a stack slot if there is any live range where uses cannot be
1616 // rematerialized.
1617 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001618 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001619 if (CanDelete)
1620 ReMatDelete.set(VN);
1621 } else {
1622 // Need a stack slot if there is any live range where uses cannot be
1623 // rematerialized.
1624 NeedStackSlot = true;
1625 }
1626 }
1627
1628 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001629 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001630 Slot = vrm.assignVirt2StackSlot(li.reg);
1631
1632 // Create new intervals and rewrite defs and uses.
1633 for (LiveInterval::Ranges::const_iterator
1634 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001635 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1636 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1637 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001638 bool CanDelete = ReMatDelete[I->valno->id];
1639 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001640 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001641 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001642 (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001643 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001644 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001645 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001646 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001647 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengf2fbca62007-11-12 06:35:08 +00001648 }
1649
Evan Cheng0cbb1162007-11-29 01:06:25 +00001650 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001651 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001652 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001653 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00001654 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001655
Evan Chengb50bb8c2007-12-05 08:16:32 +00001656 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001657 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001658 if (NeedStackSlot) {
1659 int Id = SpillMBBs.find_first();
1660 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001661 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1662 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001663 std::vector<SRInfo> &spills = SpillIdxes[Id];
1664 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1665 int index = spills[i].index;
1666 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001667 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001668 bool isReMat = vrm.isReMaterialized(VReg);
1669 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001670 bool CanFold = false;
1671 bool FoundUse = false;
1672 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001673 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001674 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001675 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1676 MachineOperand &MO = MI->getOperand(j);
1677 if (!MO.isRegister() || MO.getReg() != VReg)
1678 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001679
1680 Ops.push_back(j);
1681 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001682 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001683 if (isReMat ||
1684 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1685 RestoreMBBs, RestoreIdxes))) {
1686 // MI has two-address uses of the same register. If the use
1687 // isn't the first and only use in the BB, then we can't fold
1688 // it. FIXME: Move this to rewriteInstructionsForSpills.
1689 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001690 break;
1691 }
Evan Chengaee4af62007-12-02 08:30:39 +00001692 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001693 }
1694 }
1695 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001696 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001697 if (CanFold && !Ops.empty()) {
1698 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001699 Folded = true;
Evan Chengf38d14f2007-12-05 09:05:34 +00001700 if (FoundUse > 0) {
Evan Chengaee4af62007-12-02 08:30:39 +00001701 // Also folded uses, do not issue a load.
1702 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00001703 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
1704 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001705 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00001706 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001707 }
1708
Evan Cheng7e073ba2008-04-09 20:57:25 +00001709 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00001710 if (!Folded) {
1711 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
1712 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00001713 if (!MI->registerDefIsDead(nI.reg))
1714 // No need to spill a dead def.
1715 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001716 if (isKill)
1717 AddedKill.insert(&nI);
1718 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001719
1720 // Update spill slot weight.
1721 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001722 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001723 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001724 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001725 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001726 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001727
Evan Cheng1953d0c2007-11-29 10:12:14 +00001728 int Id = RestoreMBBs.find_first();
1729 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001730 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1731 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
1732
Evan Cheng1953d0c2007-11-29 10:12:14 +00001733 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1734 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
1735 int index = restores[i].index;
1736 if (index == -1)
1737 continue;
1738 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001739 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001740 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001741 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001742 bool CanFold = false;
1743 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001744 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001745 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001746 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1747 MachineOperand &MO = MI->getOperand(j);
1748 if (!MO.isRegister() || MO.getReg() != VReg)
1749 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001750
Evan Cheng0cbb1162007-11-29 01:06:25 +00001751 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00001752 // If this restore were to be folded, it would have been folded
1753 // already.
1754 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00001755 break;
1756 }
Evan Chengaee4af62007-12-02 08:30:39 +00001757 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00001758 }
1759 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001760
1761 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001762 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001763 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001764 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00001765 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
1766 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001767 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
1768 int LdSlot = 0;
1769 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1770 // If the rematerializable def is a load, also try to fold it.
Chris Lattner749c6f62008-01-07 07:27:27 +00001771 if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00001772 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1773 Ops, isLoadSS, LdSlot, VReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001774 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
1775 if (ImpUse) {
1776 // Re-matting an instruction with virtual register use. Add the
1777 // register as an implicit use on the use MI and update the register
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001778 // interval's spill weight to HUGE_VALF to prevent it from being
1779 // spilled.
Evan Chengd70dbb52008-02-22 09:24:50 +00001780 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001781 ImpLi.weight = HUGE_VALF;
Evan Chengd70dbb52008-02-22 09:24:50 +00001782 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1783 }
Evan Chengaee4af62007-12-02 08:30:39 +00001784 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001785 }
1786 // If folding is not possible / failed, then tell the spiller to issue a
1787 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00001788 if (Folded)
1789 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001790 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00001791 vrm.addRestorePoint(VReg, MI);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001792
1793 // Update spill slot weight.
1794 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001795 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Cheng81a03822007-11-17 00:40:40 +00001796 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001797 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00001798 }
1799
Evan Chengb50bb8c2007-12-05 08:16:32 +00001800 // Finalize intervals: add kills, finalize spill weights, and filter out
1801 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00001802 std::vector<LiveInterval*> RetNewLIs;
1803 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
1804 LiveInterval *LI = NewLIs[i];
1805 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00001806 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001807 if (!AddedKill.count(LI)) {
1808 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00001809 unsigned LastUseIdx = getBaseIndex(LR->end);
1810 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00001811 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001812 assert(UseIdx != -1);
Evan Chengd70dbb52008-02-22 09:24:50 +00001813 if (LastUse->getOperand(UseIdx).isImplicit() ||
1814 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chengb50bb8c2007-12-05 08:16:32 +00001815 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00001816 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00001817 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00001818 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001819 RetNewLIs.push_back(LI);
1820 }
1821 }
Evan Cheng81a03822007-11-17 00:40:40 +00001822
Evan Cheng4cce6b42008-04-11 17:53:36 +00001823 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00001824 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00001825}
Evan Cheng676dd7c2008-03-11 07:19:34 +00001826
1827/// hasAllocatableSuperReg - Return true if the specified physical register has
1828/// any super register that's allocatable.
1829bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
1830 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
1831 if (allocatableRegs_[*AS] && hasInterval(*AS))
1832 return true;
1833 return false;
1834}
1835
1836/// getRepresentativeReg - Find the largest super register of the specified
1837/// physical register.
1838unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
1839 // Find the largest super-register that is allocatable.
1840 unsigned BestReg = Reg;
1841 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
1842 unsigned SuperReg = *AS;
1843 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
1844 BestReg = SuperReg;
1845 break;
1846 }
1847 }
1848 return BestReg;
1849}
1850
1851/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
1852/// specified interval that conflicts with the specified physical register.
1853unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
1854 unsigned PhysReg) const {
1855 unsigned NumConflicts = 0;
1856 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
1857 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1858 E = mri_->reg_end(); I != E; ++I) {
1859 MachineOperand &O = I.getOperand();
1860 MachineInstr *MI = O.getParent();
1861 unsigned Index = getInstructionIndex(MI);
1862 if (pli.liveAt(Index))
1863 ++NumConflicts;
1864 }
1865 return NumConflicts;
1866}
1867
1868/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
1869/// around all defs and uses of the specified interval.
1870void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
1871 unsigned PhysReg, VirtRegMap &vrm) {
1872 unsigned SpillReg = getRepresentativeReg(PhysReg);
1873
1874 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
1875 // If there are registers which alias PhysReg, but which are not a
1876 // sub-register of the chosen representative super register. Assert
1877 // since we can't handle it yet.
1878 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
1879 tri_->isSuperRegister(*AS, SpillReg));
1880
1881 LiveInterval &pli = getInterval(SpillReg);
1882 SmallPtrSet<MachineInstr*, 8> SeenMIs;
1883 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1884 E = mri_->reg_end(); I != E; ++I) {
1885 MachineOperand &O = I.getOperand();
1886 MachineInstr *MI = O.getParent();
1887 if (SeenMIs.count(MI))
1888 continue;
1889 SeenMIs.insert(MI);
1890 unsigned Index = getInstructionIndex(MI);
1891 if (pli.liveAt(Index)) {
1892 vrm.addEmergencySpill(SpillReg, MI);
1893 pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1894 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
1895 if (!hasInterval(*AS))
1896 continue;
1897 LiveInterval &spli = getInterval(*AS);
1898 if (spli.liveAt(Index))
1899 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1900 }
1901 }
1902 }
1903}
Owen Andersonc4dc1322008-06-05 17:15:43 +00001904
1905LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1906 MachineInstr* startInst) {
1907 LiveInterval& Interval = getOrCreateInterval(reg);
1908 VNInfo* VN = Interval.getNextValue(
1909 getInstructionIndex(startInst) + InstrSlots::DEF,
1910 startInst, getVNInfoAllocator());
1911 VN->hasPHIKill = true;
1912 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
1913 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
1914 getMBBEndIdx(startInst->getParent()) + 1, VN);
1915 Interval.addRange(LR);
1916
1917 return LR;
1918}