blob: eef117af300f030f706b00e3f66ab0cb7f18e7e8 [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 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"
Evan Cheng81a03822007-11-17 00:40:40 +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>
Jeff Cohen97af7512006-12-02 02:22:01 +000036#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000037using namespace llvm;
38
Evan Chengbc165e42007-08-16 07:24:22 +000039namespace {
40 // Hidden options for help debugging.
41 cl::opt<bool> DisableReMat("disable-rematerialization",
42 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000043
44 cl::opt<bool> SplitAtBB("split-intervals-at-bb",
Evan Cheng0cbb1162007-11-29 01:06:25 +000045 cl::init(false), cl::Hidden);
46 cl::opt<int> SplitLimit("split-limit",
47 cl::init(-1), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000048}
49
Chris Lattnercd3245a2006-12-19 22:41:21 +000050STATISTIC(numIntervals, "Number of original intervals");
51STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
Evan Cheng0cbb1162007-11-29 01:06:25 +000052STATISTIC(numFolds , "Number of loads/stores folded into instructions");
53STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000054
Devang Patel19974732007-05-03 01:11:54 +000055char LiveIntervals::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000056namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +000057 RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Chris Lattnerd74ea2b2006-05-24 17:04:05 +000058}
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000059
Chris Lattnerf7da2c72006-08-24 22:43:55 +000060void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
David Greene25133302007-06-08 17:18:56 +000061 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000062 AU.addRequired<LiveVariables>();
63 AU.addPreservedID(PHIEliminationID);
64 AU.addRequiredID(PHIEliminationID);
65 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000066 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000067}
68
Chris Lattnerf7da2c72006-08-24 22:43:55 +000069void LiveIntervals::releaseMemory() {
Evan Cheng4ca980e2007-10-17 02:10:22 +000070 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000071 mi2iMap_.clear();
72 i2miMap_.clear();
73 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000074 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
75 VNInfoAllocator.Reset();
Evan Cheng549f27d32007-08-13 23:45:17 +000076 for (unsigned i = 0, e = ClonedMIs.size(); i != e; ++i)
77 delete ClonedMIs[i];
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000078}
79
Evan Cheng4ca980e2007-10-17 02:10:22 +000080namespace llvm {
81 inline bool operator<(unsigned V, const IdxMBBPair &IM) {
82 return V < IM.first;
83 }
84
85 inline bool operator<(const IdxMBBPair &IM, unsigned V) {
86 return IM.first < V;
87 }
88
89 struct Idx2MBBCompare {
90 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
91 return LHS.first < RHS.first;
92 }
93 };
94}
95
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000096/// runOnMachineFunction - Register allocate the whole function
97///
98bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000099 mf_ = &fn;
100 tm_ = &fn.getTarget();
101 mri_ = tm_->getRegisterInfo();
Chris Lattnerf768bba2005-03-09 23:05:19 +0000102 tii_ = tm_->getInstrInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000103 lv_ = &getAnalysis<LiveVariables>();
Evan Cheng20b0abc2007-04-17 20:32:26 +0000104 allocatableRegs_ = mri_->getAllocatableSet(fn);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000105
Chris Lattner428b92e2006-09-15 03:57:23 +0000106 // Number MachineInstrs and MachineBasicBlocks.
107 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +0000108 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +0000109
110 unsigned MIIndex = 0;
111 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
112 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000113 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000114
Chris Lattner428b92e2006-09-15 03:57:23 +0000115 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
116 I != E; ++I) {
117 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000118 assert(inserted && "multiple MachineInstr -> index mappings");
Chris Lattner428b92e2006-09-15 03:57:23 +0000119 i2miMap_.push_back(I);
120 MIIndex += InstrSlots::NUM;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000121 }
Evan Cheng549f27d32007-08-13 23:45:17 +0000122
123 // Set the MBB2IdxMap entry for this MBB.
124 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
Evan Cheng4ca980e2007-10-17 02:10:22 +0000125 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000126 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000127 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000128
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000129 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000130
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000131 numIntervals += getNumIntervals();
132
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000133 DOUT << "********** INTERVALS **********\n";
134 for (iterator I = begin(), E = end(); I != E; ++I) {
135 I->second.print(DOUT, mri_);
136 DOUT << "\n";
137 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000138
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000139 numIntervalsAfter += getNumIntervals();
Chris Lattner70ca3582004-09-30 15:59:17 +0000140 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000141 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000142}
143
Chris Lattner70ca3582004-09-30 15:59:17 +0000144/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000145void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000146 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000147 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000148 I->second.print(DOUT, mri_);
149 DOUT << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000150 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000151
152 O << "********** MACHINEINSTRS **********\n";
153 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
154 mbbi != mbbe; ++mbbi) {
155 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
156 for (MachineBasicBlock::iterator mii = mbbi->begin(),
157 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000158 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000159 }
160 }
161}
162
Evan Chengc92da382007-11-03 07:20:12 +0000163/// conflictsWithPhysRegDef - Returns true if the specified register
164/// is defined during the duration of the specified interval.
165bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
166 VirtRegMap &vrm, unsigned reg) {
167 for (LiveInterval::Ranges::const_iterator
168 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
169 for (unsigned index = getBaseIndex(I->start),
170 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
171 index += InstrSlots::NUM) {
172 // skip deleted instructions
173 while (index != end && !getInstructionFromIndex(index))
174 index += InstrSlots::NUM;
175 if (index == end) break;
176
177 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng5d446262007-11-15 08:13:29 +0000178 unsigned SrcReg, DstReg;
179 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
180 if (SrcReg == li.reg || DstReg == li.reg)
181 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000182 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
183 MachineOperand& mop = MI->getOperand(i);
Evan Cheng5d446262007-11-15 08:13:29 +0000184 if (!mop.isRegister())
Evan Chengc92da382007-11-03 07:20:12 +0000185 continue;
186 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000187 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000188 continue;
Evan Cheng5d446262007-11-15 08:13:29 +0000189 if (MRegisterInfo::isVirtualRegister(PhysReg)) {
190 if (!vrm.hasPhys(PhysReg))
191 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000192 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000193 }
Evan Cheng5f5f3b62007-11-05 00:59:10 +0000194 if (PhysReg && mri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000195 return true;
196 }
197 }
198 }
199
200 return false;
201}
202
Evan Cheng549f27d32007-08-13 23:45:17 +0000203void LiveIntervals::printRegName(unsigned reg) const {
204 if (MRegisterInfo::isPhysicalRegister(reg))
205 cerr << mri_->getName(reg);
206 else
207 cerr << "%reg" << reg;
208}
209
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000210void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000211 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000212 unsigned MIIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000213 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000214 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000215 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000216
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000217 // Virtual registers may be defined multiple times (due to phi
218 // elimination and 2-addr elimination). Much of what we do only has to be
219 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000220 // time we see a vreg.
221 if (interval.empty()) {
222 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000223 unsigned defIndex = getDefIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000224 VNInfo *ValNo;
Chris Lattner91725b72006-08-31 05:54:43 +0000225 unsigned SrcReg, DstReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +0000226 if (tii_->isMoveInstr(*mi, SrcReg, DstReg))
Evan Chengf3bb2e62007-09-05 21:46:51 +0000227 ValNo = interval.getNextValue(defIndex, SrcReg, VNInfoAllocator);
Evan Cheng48ff2822007-10-12 17:16:50 +0000228 else if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
Evan Cheng32dfbea2007-10-12 08:50:34 +0000229 ValNo = interval.getNextValue(defIndex, mi->getOperand(1).getReg(),
230 VNInfoAllocator);
231 else
232 ValNo = interval.getNextValue(defIndex, 0, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000233
234 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000235
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000236 // Loop over all of the blocks that the vreg is defined in. There are
237 // two cases we have to handle here. The most common case is a vreg
238 // whose lifetime is contained within a basic block. In this case there
239 // will be a single kill, in MBB, which comes after the definition.
240 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
241 // FIXME: what about dead vars?
242 unsigned killIdx;
243 if (vi.Kills[0] != mi)
244 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
245 else
246 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000247
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000248 // If the kill happens after the definition, we have an intra-block
249 // live range.
250 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000251 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000252 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000253 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000254 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000255 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000256 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000257 return;
258 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000259 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000260
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000261 // The other case we handle is when a virtual register lives to the end
262 // of the defining block, potentially live across some blocks, then is
263 // live into some number of blocks, but gets killed. Start by adding a
264 // range that goes from this definition to the end of the defining block.
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000265 LiveRange NewLR(defIndex,
266 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000267 ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000268 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000269 interval.addRange(NewLR);
270
271 // Iterate over all of the blocks that the variable is completely
272 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
273 // live interval.
274 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
275 if (vi.AliveBlocks[i]) {
Chris Lattner428b92e2006-09-15 03:57:23 +0000276 MachineBasicBlock *MBB = mf_->getBlockNumbered(i);
277 if (!MBB->empty()) {
278 LiveRange LR(getMBBStartIdx(i),
279 getInstructionIndex(&MBB->back()) + InstrSlots::NUM,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000280 ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000281 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000282 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000283 }
284 }
285 }
286
287 // Finally, this virtual register is live from the start of any killing
288 // block to the 'use' slot of the killing instruction.
289 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
290 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000291 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000292 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000293 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000294 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000295 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000296 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000297 }
298
299 } else {
300 // If this is the second time we see a virtual register definition, it
301 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000302 // the result of two address elimination, then the vreg is one of the
303 // def-and-use register operand.
Evan Cheng32dfbea2007-10-12 08:50:34 +0000304 if (mi->isRegReDefinedByTwoAddr(interval.reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000305 // If this is a two-address definition, then we have already processed
306 // the live range. The only problem is that we didn't realize there
307 // are actually two values in the live interval. Because of this we
308 // need to take the LiveRegion that defines this register and split it
309 // into two values.
310 unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
Chris Lattner6b128bd2006-09-03 08:07:11 +0000311 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000312
Evan Cheng4f8ff162007-08-11 00:59:19 +0000313 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000314 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000315 unsigned OldEnd = OldLR->end;
316
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000317 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000318 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000319 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000320
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000321 // Two-address vregs should always only be redefined once. This means
322 // that at this point, there should be exactly one value number in it.
323 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
324
Chris Lattner91725b72006-08-31 05:54:43 +0000325 // The new value number (#1) is defined by the instruction we claimed
326 // defined value #0.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000327 VNInfo *ValNo = interval.getNextValue(0, 0, VNInfoAllocator);
328 interval.copyValNumInfo(ValNo, OldValNo);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000329
Chris Lattner91725b72006-08-31 05:54:43 +0000330 // Value#0 is now defined by the 2-addr instruction.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000331 OldValNo->def = RedefIndex;
332 OldValNo->reg = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000333
334 // Add the new live interval which replaces the range for the input copy.
335 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000336 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000337 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000338 interval.addKill(ValNo, RedefIndex);
339 interval.removeKills(ValNo, RedefIndex, OldEnd);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000340
341 // If this redefinition is dead, we need to add a dummy unit live
342 // range covering the def slot.
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000343 if (lv_->RegisterDefIsDead(mi, interval.reg))
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000344 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000345
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000346 DOUT << " RESULT: ";
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000347 interval.print(DOUT, mri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348
349 } else {
350 // Otherwise, this must be because of phi elimination. If this is the
351 // first redefinition of the vreg that we have seen, go back and change
352 // the live range in the PHI block to be a different value number.
353 if (interval.containsOneValue()) {
354 assert(vi.Kills.size() == 1 &&
355 "PHI elimination vreg should have one kill, the PHI itself!");
356
357 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000358 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000359 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000360 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000361 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000362 DOUT << " Removing [" << Start << "," << End << "] from: ";
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000363 interval.print(DOUT, mri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000364 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000365 interval.addKill(VNI, Start);
366 VNI->hasPHIKill = true;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000367 DOUT << " RESULT: "; interval.print(DOUT, mri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000368
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000369 // Replace the interval with one of a NEW value number. Note that this
370 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000371 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000372 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000373 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000374 interval.addKill(LR.valno, End);
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000375 DOUT << " RESULT: "; interval.print(DOUT, mri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000376 }
377
378 // In the case of PHI elimination, each variable definition is only
379 // live until the end of the block. We've already taken care of the
380 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000381 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000382
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000383 VNInfo *ValNo;
Chris Lattner91725b72006-08-31 05:54:43 +0000384 unsigned SrcReg, DstReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +0000385 if (tii_->isMoveInstr(*mi, SrcReg, DstReg))
Evan Chengf3bb2e62007-09-05 21:46:51 +0000386 ValNo = interval.getNextValue(defIndex, SrcReg, VNInfoAllocator);
Evan Cheng32dfbea2007-10-12 08:50:34 +0000387 else if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
388 ValNo = interval.getNextValue(defIndex, mi->getOperand(1).getReg(),
389 VNInfoAllocator);
390 else
391 ValNo = interval.getNextValue(defIndex, 0, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000392
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000393 unsigned killIndex = getInstructionIndex(&mbb->back()) + InstrSlots::NUM;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000394 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000395 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000396 interval.addKill(ValNo, killIndex);
397 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000398 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000399 }
400 }
401
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000402 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000403}
404
Chris Lattnerf35fef72004-07-23 21:24:19 +0000405void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000406 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000407 unsigned MIIdx,
Chris Lattner91725b72006-08-31 05:54:43 +0000408 LiveInterval &interval,
409 unsigned SrcReg) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000410 // A physical register cannot be live across basic block, so its
411 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000412 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000413
Chris Lattner6b128bd2006-09-03 08:07:11 +0000414 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000415 unsigned start = getDefIndex(baseIndex);
416 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000417
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000418 // If it is not used after definition, it is considered dead at
419 // the instruction defining it. Hence its interval is:
420 // [defSlot(def), defSlot(def)+1)
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000421 if (lv_->RegisterDefIsDead(mi, interval.reg)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000422 DOUT << " dead";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000423 end = getDefIndex(start) + 1;
424 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000425 }
426
427 // If it is not dead on definition, it must be killed by a
428 // subsequent instruction. Hence its interval is:
429 // [defSlot(def), useSlot(kill)+1)
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000430 while (++mi != MBB->end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000431 baseIndex += InstrSlots::NUM;
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000432 if (lv_->KillsRegister(mi, interval.reg)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000433 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000434 end = getUseIndex(baseIndex) + 1;
435 goto exit;
Evan Cheng9a1956a2006-11-15 20:54:11 +0000436 } else if (lv_->ModifiesRegister(mi, interval.reg)) {
437 // Another instruction redefines the register before it is ever read.
438 // Then the register is essentially dead at the instruction that defines
439 // it. Hence its interval is:
440 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000441 DOUT << " dead";
Evan Cheng9a1956a2006-11-15 20:54:11 +0000442 end = getDefIndex(start) + 1;
443 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000444 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000445 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000446
447 // The only case we should have a dead physreg here without a killing or
448 // instruction where we know it's dead is if it is live-in to the function
449 // and never used.
Chris Lattner91725b72006-08-31 05:54:43 +0000450 assert(!SrcReg && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000451 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000452
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000453exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000454 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000455
Evan Cheng24a3cc42007-04-25 07:30:23 +0000456 // Already exists? Extend old live interval.
457 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000458 VNInfo *ValNo = (OldLR != interval.end())
Evan Chengf3bb2e62007-09-05 21:46:51 +0000459 ? OldLR->valno : interval.getNextValue(start, SrcReg, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000460 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000461 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000462 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000463 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000464}
465
Chris Lattnerf35fef72004-07-23 21:24:19 +0000466void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
467 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000468 unsigned MIIdx,
Chris Lattnerf35fef72004-07-23 21:24:19 +0000469 unsigned reg) {
470 if (MRegisterInfo::isVirtualRegister(reg))
Chris Lattner6b128bd2006-09-03 08:07:11 +0000471 handleVirtualRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg));
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000472 else if (allocatableRegs_[reg]) {
Chris Lattner91725b72006-08-31 05:54:43 +0000473 unsigned SrcReg, DstReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +0000474 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
475 SrcReg = MI->getOperand(1).getReg();
476 else if (!tii_->isMoveInstr(*MI, SrcReg, DstReg))
Chris Lattner91725b72006-08-31 05:54:43 +0000477 SrcReg = 0;
Chris Lattner6b128bd2006-09-03 08:07:11 +0000478 handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg), SrcReg);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000479 // Def of a register also defines its sub-registers.
480 for (const unsigned* AS = mri_->getSubRegisters(reg); *AS; ++AS)
481 // Avoid processing some defs more than once.
482 if (!MI->findRegisterDefOperand(*AS))
483 handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000484 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000485}
486
Evan Chengb371f452007-02-19 21:49:54 +0000487void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000488 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000489 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000490 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
491
492 // Look for kills, if it reaches a def before it's killed, then it shouldn't
493 // be considered a livein.
494 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000495 unsigned baseIndex = MIIdx;
496 unsigned start = baseIndex;
Evan Chengb371f452007-02-19 21:49:54 +0000497 unsigned end = start;
498 while (mi != MBB->end()) {
499 if (lv_->KillsRegister(mi, interval.reg)) {
500 DOUT << " killed";
501 end = getUseIndex(baseIndex) + 1;
502 goto exit;
503 } else if (lv_->ModifiesRegister(mi, interval.reg)) {
504 // Another instruction redefines the register before it is ever read.
505 // Then the register is essentially dead at the instruction that defines
506 // it. Hence its interval is:
507 // [defSlot(def), defSlot(def)+1)
508 DOUT << " dead";
509 end = getDefIndex(start) + 1;
510 goto exit;
511 }
512
513 baseIndex += InstrSlots::NUM;
514 ++mi;
515 }
516
517exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000518 // Live-in register might not be used at all.
519 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000520 if (isAlias) {
521 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000522 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000523 } else {
524 DOUT << " live through";
525 end = baseIndex;
526 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000527 }
528
Evan Chengf3bb2e62007-09-05 21:46:51 +0000529 LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000530 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000531 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000532 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000533}
534
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000535/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000536/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000537/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000538/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000539void LiveIntervals::computeIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000540 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
541 << "********** Function: "
542 << ((Value*)mf_->getFunction())->getName() << '\n';
Chris Lattner6b128bd2006-09-03 08:07:11 +0000543 // Track the index of the current machine instr.
544 unsigned MIIndex = 0;
Chris Lattner428b92e2006-09-15 03:57:23 +0000545 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
546 MBBI != E; ++MBBI) {
547 MachineBasicBlock *MBB = MBBI;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000548 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000549
Chris Lattner428b92e2006-09-15 03:57:23 +0000550 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000551
Dan Gohmancb406c22007-10-03 19:26:29 +0000552 // Create intervals for live-ins to this BB first.
553 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
554 LE = MBB->livein_end(); LI != LE; ++LI) {
555 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
556 // Multiple live-ins can alias the same register.
557 for (const unsigned* AS = mri_->getSubRegisters(*LI); *AS; ++AS)
558 if (!hasInterval(*AS))
559 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
560 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000561 }
562
Chris Lattner428b92e2006-09-15 03:57:23 +0000563 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000564 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000565
Evan Cheng438f7bc2006-11-10 08:43:01 +0000566 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000567 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
568 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000569 // handle register defs - build intervals
Chris Lattner428b92e2006-09-15 03:57:23 +0000570 if (MO.isRegister() && MO.getReg() && MO.isDef())
571 handleRegisterDef(MBB, MI, MIIndex, MO.getReg());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000572 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000573
574 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000575 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000576 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000577}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000578
Evan Cheng4ca980e2007-10-17 02:10:22 +0000579bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Chenga5bfc972007-10-17 06:53:44 +0000580 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000581 std::vector<IdxMBBPair>::const_iterator I =
582 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
583
584 bool ResVal = false;
585 while (I != Idx2MBBMap.end()) {
586 if (LR.end <= I->first)
587 break;
588 MBBs.push_back(I->second);
589 ResVal = true;
590 ++I;
591 }
592 return ResVal;
593}
594
595
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000596LiveInterval LiveIntervals::createInterval(unsigned reg) {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000597 float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000598 HUGE_VALF : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000599 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000600}
Evan Chengf2fbca62007-11-12 06:35:08 +0000601
602
603//===----------------------------------------------------------------------===//
604// Register allocator hooks.
605//
606
607/// isReMaterializable - Returns true if the definition MI of the specified
608/// val# of the specified interval is re-materializable.
609bool LiveIntervals::isReMaterializable(const LiveInterval &li,
610 const VNInfo *ValNo, MachineInstr *MI) {
611 if (DisableReMat)
612 return false;
613
614 if (tii_->isTriviallyReMaterializable(MI))
615 return true;
616
617 int FrameIdx = 0;
618 if (!tii_->isLoadFromStackSlot(MI, FrameIdx) ||
619 !mf_->getFrameInfo()->isFixedObjectIndex(FrameIdx))
620 return false;
621
622 // This is a load from fixed stack slot. It can be rematerialized unless it's
623 // re-defined by a two-address instruction.
624 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
625 i != e; ++i) {
626 const VNInfo *VNI = *i;
627 if (VNI == ValNo)
628 continue;
629 unsigned DefIdx = VNI->def;
630 if (DefIdx == ~1U)
631 continue; // Dead val#.
632 MachineInstr *DefMI = (DefIdx == ~0u)
633 ? NULL : getInstructionFromIndex(DefIdx);
634 if (DefMI && DefMI->isRegReDefinedByTwoAddr(li.reg))
635 return false;
636 }
637 return true;
638}
639
640/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
641/// slot / to reg or any rematerialized load into ith operand of specified
642/// MI. If it is successul, MI is updated with the newly created MI and
643/// returns true.
Evan Cheng81a03822007-11-17 00:40:40 +0000644bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
Evan Chengcddbb832007-11-30 21:23:43 +0000645 VirtRegMap &vrm, MachineInstr *DefMI,
Evan Chengaee4af62007-12-02 08:30:39 +0000646 unsigned InstrIdx,
647 SmallVector<unsigned, 2> &Ops,
Evan Chengcddbb832007-11-30 21:23:43 +0000648 bool isSS, int Slot, unsigned Reg) {
Evan Chengaee4af62007-12-02 08:30:39 +0000649 unsigned MRInfo = 0;
650 const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
651 SmallVector<unsigned, 2> FoldOps;
652 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
653 unsigned OpIdx = Ops[i];
654 // FIXME: fold subreg use.
655 if (MI->getOperand(OpIdx).getSubReg())
Evan Chenge62f97c2007-12-01 02:07:52 +0000656 return false;
Evan Chengaee4af62007-12-02 08:30:39 +0000657 if (MI->getOperand(OpIdx).isDef())
658 MRInfo |= (unsigned)VirtRegMap::isMod;
659 else {
660 // Filter out two-address use operand(s).
661 if (TID->getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
662 MRInfo = VirtRegMap::isModRef;
663 continue;
664 }
665 MRInfo |= (unsigned)VirtRegMap::isRef;
666 }
667 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +0000668 }
669
Evan Chengaee4af62007-12-02 08:30:39 +0000670 MachineInstr *fmi = isSS ? mri_->foldMemoryOperand(MI, FoldOps, Slot)
671 : mri_->foldMemoryOperand(MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +0000672 if (fmi) {
673 // Attempt to fold the memory reference into the instruction. If
674 // we can do this, we don't need to insert spill code.
675 if (lv_)
676 lv_->instructionChanged(MI, fmi);
Evan Cheng81a03822007-11-17 00:40:40 +0000677 else
678 LiveVariables::transferKillDeadInfo(MI, fmi, mri_);
Evan Chengf2fbca62007-11-12 06:35:08 +0000679 MachineBasicBlock &MBB = *MI->getParent();
Evan Chengcddbb832007-11-30 21:23:43 +0000680 if (isSS && !mf_->getFrameInfo()->isFixedObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +0000681 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +0000682 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000683 vrm.transferRestorePts(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +0000684 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +0000685 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
686 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +0000687 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000688 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +0000689 return true;
690 }
691 return false;
692}
693
Evan Cheng81a03822007-11-17 00:40:40 +0000694bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
695 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
696 for (LiveInterval::Ranges::const_iterator
697 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
698 std::vector<IdxMBBPair>::const_iterator II =
699 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
700 if (II == Idx2MBBMap.end())
701 continue;
702 if (I->end > II->first) // crossing a MBB.
703 return false;
704 MBBs.insert(II->second);
705 if (MBBs.size() > 1)
706 return false;
707 }
708 return true;
709}
710
Evan Chengf2fbca62007-11-12 06:35:08 +0000711/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
712/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
713void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +0000714rewriteInstructionForSpills(const LiveInterval &li, bool TrySplit,
715 unsigned id, unsigned index, unsigned end, MachineInstr *MI,
716 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +0000717 unsigned Slot, int LdSlot,
718 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
719 VirtRegMap &vrm, SSARegMap *RegMap,
720 const TargetRegisterClass* rc,
721 SmallVector<int, 4> &ReMatIds,
Evan Cheng81a03822007-11-17 00:40:40 +0000722 unsigned &NewVReg, bool &HasDef, bool &HasUse,
Evan Chengcada2452007-11-28 01:28:46 +0000723 const LoopInfo *loopInfo,
Evan Cheng1953d0c2007-11-29 10:12:14 +0000724 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Chengf2fbca62007-11-12 06:35:08 +0000725 std::vector<LiveInterval*> &NewLIs) {
726 RestartInstruction:
727 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
728 MachineOperand& mop = MI->getOperand(i);
729 if (!mop.isRegister())
730 continue;
731 unsigned Reg = mop.getReg();
732 unsigned RegI = Reg;
733 if (Reg == 0 || MRegisterInfo::isPhysicalRegister(Reg))
734 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +0000735 if (Reg != li.reg)
736 continue;
737
738 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +0000739 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +0000740 int FoldSlot = Slot;
741 if (DefIsReMat) {
742 // If this is the rematerializable definition MI itself and
743 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +0000744 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +0000745 DOUT << "\t\t\t\tErasing re-materlizable def: ";
746 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +0000747 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +0000748 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +0000749 MI->eraseFromParent();
750 break;
751 }
752
753 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +0000754 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +0000755 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +0000756 if (isLoad) {
757 // Try fold loads (from stack slot, constant pool, etc.) into uses.
758 FoldSS = isLoadSS;
759 FoldSlot = LdSlot;
760 }
761 }
762
Evan Cheng0cbb1162007-11-29 01:06:25 +0000763 // Do not fold load / store here if we are splitting. We'll find an
764 // optimal point to insert a load / store later.
765 if (TryFold)
766 TryFold = !TrySplit && NewVReg == 0;
Evan Cheng81a03822007-11-17 00:40:40 +0000767
Evan Chengf2fbca62007-11-12 06:35:08 +0000768 // Scan all of the operands of this instruction rewriting operands
769 // to use NewVReg instead of li.reg as appropriate. We do this for
770 // two reasons:
771 //
772 // 1. If the instr reads the same spilled vreg multiple times, we
773 // want to reuse the NewVReg.
774 // 2. If the instr is a two-addr instruction, we are required to
775 // keep the src/dst regs pinned.
776 //
777 // Keep track of whether we replace a use and/or def so that we can
778 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +0000779
Evan Cheng81a03822007-11-17 00:40:40 +0000780 HasUse = mop.isUse();
781 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +0000782 SmallVector<unsigned, 2> Ops;
783 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +0000784 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +0000785 const MachineOperand &MOj = MI->getOperand(j);
786 if (!MOj.isRegister())
Evan Chengf2fbca62007-11-12 06:35:08 +0000787 continue;
Evan Chengaee4af62007-12-02 08:30:39 +0000788 unsigned RegJ = MOj.getReg();
Evan Chengf2fbca62007-11-12 06:35:08 +0000789 if (RegJ == 0 || MRegisterInfo::isPhysicalRegister(RegJ))
790 continue;
791 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +0000792 Ops.push_back(j);
793 HasUse |= MOj.isUse();
794 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +0000795 }
796 }
797
Evan Chengcddbb832007-11-30 21:23:43 +0000798 if (TryFold &&
Evan Chengaee4af62007-12-02 08:30:39 +0000799 tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
800 Ops, FoldSS, FoldSlot, Reg)) {
Evan Chengcddbb832007-11-30 21:23:43 +0000801 // Folding the load/store can completely change the instruction in
802 // unpredictable ways, rescan it from the beginning.
803 HasUse = false;
804 HasDef = false;
805 goto RestartInstruction;
806 }
807
808 // Create a new virtual register for the spill interval.
809 bool CreatedNewVReg = false;
810 if (NewVReg == 0) {
811 NewVReg = RegMap->createVirtualRegister(rc);
812 vrm.grow();
813 CreatedNewVReg = true;
814 }
815 mop.setReg(NewVReg);
816
817 // Reuse NewVReg for other reads.
Evan Chengaee4af62007-12-02 08:30:39 +0000818 for (unsigned j = 0, e = Ops.size(); j != e; ++j)
819 MI->getOperand(Ops[j]).setReg(NewVReg);
Evan Chengcddbb832007-11-30 21:23:43 +0000820
Evan Cheng81a03822007-11-17 00:40:40 +0000821 if (CreatedNewVReg) {
822 if (DefIsReMat) {
823 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
824 if (ReMatIds[id] == VirtRegMap::MAX_STACK_SLOT) {
825 // Each valnum may have its own remat id.
826 ReMatIds[id] = vrm.assignVirtReMatId(NewVReg);
827 } else {
828 vrm.assignVirtReMatId(NewVReg, ReMatIds[id]);
829 }
830 if (!CanDelete || (HasUse && HasDef)) {
831 // If this is a two-addr instruction then its use operands are
832 // rematerializable but its def is not. It should be assigned a
833 // stack slot.
834 vrm.assignVirt2StackSlot(NewVReg, Slot);
835 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000836 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +0000837 vrm.assignVirt2StackSlot(NewVReg, Slot);
838 }
Evan Chengcb3c3302007-11-29 23:02:50 +0000839 } else if (HasUse && HasDef &&
840 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
841 // If this interval hasn't been assigned a stack slot (because earlier
842 // def is a deleted remat def), do it now.
843 assert(Slot != VirtRegMap::NO_STACK_SLOT);
844 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +0000845 }
846
847 // create a new register interval for this spill / remat.
848 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +0000849 if (CreatedNewVReg) {
850 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +0000851 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +0000852 if (TrySplit)
853 vrm.setIsSplitFromReg(NewVReg, li.reg);
854 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000855
856 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +0000857 if (CreatedNewVReg) {
858 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
859 nI.getNextValue(~0U, 0, VNInfoAllocator));
860 DOUT << " +" << LR;
861 nI.addRange(LR);
862 } else {
863 // Extend the split live interval to this def / use.
864 unsigned End = getUseIndex(index)+1;
865 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
866 nI.getValNumInfo(nI.getNumValNums()-1));
867 DOUT << " +" << LR;
868 nI.addRange(LR);
869 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000870 }
871 if (HasDef) {
872 LiveRange LR(getDefIndex(index), getStoreIndex(index),
873 nI.getNextValue(~0U, 0, VNInfoAllocator));
874 DOUT << " +" << LR;
875 nI.addRange(LR);
876 }
Evan Cheng81a03822007-11-17 00:40:40 +0000877
Evan Chengf2fbca62007-11-12 06:35:08 +0000878 DOUT << "\t\t\t\tAdded new interval: ";
879 nI.print(DOUT, mri_);
880 DOUT << '\n';
881 }
882}
883
Evan Cheng81a03822007-11-17 00:40:40 +0000884bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +0000885 const VNInfo *VNI,
886 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +0000887 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000888 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
889 unsigned KillIdx = VNI->kills[j];
890 if (KillIdx > Idx && KillIdx < End)
891 return true;
Evan Cheng81a03822007-11-17 00:40:40 +0000892 }
893 return false;
894}
895
Evan Cheng1953d0c2007-11-29 10:12:14 +0000896static const VNInfo *findDefinedVNInfo(const LiveInterval &li, unsigned DefIdx) {
897 const VNInfo *VNI = NULL;
898 for (LiveInterval::const_vni_iterator i = li.vni_begin(),
899 e = li.vni_end(); i != e; ++i)
900 if ((*i)->def == DefIdx) {
901 VNI = *i;
902 break;
903 }
904 return VNI;
905}
906
Evan Chengf2fbca62007-11-12 06:35:08 +0000907void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +0000908rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +0000909 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +0000910 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +0000911 unsigned Slot, int LdSlot,
912 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
913 VirtRegMap &vrm, SSARegMap *RegMap,
914 const TargetRegisterClass* rc,
915 SmallVector<int, 4> &ReMatIds,
Evan Cheng81a03822007-11-17 00:40:40 +0000916 const LoopInfo *loopInfo,
917 BitVector &SpillMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +0000918 std::map<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +0000919 BitVector &RestoreMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +0000920 std::map<unsigned, std::vector<SRInfo> > &RestoreIdxes,
921 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Chengf2fbca62007-11-12 06:35:08 +0000922 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng81a03822007-11-17 00:40:40 +0000923 unsigned NewVReg = 0;
Evan Chengf2fbca62007-11-12 06:35:08 +0000924 unsigned index = getBaseIndex(I->start);
925 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Cheng81a03822007-11-17 00:40:40 +0000926 bool TrySplitMI = TrySplit && vrm.getPreSplitReg(li.reg) == 0;
Evan Chengf2fbca62007-11-12 06:35:08 +0000927 for (; index != end; index += InstrSlots::NUM) {
928 // skip deleted instructions
929 while (index != end && !getInstructionFromIndex(index))
930 index += InstrSlots::NUM;
931 if (index == end) break;
932
933 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng81a03822007-11-17 00:40:40 +0000934 MachineBasicBlock *MBB = MI->getParent();
Evan Chengcada2452007-11-28 01:28:46 +0000935 NewVReg = 0;
936 if (TrySplitMI) {
937 std::map<unsigned,unsigned>::const_iterator NVI =
Evan Cheng1953d0c2007-11-29 10:12:14 +0000938 MBBVRegsMap.find(MBB->getNumber());
939 if (NVI != MBBVRegsMap.end()) {
Evan Chengcada2452007-11-28 01:28:46 +0000940 NewVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +0000941 // One common case:
942 // x = use
943 // ...
944 // ...
945 // def = ...
946 // = use
947 // It's better to start a new interval to avoid artifically
948 // extend the new interval.
949 // FIXME: Too slow? Can we fix it after rewriteInstructionsForSpills?
950 bool MIHasUse = false;
951 bool MIHasDef = false;
952 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
953 MachineOperand& mop = MI->getOperand(i);
954 if (!mop.isRegister() || mop.getReg() != li.reg)
955 continue;
956 if (mop.isUse())
957 MIHasUse = true;
958 else
959 MIHasDef = true;
960 }
961 if (MIHasDef && !MIHasUse) {
962 MBBVRegsMap.erase(MBB->getNumber());
963 NewVReg = 0;
964 }
965 }
Evan Chengcada2452007-11-28 01:28:46 +0000966 }
Evan Cheng81a03822007-11-17 00:40:40 +0000967 bool IsNew = NewVReg == 0;
968 bool HasDef = false;
969 bool HasUse = false;
970 rewriteInstructionForSpills(li, TrySplitMI, I->valno->id, index, end,
971 MI, ReMatOrigDefMI, ReMatDefMI, Slot, LdSlot,
972 isLoad, isLoadSS, DefIsReMat, CanDelete, vrm,
973 RegMap, rc, ReMatIds, NewVReg, HasDef, HasUse,
Evan Cheng1953d0c2007-11-29 10:12:14 +0000974 loopInfo, MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +0000975 if (!HasDef && !HasUse)
976 continue;
977
978 // Update weight of spill interval.
979 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000980 if (!TrySplitMI) {
Evan Cheng81a03822007-11-17 00:40:40 +0000981 // The spill weight is now infinity as it cannot be spilled again.
982 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +0000983 continue;
Evan Cheng81a03822007-11-17 00:40:40 +0000984 }
Evan Cheng0cbb1162007-11-29 01:06:25 +0000985
986 // Keep track of the last def and first use in each MBB.
987 unsigned MBBId = MBB->getNumber();
988 if (HasDef) {
989 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +0000990 bool HasKill = false;
991 if (!HasUse)
992 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
993 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +0000994 // If this is a two-address code, then this index starts a new VNInfo.
995 const VNInfo *VNI = findDefinedVNInfo(li, getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +0000996 if (VNI)
997 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
998 }
Evan Chenge3110d02007-12-01 04:42:39 +0000999 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
1000 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001001 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001002 if (SII == SpillIdxes.end()) {
1003 std::vector<SRInfo> S;
1004 S.push_back(SRInfo(index, NewVReg, true));
1005 SpillIdxes.insert(std::make_pair(MBBId, S));
1006 } else if (SII->second.back().vreg != NewVReg) {
1007 SII->second.push_back(SRInfo(index, NewVReg, true));
1008 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001009 // If there is an earlier def and this is a two-address
1010 // instruction, then it's not possible to fold the store (which
1011 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001012 SRInfo &Info = SII->second.back();
1013 Info.index = index;
1014 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001015 }
1016 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001017 } else if (SII != SpillIdxes.end() &&
1018 SII->second.back().vreg == NewVReg &&
1019 (int)index > SII->second.back().index) {
1020 // There is an earlier def that's not killed (must be two-address).
1021 // The spill is no longer needed.
1022 SII->second.pop_back();
1023 if (SII->second.empty()) {
1024 SpillIdxes.erase(MBBId);
1025 SpillMBBs.reset(MBBId);
1026 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001027 }
1028 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001029 }
1030
1031 if (HasUse) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001032 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001033 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001034 if (SII != SpillIdxes.end() &&
1035 SII->second.back().vreg == NewVReg &&
1036 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001037 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001038 SII->second.back().canFold = false;
1039 std::map<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001040 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001041 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001042 // If we are splitting live intervals, only fold if it's the first
1043 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001044 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001045 else if (IsNew) {
1046 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001047 if (RII == RestoreIdxes.end()) {
1048 std::vector<SRInfo> Infos;
1049 Infos.push_back(SRInfo(index, NewVReg, true));
1050 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1051 } else {
1052 RII->second.push_back(SRInfo(index, NewVReg, true));
1053 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001054 RestoreMBBs.set(MBBId);
1055 }
1056 }
1057
1058 // Update spill weight.
1059 unsigned loopDepth = loopInfo->getLoopDepth(MBB->getBasicBlock());
1060 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001061 }
1062}
1063
Evan Cheng1953d0c2007-11-29 10:12:14 +00001064bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1065 BitVector &RestoreMBBs,
1066 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1067 if (!RestoreMBBs[Id])
1068 return false;
1069 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1070 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1071 if (Restores[i].index == index &&
1072 Restores[i].vreg == vr &&
1073 Restores[i].canFold)
1074 return true;
1075 return false;
1076}
1077
1078void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1079 BitVector &RestoreMBBs,
1080 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1081 if (!RestoreMBBs[Id])
1082 return;
1083 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1084 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1085 if (Restores[i].index == index && Restores[i].vreg)
1086 Restores[i].index = -1;
1087}
Evan Cheng81a03822007-11-17 00:40:40 +00001088
1089
Evan Chengf2fbca62007-11-12 06:35:08 +00001090std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001091addIntervalsForSpills(const LiveInterval &li,
1092 const LoopInfo *loopInfo, VirtRegMap &vrm) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001093 // Since this is called after the analysis is done we don't know if
1094 // LiveVariables is available
1095 lv_ = getAnalysisToUpdate<LiveVariables>();
1096
1097 assert(li.weight != HUGE_VALF &&
1098 "attempt to spill already spilled interval!");
1099
1100 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
1101 li.print(DOUT, mri_);
1102 DOUT << '\n';
1103
Evan Cheng81a03822007-11-17 00:40:40 +00001104 // Each bit specify whether it a spill is required in the MBB.
1105 BitVector SpillMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001106 std::map<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001107 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001108 std::map<unsigned, std::vector<SRInfo> > RestoreIdxes;
1109 std::map<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001110 std::vector<LiveInterval*> NewLIs;
1111 SSARegMap *RegMap = mf_->getSSARegMap();
1112 const TargetRegisterClass* rc = RegMap->getRegClass(li.reg);
1113
1114 unsigned NumValNums = li.getNumValNums();
1115 SmallVector<MachineInstr*, 4> ReMatDefs;
1116 ReMatDefs.resize(NumValNums, NULL);
1117 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1118 ReMatOrigDefs.resize(NumValNums, NULL);
1119 SmallVector<int, 4> ReMatIds;
1120 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1121 BitVector ReMatDelete(NumValNums);
1122 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1123
Evan Cheng81a03822007-11-17 00:40:40 +00001124 // Spilling a split live interval. It cannot be split any further. Also,
1125 // it's also guaranteed to be a single val# / range interval.
1126 if (vrm.getPreSplitReg(li.reg)) {
1127 vrm.setIsSplitFromReg(li.reg, 0);
1128 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1129 Slot = vrm.getStackSlot(li.reg);
1130 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1131 MachineInstr *ReMatDefMI = DefIsReMat ?
1132 vrm.getReMaterializedMI(li.reg) : NULL;
1133 int LdSlot = 0;
1134 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1135 bool isLoad = isLoadSS ||
1136 (DefIsReMat && (ReMatDefMI->getInstrDescriptor()->Flags & M_LOAD_FLAG));
Evan Cheng81a03822007-11-17 00:40:40 +00001137 bool IsFirstRange = true;
1138 for (LiveInterval::Ranges::const_iterator
1139 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1140 // If this is a split live interval with multiple ranges, it means there
1141 // are two-address instructions that re-defined the value. Only the
1142 // first def can be rematerialized!
1143 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001144 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001145 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1146 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001147 false, vrm, RegMap, rc, ReMatIds, loopInfo,
1148 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001149 MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001150 } else {
1151 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1152 Slot, 0, false, false, false,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001153 false, vrm, RegMap, rc, ReMatIds, loopInfo,
1154 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001155 MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001156 }
1157 IsFirstRange = false;
1158 }
1159 return NewLIs;
1160 }
1161
1162 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001163 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1164 TrySplit = false;
1165 if (TrySplit)
1166 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001167 bool NeedStackSlot = false;
1168 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1169 i != e; ++i) {
1170 const VNInfo *VNI = *i;
1171 unsigned VN = VNI->id;
1172 unsigned DefIdx = VNI->def;
1173 if (DefIdx == ~1U)
1174 continue; // Dead val#.
1175 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001176 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1177 ? 0 : getInstructionFromIndex(DefIdx);
1178 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001179 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001180 ReMatOrigDefs[VN] = ReMatDefMI;
Evan Chengf2fbca62007-11-12 06:35:08 +00001181 // Original def may be modified so we have to make a copy here. vrm must
1182 // delete these!
Evan Cheng81a03822007-11-17 00:40:40 +00001183 ReMatDefs[VN] = ReMatDefMI = ReMatDefMI->clone();
1184 vrm.setVirtIsReMaterialized(li.reg, ReMatDefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001185
1186 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001187 if (VNI->hasPHIKill) {
1188 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001189 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001190 CanDelete = false;
1191 // Need a stack slot if there is any live range where uses cannot be
1192 // rematerialized.
1193 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001194 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001195 if (CanDelete)
1196 ReMatDelete.set(VN);
1197 } else {
1198 // Need a stack slot if there is any live range where uses cannot be
1199 // rematerialized.
1200 NeedStackSlot = true;
1201 }
1202 }
1203
1204 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001205 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001206 Slot = vrm.assignVirt2StackSlot(li.reg);
1207
1208 // Create new intervals and rewrite defs and uses.
1209 for (LiveInterval::Ranges::const_iterator
1210 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001211 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1212 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1213 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001214 bool CanDelete = ReMatDelete[I->valno->id];
1215 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001216 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001217 bool isLoad = isLoadSS ||
Evan Cheng81a03822007-11-17 00:40:40 +00001218 (DefIsReMat && (ReMatDefMI->getInstrDescriptor()->Flags & M_LOAD_FLAG));
1219 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001220 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1221 CanDelete, vrm, RegMap, rc, ReMatIds, loopInfo,
1222 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001223 MBBVRegsMap, NewLIs);
Evan Chengf2fbca62007-11-12 06:35:08 +00001224 }
1225
Evan Cheng0cbb1162007-11-29 01:06:25 +00001226 // Insert spills / restores if we are splitting.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001227 if (!TrySplit)
1228 return NewLIs;
1229
Evan Chengaee4af62007-12-02 08:30:39 +00001230 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001231 if (NeedStackSlot) {
1232 int Id = SpillMBBs.find_first();
1233 while (Id != -1) {
1234 std::vector<SRInfo> &spills = SpillIdxes[Id];
1235 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1236 int index = spills[i].index;
1237 unsigned VReg = spills[i].vreg;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001238 bool isReMat = vrm.isReMaterialized(VReg);
1239 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001240 bool CanFold = false;
1241 bool FoundUse = false;
1242 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001243 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001244 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001245 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1246 MachineOperand &MO = MI->getOperand(j);
1247 if (!MO.isRegister() || MO.getReg() != VReg)
1248 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001249
1250 Ops.push_back(j);
1251 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001252 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001253 if (isReMat ||
1254 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1255 RestoreMBBs, RestoreIdxes))) {
1256 // MI has two-address uses of the same register. If the use
1257 // isn't the first and only use in the BB, then we can't fold
1258 // it. FIXME: Move this to rewriteInstructionsForSpills.
1259 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001260 break;
1261 }
Evan Chengaee4af62007-12-02 08:30:39 +00001262 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001263 }
1264 }
1265 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001266 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001267 if (CanFold && !Ops.empty()) {
1268 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001269 Folded = true;
Evan Chengaee4af62007-12-02 08:30:39 +00001270 if (FoundUse > 0)
1271 // Also folded uses, do not issue a load.
1272 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengcddbb832007-11-30 21:23:43 +00001273 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001274 }
1275
Evan Chengaee4af62007-12-02 08:30:39 +00001276 // Else tell the spiller to issue a spill.
Evan Chengcddbb832007-11-30 21:23:43 +00001277 if (!Folded)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001278 vrm.addSpillPoint(VReg, MI);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001279 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001280 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001281 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001282 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001283
Evan Cheng1953d0c2007-11-29 10:12:14 +00001284 int Id = RestoreMBBs.find_first();
1285 while (Id != -1) {
1286 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1287 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
1288 int index = restores[i].index;
1289 if (index == -1)
1290 continue;
1291 unsigned VReg = restores[i].vreg;
Evan Cheng81a03822007-11-17 00:40:40 +00001292 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001293 bool CanFold = false;
1294 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001295 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001296 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001297 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1298 MachineOperand &MO = MI->getOperand(j);
1299 if (!MO.isRegister() || MO.getReg() != VReg)
1300 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001301
Evan Cheng0cbb1162007-11-29 01:06:25 +00001302 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00001303 // If this restore were to be folded, it would have been folded
1304 // already.
1305 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00001306 break;
1307 }
Evan Chengaee4af62007-12-02 08:30:39 +00001308 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00001309 }
1310 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001311
1312 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001313 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001314 if (CanFold && !Ops.empty()) {
1315 if (!vrm.isReMaterialized(VReg))
1316 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
1317 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001318 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
1319 int LdSlot = 0;
1320 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1321 // If the rematerializable def is a load, also try to fold it.
1322 if (isLoadSS ||
1323 (ReMatDefMI->getInstrDescriptor()->Flags & M_LOAD_FLAG))
Evan Chengaee4af62007-12-02 08:30:39 +00001324 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1325 Ops, isLoadSS, LdSlot, VReg);
1326 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001327 }
1328 // If folding is not possible / failed, then tell the spiller to issue a
1329 // load / rematerialization for us.
Evan Chengcddbb832007-11-30 21:23:43 +00001330 if (!Folded)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001331 vrm.addRestorePoint(VReg, MI);
Evan Cheng81a03822007-11-17 00:40:40 +00001332 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001333 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00001334 }
1335
1336 // Finalize spill weights.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001337 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i)
1338 NewLIs[i]->weight /= NewLIs[i]->getSize();
Evan Cheng81a03822007-11-17 00:40:40 +00001339
Evan Chengf2fbca62007-11-12 06:35:08 +00001340 return NewLIs;
1341}