blob: c3c6fee98311127aafdd660a2ef3d606aa9cd428 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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 Lattnera3b8b5c2004-07-23 17:56:30 +000019#include "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 Evlogimenos6b4edba2003-12-21 20:19:10 +000022#include "llvm/Analysis/LoopInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000023#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/MachineInstr.h"
26#include "llvm/CodeGen/Passes.h"
27#include "llvm/CodeGen/SSARegMap.h"
28#include "llvm/Target/MRegisterInfo.h"
29#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>
Misha Brukman08a6c762004-09-03 18:25:53 +000036#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000037using namespace llvm;
38
39namespace {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000040 RegisterAnalysis<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000041
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000042 Statistic<> numIntervals
43 ("liveintervals", "Number of original intervals");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000044
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000045 Statistic<> numIntervalsAfter
46 ("liveintervals", "Number of intervals after coalescing");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000047
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000048 Statistic<> numJoins
49 ("liveintervals", "Number of interval joins performed");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000050
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000051 Statistic<> numPeep
52 ("liveintervals", "Number of identity moves eliminated after coalescing");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000053
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000054 Statistic<> numFolded
55 ("liveintervals", "Number of loads/stores folded into instructions");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000056
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000057 cl::opt<bool>
58 EnableJoining("join-liveintervals",
59 cl::desc("Join compatible live intervals"),
60 cl::init(true));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000061};
62
63void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
64{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000065 AU.addPreserved<LiveVariables>();
66 AU.addRequired<LiveVariables>();
67 AU.addPreservedID(PHIEliminationID);
68 AU.addRequiredID(PHIEliminationID);
69 AU.addRequiredID(TwoAddressInstructionPassID);
70 AU.addRequired<LoopInfo>();
71 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000072}
73
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000074void LiveIntervals::releaseMemory()
75{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 mi2iMap_.clear();
77 i2miMap_.clear();
78 r2iMap_.clear();
79 r2rMap_.clear();
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000080}
81
82
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000083/// runOnMachineFunction - Register allocate the whole function
84///
85bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000086 mf_ = &fn;
87 tm_ = &fn.getTarget();
88 mri_ = tm_->getRegisterInfo();
89 lv_ = &getAnalysis<LiveVariables>();
Alkis Evlogimenos53278012004-08-26 22:22:38 +000090 allocatableRegs_ = mri_->getAllocatableSet(fn);
Alkis Evlogimenos2c4f7b52004-09-09 19:24:38 +000091 r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000092
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000093 // number MachineInstrs
94 unsigned miIndex = 0;
95 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
96 mbb != mbbEnd; ++mbb)
97 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
98 mi != miEnd; ++mi) {
99 bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
100 assert(inserted && "multiple MachineInstr -> index mappings");
101 i2miMap_.push_back(mi);
102 miIndex += InstrSlots::NUM;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000103 }
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000104
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000105 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000106
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000107 numIntervals += getNumIntervals();
108
109#if 1
110 DEBUG(std::cerr << "********** INTERVALS **********\n");
111 DEBUG(for (iterator I = begin(), E = end(); I != E; ++I)
112 std::cerr << I->second << "\n");
113#endif
114
115 // join intervals if requested
116 if (EnableJoining) joinIntervals();
117
118 numIntervalsAfter += getNumIntervals();
119
120 // perform a final pass over the instructions and compute spill
121 // weights, coalesce virtual registers and remove identity moves
122 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
123 const TargetInstrInfo& tii = *tm_->getInstrInfo();
124
125 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
126 mbbi != mbbe; ++mbbi) {
127 MachineBasicBlock* mbb = mbbi;
128 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
129
130 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
131 mii != mie; ) {
132 // if the move will be an identity move delete it
133 unsigned srcReg, dstReg, RegRep;
134 if (tii.isMoveInstr(*mii, srcReg, dstReg) &&
135 (RegRep = rep(srcReg)) == rep(dstReg)) {
136 // remove from def list
137 LiveInterval &interval = getOrCreateInterval(RegRep);
138 // remove index -> MachineInstr and
139 // MachineInstr -> index mappings
140 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
141 if (mi2i != mi2iMap_.end()) {
142 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
143 mi2iMap_.erase(mi2i);
144 }
145 mii = mbbi->erase(mii);
146 ++numPeep;
147 }
148 else {
149 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
150 const MachineOperand& mop = mii->getOperand(i);
151 if (mop.isRegister() && mop.getReg() &&
152 MRegisterInfo::isVirtualRegister(mop.getReg())) {
153 // replace register with representative register
154 unsigned reg = rep(mop.getReg());
155 mii->SetMachineOperandReg(i, reg);
156
157 LiveInterval &RegInt = getInterval(reg);
158 RegInt.weight +=
159 (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth);
160 }
161 }
162 ++mii;
163 }
164 }
165 }
166
Chris Lattner70ca3582004-09-30 15:59:17 +0000167 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000168 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000169}
170
Chris Lattner70ca3582004-09-30 15:59:17 +0000171/// print - Implement the dump method.
172void LiveIntervals::print(std::ostream &O) const {
173 O << "********** INTERVALS **********\n";
174 for (const_iterator I = begin(), E = end(); I != E; ++I)
175 O << I->second << "\n";
176
177 O << "********** MACHINEINSTRS **********\n";
178 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
179 mbbi != mbbe; ++mbbi) {
180 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
181 for (MachineBasicBlock::iterator mii = mbbi->begin(),
182 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000183 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000184 }
185 }
186}
187
188
189std::vector<LiveInterval*> LiveIntervals::
190addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000191 // since this is called after the analysis is done we don't know if
192 // LiveVariables is available
193 lv_ = getAnalysisToUpdate<LiveVariables>();
194
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000195 std::vector<LiveInterval*> added;
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000196
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000197 assert(li.weight != HUGE_VAL &&
198 "attempt to spill already spilled interval!");
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000199
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000200 DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
201 << li << '\n');
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000202
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000203 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000204
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000205 for (LiveInterval::Ranges::const_iterator
206 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
207 unsigned index = getBaseIndex(i->start);
208 unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
209 for (; index != end; index += InstrSlots::NUM) {
210 // skip deleted instructions
211 while (index != end && !getInstructionFromIndex(index))
212 index += InstrSlots::NUM;
213 if (index == end) break;
Chris Lattner8640f4e2004-07-19 15:16:53 +0000214
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000215 MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000216
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000217 for_operand:
218 for (unsigned i = 0; i != mi->getNumOperands(); ++i) {
219 MachineOperand& mop = mi->getOperand(i);
220 if (mop.isRegister() && mop.getReg() == li.reg) {
Chris Lattner477e4552004-09-30 16:10:45 +0000221 // First thing, attempt to fold the memory reference into the
222 // instruction. If we can do this, we don't need to insert spill
223 // code.
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000224 if (MachineInstr* fmi = mri_->foldMemoryOperand(mi, i, slot)) {
225 if (lv_)
226 lv_->instructionChanged(mi, fmi);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000227 vrm.virtFolded(li.reg, mi, fmi);
228 mi2iMap_.erase(mi);
229 i2miMap_[index/InstrSlots::NUM] = fmi;
230 mi2iMap_[fmi] = index;
Chris Lattner477e4552004-09-30 16:10:45 +0000231 MachineBasicBlock &MBB = *mi->getParent();
232 mi = MBB.insert(MBB.erase(mi), fmi);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000233 ++numFolded;
Chris Lattner477e4552004-09-30 16:10:45 +0000234
235 // Folding the load/store can completely change the instruction in
236 // unpredictable ways, rescan it from the beginning.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000237 goto for_operand;
Chris Lattner477e4552004-09-30 16:10:45 +0000238 } else {
Chris Lattner70ca3582004-09-30 15:59:17 +0000239 // This is tricky. We need to add information in the interval about
240 // the spill code so we have to use our extra load/store slots.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000241 //
Chris Lattner70ca3582004-09-30 15:59:17 +0000242 // If we have a use we are going to have a load so we start the
243 // interval from the load slot onwards. Otherwise we start from the
244 // def slot.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000245 unsigned start = (mop.isUse() ?
246 getLoadIndex(index) :
247 getDefIndex(index));
Chris Lattner70ca3582004-09-30 15:59:17 +0000248 // If we have a def we are going to have a store right after it so
249 // we end the interval after the use of the next
250 // instruction. Otherwise we end after the use of this instruction.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000251 unsigned end = 1 + (mop.isDef() ?
252 getStoreIndex(index) :
253 getUseIndex(index));
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000254
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000255 // create a new register for this spill
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000256 unsigned nReg = mf_->getSSARegMap()->createVirtualRegister(rc);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000257 mi->SetMachineOperandReg(i, nReg);
258 vrm.grow();
259 vrm.assignVirt2StackSlot(nReg, slot);
260 LiveInterval& nI = getOrCreateInterval(nReg);
261 assert(nI.empty());
Chris Lattner70ca3582004-09-30 15:59:17 +0000262
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000263 // the spill weight is now infinity as it
264 // cannot be spilled again
265 nI.weight = HUGE_VAL;
266 LiveRange LR(start, end, nI.getNextValue());
267 DEBUG(std::cerr << " +" << LR);
268 nI.addRange(LR);
269 added.push_back(&nI);
Chris Lattner70ca3582004-09-30 15:59:17 +0000270
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000271 // update live variables if it is available
272 if (lv_)
273 lv_->addVirtualRegisterKilled(nReg, mi);
274 DEBUG(std::cerr << "\t\t\t\tadded new interval: " << nI << '\n');
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000275 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000276 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000277 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000278 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000279 }
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000280
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000281 return added;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000282}
283
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000284void LiveIntervals::printRegName(unsigned reg) const
285{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000286 if (MRegisterInfo::isPhysicalRegister(reg))
287 std::cerr << mri_->getName(reg);
288 else
289 std::cerr << "%reg" << reg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000290}
291
292void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
293 MachineBasicBlock::iterator mi,
Chris Lattner418da552004-06-21 13:10:56 +0000294 LiveInterval& interval)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000295{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000296 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
297 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000298
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000299 // Virtual registers may be defined multiple times (due to phi
300 // elimination and 2-addr elimination). Much of what we do only has to be
301 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000302 // time we see a vreg.
303 if (interval.empty()) {
304 // Get the Idx of the defining instructions.
305 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
Chris Lattner6097d132004-07-19 02:15:56 +0000306
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000307 unsigned ValNum = interval.getNextValue();
308 assert(ValNum == 0 && "First value in interval is not 0?");
309 ValNum = 0; // Clue in the optimizer.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000310
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000311 // Loop over all of the blocks that the vreg is defined in. There are
312 // two cases we have to handle here. The most common case is a vreg
313 // whose lifetime is contained within a basic block. In this case there
314 // will be a single kill, in MBB, which comes after the definition.
315 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
316 // FIXME: what about dead vars?
317 unsigned killIdx;
318 if (vi.Kills[0] != mi)
319 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
320 else
321 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000322
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000323 // If the kill happens after the definition, we have an intra-block
324 // live range.
325 if (killIdx > defIndex) {
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000326 assert(vi.AliveBlocks.empty() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000327 "Shouldn't be alive across any blocks!");
328 LiveRange LR(defIndex, killIdx, ValNum);
329 interval.addRange(LR);
330 DEBUG(std::cerr << " +" << LR << "\n");
331 return;
332 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000333 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000334
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000335 // The other case we handle is when a virtual register lives to the end
336 // of the defining block, potentially live across some blocks, then is
337 // live into some number of blocks, but gets killed. Start by adding a
338 // range that goes from this definition to the end of the defining block.
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000339 LiveRange NewLR(defIndex,
340 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
341 ValNum);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000342 DEBUG(std::cerr << " +" << NewLR);
343 interval.addRange(NewLR);
344
345 // Iterate over all of the blocks that the variable is completely
346 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
347 // live interval.
348 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
349 if (vi.AliveBlocks[i]) {
350 MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
351 if (!mbb->empty()) {
352 LiveRange LR(getInstructionIndex(&mbb->front()),
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000353 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000354 ValNum);
355 interval.addRange(LR);
356 DEBUG(std::cerr << " +" << LR);
357 }
358 }
359 }
360
361 // Finally, this virtual register is live from the start of any killing
362 // block to the 'use' slot of the killing instruction.
363 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
364 MachineInstr *Kill = vi.Kills[i];
365 LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000366 getUseIndex(getInstructionIndex(Kill))+1,
367 ValNum);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000368 interval.addRange(LR);
369 DEBUG(std::cerr << " +" << LR);
370 }
371
372 } else {
373 // If this is the second time we see a virtual register definition, it
374 // must be due to phi elimination or two addr elimination. If this is
375 // the result of two address elimination, then the vreg is the first
376 // operand, and is a def-and-use.
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000377 if (mi->getOperand(0).isRegister() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000378 mi->getOperand(0).getReg() == interval.reg &&
379 mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
380 // If this is a two-address definition, then we have already processed
381 // the live range. The only problem is that we didn't realize there
382 // are actually two values in the live interval. Because of this we
383 // need to take the LiveRegion that defines this register and split it
384 // into two values.
385 unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
386 unsigned RedefIndex = getDefIndex(getInstructionIndex(mi));
387
388 // Delete the initial value, which should be short and continuous,
389 // becuase the 2-addr copy must be in the same MBB as the redef.
390 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000391
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000392 LiveRange LR(DefIndex, RedefIndex, interval.getNextValue());
393 DEBUG(std::cerr << " replace range with " << LR);
394 interval.addRange(LR);
395
396 // If this redefinition is dead, we need to add a dummy unit live
397 // range covering the def slot.
398 for (LiveVariables::killed_iterator KI = lv_->dead_begin(mi),
399 E = lv_->dead_end(mi); KI != E; ++KI)
400 if (KI->second == interval.reg) {
401 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
402 break;
403 }
404
405 DEBUG(std::cerr << "RESULT: " << interval);
406
407 } else {
408 // Otherwise, this must be because of phi elimination. If this is the
409 // first redefinition of the vreg that we have seen, go back and change
410 // the live range in the PHI block to be a different value number.
411 if (interval.containsOneValue()) {
412 assert(vi.Kills.size() == 1 &&
413 "PHI elimination vreg should have one kill, the PHI itself!");
414
415 // Remove the old range that we now know has an incorrect number.
416 MachineInstr *Killer = vi.Kills[0];
417 unsigned Start = getInstructionIndex(Killer->getParent()->begin());
418 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
419 DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: "
420 << interval << "\n");
421 interval.removeRange(Start, End);
422 DEBUG(std::cerr << "RESULT: " << interval);
423
424 // Replace the interval with one of a NEW value number.
425 LiveRange LR(Start, End, interval.getNextValue());
426 DEBUG(std::cerr << " replace range with " << LR);
427 interval.addRange(LR);
428 DEBUG(std::cerr << "RESULT: " << interval);
429 }
430
431 // In the case of PHI elimination, each variable definition is only
432 // live until the end of the block. We've already taken care of the
433 // rest of the live range.
434 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000435 LiveRange LR(defIndex,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000436 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
437 interval.getNextValue());
438 interval.addRange(LR);
439 DEBUG(std::cerr << " +" << LR);
440 }
441 }
442
443 DEBUG(std::cerr << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000444}
445
Chris Lattnerf35fef72004-07-23 21:24:19 +0000446void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000447 MachineBasicBlock::iterator mi,
Chris Lattner418da552004-06-21 13:10:56 +0000448 LiveInterval& interval)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000449{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000450 // A physical register cannot be live across basic block, so its
451 // lifetime must end somewhere in its defining basic block.
452 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
453 typedef LiveVariables::killed_iterator KillIter;
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000454
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000455 unsigned baseIndex = getInstructionIndex(mi);
456 unsigned start = getDefIndex(baseIndex);
457 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000458
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000459 // If it is not used after definition, it is considered dead at
460 // the instruction defining it. Hence its interval is:
461 // [defSlot(def), defSlot(def)+1)
462 for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
463 ki != ke; ++ki) {
464 if (interval.reg == ki->second) {
465 DEBUG(std::cerr << " dead");
466 end = getDefIndex(start) + 1;
467 goto exit;
468 }
469 }
470
471 // If it is not dead on definition, it must be killed by a
472 // subsequent instruction. Hence its interval is:
473 // [defSlot(def), useSlot(kill)+1)
474 while (true) {
475 ++mi;
476 assert(mi != MBB->end() && "physreg was not killed in defining block!");
477 baseIndex += InstrSlots::NUM;
478 for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000479 ki != ke; ++ki) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000480 if (interval.reg == ki->second) {
481 DEBUG(std::cerr << " killed");
482 end = getUseIndex(baseIndex) + 1;
483 goto exit;
484 }
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000485 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000486 }
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000487
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000488exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000489 assert(start < end && "did not find end of interval?");
490 LiveRange LR(start, end, interval.getNextValue());
491 interval.addRange(LR);
492 DEBUG(std::cerr << " +" << LR << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000493}
494
Chris Lattnerf35fef72004-07-23 21:24:19 +0000495void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
496 MachineBasicBlock::iterator MI,
497 unsigned reg) {
498 if (MRegisterInfo::isVirtualRegister(reg))
499 handleVirtualRegisterDef(MBB, MI, getOrCreateInterval(reg));
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000500 else if (allocatableRegs_[reg]) {
Chris Lattnerf35fef72004-07-23 21:24:19 +0000501 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(reg));
502 for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
503 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(*AS));
504 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000505}
506
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000507/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000508/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000509/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000510/// which a variable is live
511void LiveIntervals::computeIntervals()
512{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000513 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
514 DEBUG(std::cerr << "********** Function: "
515 << ((Value*)mf_->getFunction())->getName() << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000516
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000517 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000518 I != E; ++I) {
519 MachineBasicBlock* mbb = I;
520 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000521
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000522 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
523 mi != miEnd; ++mi) {
524 const TargetInstrDescriptor& tid =
525 tm_->getInstrInfo()->get(mi->getOpcode());
Chris Lattner477e4552004-09-30 16:10:45 +0000526 DEBUG(std::cerr << getInstructionIndex(mi) << "\t" << *mi);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000527
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000528 // handle implicit defs
529 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
530 handleRegisterDef(mbb, mi, *id);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000531
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000532 // handle explicit defs
533 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
534 MachineOperand& mop = mi->getOperand(i);
535 // handle register defs - build intervals
536 if (mop.isRegister() && mop.getReg() && mop.isDef())
537 handleRegisterDef(mbb, mi, mop.getReg());
538 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000539 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000540 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000541}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000542
Chris Lattner1c5c0442004-07-19 14:08:10 +0000543void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
Chris Lattner7ac2d312004-07-24 02:59:07 +0000544 DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
545 const TargetInstrInfo &TII = *tm_->getInstrInfo();
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000546
Chris Lattner7ac2d312004-07-24 02:59:07 +0000547 for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
548 mi != mie; ++mi) {
549 DEBUG(std::cerr << getInstructionIndex(mi) << '\t' << *mi);
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000550
Chris Lattner7ac2d312004-07-24 02:59:07 +0000551 // we only join virtual registers with allocatable
552 // physical registers since we do not have liveness information
553 // on not allocatable physical registers
554 unsigned regA, regB;
555 if (TII.isMoveInstr(*mi, regA, regB) &&
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000556 (MRegisterInfo::isVirtualRegister(regA) || allocatableRegs_[regA]) &&
557 (MRegisterInfo::isVirtualRegister(regB) || allocatableRegs_[regB])) {
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000558
Chris Lattner7ac2d312004-07-24 02:59:07 +0000559 // Get representative registers.
560 regA = rep(regA);
561 regB = rep(regB);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000562
Chris Lattner7ac2d312004-07-24 02:59:07 +0000563 // If they are already joined we continue.
564 if (regA == regB)
565 continue;
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000566
Chris Lattner7ac2d312004-07-24 02:59:07 +0000567 // If they are both physical registers, we cannot join them.
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000568 if (MRegisterInfo::isPhysicalRegister(regA) &&
Chris Lattner7ac2d312004-07-24 02:59:07 +0000569 MRegisterInfo::isPhysicalRegister(regB))
570 continue;
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000571
Chris Lattner7ac2d312004-07-24 02:59:07 +0000572 // If they are not of the same register class, we cannot join them.
573 if (differingRegisterClasses(regA, regB))
574 continue;
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000575
Chris Lattner7ac2d312004-07-24 02:59:07 +0000576 LiveInterval &IntA = getInterval(regA);
577 LiveInterval &IntB = getInterval(regB);
578 assert(IntA.reg == regA && IntB.reg == regB &&
579 "Register mapping is horribly broken!");
Chris Lattner060913c2004-07-24 04:32:22 +0000580
581 DEBUG(std::cerr << "\t\tInspecting " << IntA << " and " << IntB << ": ");
582
Chris Lattner4df98e52004-07-24 03:32:06 +0000583 // If two intervals contain a single value and are joined by a copy, it
584 // does not matter if the intervals overlap, they can always be joined.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000585 bool TriviallyJoinable =
586 IntA.containsOneValue() && IntB.containsOneValue();
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000587
Chris Lattner7ac2d312004-07-24 02:59:07 +0000588 unsigned MIDefIdx = getDefIndex(getInstructionIndex(mi));
Chris Lattnerc25b55a2004-07-25 07:47:25 +0000589 if ((TriviallyJoinable || IntB.joinable(IntA, MIDefIdx)) &&
Chris Lattner7ac2d312004-07-24 02:59:07 +0000590 !overlapsAliases(&IntA, &IntB)) {
591 IntB.join(IntA, MIDefIdx);
Chris Lattner1c5c0442004-07-19 14:08:10 +0000592
Chris Lattner7ac2d312004-07-24 02:59:07 +0000593 if (!MRegisterInfo::isPhysicalRegister(regA)) {
Chris Lattner4df98e52004-07-24 03:32:06 +0000594 r2iMap_.erase(regA);
Chris Lattner7ac2d312004-07-24 02:59:07 +0000595 r2rMap_[regA] = regB;
596 } else {
597 // Otherwise merge the data structures the other way so we don't lose
598 // the physreg information.
599 r2rMap_[regB] = regA;
600 IntB.reg = regA;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000601 IntA.swap(IntB);
Chris Lattner4df98e52004-07-24 03:32:06 +0000602 r2iMap_.erase(regB);
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000603 }
Chris Lattner7ac2d312004-07-24 02:59:07 +0000604 DEBUG(std::cerr << "Joined. Result = " << IntB << "\n");
605 ++numJoins;
606 } else {
607 DEBUG(std::cerr << "Interference!\n");
608 }
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000609 }
Chris Lattner7ac2d312004-07-24 02:59:07 +0000610 }
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000611}
612
Chris Lattnercc0d1562004-07-19 14:40:29 +0000613namespace {
614 // DepthMBBCompare - Comparison predicate that sort first based on the loop
615 // depth of the basic block (the unsigned), and then on the MBB number.
616 struct DepthMBBCompare {
617 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
618 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
619 if (LHS.first > RHS.first) return true; // Deeper loops first
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000620 return LHS.first == RHS.first &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000621 LHS.second->getNumber() < RHS.second->getNumber();
Chris Lattnercc0d1562004-07-19 14:40:29 +0000622 }
623 };
624}
Chris Lattner1c5c0442004-07-19 14:08:10 +0000625
Chris Lattnercc0d1562004-07-19 14:40:29 +0000626void LiveIntervals::joinIntervals() {
627 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
628
629 const LoopInfo &LI = getAnalysis<LoopInfo>();
630 if (LI.begin() == LI.end()) {
631 // If there are no loops in the function, join intervals in function order.
Chris Lattner1c5c0442004-07-19 14:08:10 +0000632 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
633 I != E; ++I)
634 joinIntervalsInMachineBB(I);
Chris Lattnercc0d1562004-07-19 14:40:29 +0000635 } else {
636 // Otherwise, join intervals in inner loops before other intervals.
637 // Unfortunately we can't just iterate over loop hierarchy here because
638 // there may be more MBB's than BB's. Collect MBB's for sorting.
639 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
640 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
641 I != E; ++I)
642 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
643
644 // Sort by loop depth.
645 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
646
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000647 // Finally, join intervals in loop nest order.
Chris Lattnercc0d1562004-07-19 14:40:29 +0000648 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
649 joinIntervalsInMachineBB(MBBs[i].second);
650 }
Chris Lattnerc83e40d2004-07-25 03:24:11 +0000651
652 DEBUG(std::cerr << "*** Register mapping ***\n");
Alkis Evlogimenos5d0d1e32004-09-08 03:01:50 +0000653 DEBUG(for (int i = 0, e = r2rMap_.size(); i != e; ++i)
654 if (r2rMap_[i])
655 std::cerr << " reg " << i << " -> reg " << r2rMap_[i] << "\n");
Chris Lattner1c5c0442004-07-19 14:08:10 +0000656}
657
Chris Lattner7ac2d312004-07-24 02:59:07 +0000658/// Return true if the two specified registers belong to different register
659/// classes. The registers may be either phys or virt regs.
660bool LiveIntervals::differingRegisterClasses(unsigned RegA,
661 unsigned RegB) const {
662 const TargetRegisterClass *RegClass;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000663
Chris Lattner7ac2d312004-07-24 02:59:07 +0000664 // Get the register classes for the first reg.
665 if (MRegisterInfo::isVirtualRegister(RegA))
666 RegClass = mf_->getSSARegMap()->getRegClass(RegA);
667 else
668 RegClass = mri_->getRegClass(RegA);
669
670 // Compare against the regclass for the second reg.
671 if (MRegisterInfo::isVirtualRegister(RegB))
672 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
673 else
Chris Lattnerd0d0a1a2004-08-24 17:48:29 +0000674 return !RegClass->contains(RegB);
Chris Lattner7ac2d312004-07-24 02:59:07 +0000675}
676
677bool LiveIntervals::overlapsAliases(const LiveInterval *LHS,
678 const LiveInterval *RHS) const {
679 if (!MRegisterInfo::isPhysicalRegister(LHS->reg)) {
680 if (!MRegisterInfo::isPhysicalRegister(RHS->reg))
681 return false; // vreg-vreg merge has no aliases!
682 std::swap(LHS, RHS);
683 }
684
685 assert(MRegisterInfo::isPhysicalRegister(LHS->reg) &&
686 MRegisterInfo::isVirtualRegister(RHS->reg) &&
687 "first interval must describe a physical register");
688
Chris Lattner4df98e52004-07-24 03:32:06 +0000689 for (const unsigned *AS = mri_->getAliasSet(LHS->reg); *AS; ++AS)
690 if (RHS->overlaps(getInterval(*AS)))
691 return true;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000692
Chris Lattner4df98e52004-07-24 03:32:06 +0000693 return false;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000694}
695
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000696LiveInterval LiveIntervals::createInterval(unsigned reg) {
Chris Lattner4df98e52004-07-24 03:32:06 +0000697 float Weight = MRegisterInfo::isPhysicalRegister(reg) ? HUGE_VAL :0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000698 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000699}