blob: 577400c674b48cfb4d9058b772478c11f27ed02f [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveInterval analysis pass which is used
11// by the Linear Scan Register allocator. This pass linearizes the
12// basic blocks of the function in DFS order and uses the
13// LiveVariables pass to conservatively compute live intervals for
14// each virtual and physical register.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "liveintervals"
19#include "llvm/CodeGen/LiveIntervalAnalysis.h"
20#include "VirtRegMap.h"
21#include "llvm/Value.h"
Dan Gohmane3427532008-07-25 00:02:30 +000022#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng26d17df2007-12-11 02:09:15 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner1b989192007-12-31 04:13:23 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include "llvm/CodeGen/Passes.h"
Dan Gohmane3427532008-07-25 00:02:30 +000029#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman1e57df32008-02-10 18:45:23 +000030#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetMachine.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/STLExtras.h"
37#include <algorithm>
38#include <cmath>
39using namespace llvm;
40
Dan Gohman089efff2008-05-13 00:00:25 +000041// Hidden options for help debugging.
42static cl::opt<bool> DisableReMat("disable-rematerialization",
43 cl::init(false), cl::Hidden);
Evan Chengcecc8222007-11-17 00:40:40 +000044
Dan Gohman089efff2008-05-13 00:00:25 +000045static cl::opt<bool> SplitAtBB("split-intervals-at-bb",
46 cl::init(true), cl::Hidden);
47static cl::opt<int> SplitLimit("split-limit",
48 cl::init(-1), cl::Hidden);
Evan Chengafc07f82007-08-16 07:24:22 +000049
Dan Gohmanf14c94f2008-07-25 15:08:37 +000050static cl::opt<bool> EnableAggressiveRemat("aggressive-remat", cl::Hidden);
51
Owen Andersona9205692008-08-19 00:17:30 +000052static cl::opt<bool> EnableFastSpilling("fast-spill",
53 cl::init(false), cl::Hidden);
54
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055STATISTIC(numIntervals, "Number of original intervals");
56STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
Evan Cheng96c61312007-11-29 01:06:25 +000057STATISTIC(numFolds , "Number of loads/stores folded into instructions");
58STATISTIC(numSplits , "Number of intervals split");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059
60char LiveIntervals::ID = 0;
Dan Gohman089efff2008-05-13 00:00:25 +000061static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062
63void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmane3427532008-07-25 00:02:30 +000064 AU.addRequired<AliasAnalysis>();
65 AU.addPreserved<AliasAnalysis>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066 AU.addPreserved<LiveVariables>();
67 AU.addRequired<LiveVariables>();
Bill Wendling62264362008-01-04 20:54:55 +000068 AU.addPreservedID(MachineLoopInfoID);
69 AU.addPreservedID(MachineDominatorsID);
Owen Andersonee7b97c2008-08-06 20:58:38 +000070 AU.addPreservedID(PHIEliminationID);
71 AU.addRequiredID(PHIEliminationID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072 AU.addRequiredID(TwoAddressInstructionPassID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073 MachineFunctionPass::getAnalysisUsage(AU);
74}
75
76void LiveIntervals::releaseMemory() {
Owen Anderson348d1d82008-08-13 21:49:13 +000077 // Free the live intervals themselves.
Owen Anderson36bb2ba2008-08-13 22:08:30 +000078 for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
Owen Anderson348d1d82008-08-13 21:49:13 +000079 E = r2iMap_.end(); I != E; ++I)
80 delete I->second;
81
Evan Cheng14f8a502008-06-04 09:18:41 +000082 MBB2IdxMap.clear();
Evan Cheng94262e42007-10-17 02:10:22 +000083 Idx2MBBMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084 mi2iMap_.clear();
85 i2miMap_.clear();
86 r2iMap_.clear();
Evan Cheng27344d42007-09-06 01:07:24 +000087 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
88 VNInfoAllocator.Reset();
Evan Cheng4ce1a522008-07-19 00:37:25 +000089 while (!ClonedMIs.empty()) {
90 MachineInstr *MI = ClonedMIs.back();
91 ClonedMIs.pop_back();
92 mf_->DeleteMachineInstr(MI);
93 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094}
95
Owen Andersonf47fbec2008-05-28 20:54:50 +000096void LiveIntervals::computeNumbering() {
97 Index2MiMap OldI2MI = i2miMap_;
Owen Anderson4065ac92008-07-23 21:37:49 +000098 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Andersonf47fbec2008-05-28 20:54:50 +000099
100 Idx2MBBMap.clear();
101 MBB2IdxMap.clear();
102 mi2iMap_.clear();
103 i2miMap_.clear();
104
Owen Andersona0e65132008-07-22 22:46:49 +0000105 FunctionSize = 0;
106
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 // Number MachineInstrs and MachineBasicBlocks.
108 // Initialize MBB indexes to a sentinal.
Evan Cheng1204d172007-08-13 23:45:17 +0000109 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000110
111 unsigned MIIndex = 0;
112 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
113 MBB != E; ++MBB) {
Evan Cheng1204d172007-08-13 23:45:17 +0000114 unsigned StartIdx = MIIndex;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000115
Owen Anderson4065ac92008-07-23 21:37:49 +0000116 // Insert an empty slot at the beginning of each block.
117 MIIndex += InstrSlots::NUM;
118 i2miMap_.push_back(0);
119
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
121 I != E; ++I) {
122 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
123 assert(inserted && "multiple MachineInstr -> index mappings");
124 i2miMap_.push_back(I);
125 MIIndex += InstrSlots::NUM;
Owen Andersona0e65132008-07-22 22:46:49 +0000126 FunctionSize++;
Owen Anderson4065ac92008-07-23 21:37:49 +0000127
128 // Insert an empty slot after every instruction.
Owen Anderson7894e5b2008-06-16 16:58:24 +0000129 MIIndex += InstrSlots::NUM;
130 i2miMap_.push_back(0);
Owen Andersond2e874b2008-06-16 07:10:49 +0000131 }
Owen Anderson4065ac92008-07-23 21:37:49 +0000132
Owen Anderson7894e5b2008-06-16 16:58:24 +0000133 // Set the MBB2IdxMap entry for this MBB.
134 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
135 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136 }
Evan Cheng94262e42007-10-17 02:10:22 +0000137 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Andersonf47fbec2008-05-28 20:54:50 +0000138
139 if (!OldI2MI.empty())
Owen Andersond45a11a2008-08-06 18:35:45 +0000140 for (iterator OI = begin(), OE = end(); OI != OE; ++OI) {
Owen Anderson348d1d82008-08-13 21:49:13 +0000141 for (LiveInterval::iterator LI = OI->second->begin(),
142 LE = OI->second->end(); LI != LE; ++LI) {
Owen Anderson5f7420b2008-05-29 18:15:49 +0000143
Owen Andersond7848742008-05-29 23:01:22 +0000144 // Remap the start index of the live range to the corresponding new
145 // number, or our best guess at what it _should_ correspond to if the
146 // original instruction has been erased. This is either the following
147 // instruction or its predecessor.
Owen Anderson4065ac92008-07-23 21:37:49 +0000148 unsigned index = LI->start / InstrSlots::NUM;
Owen Andersond7848742008-05-29 23:01:22 +0000149 unsigned offset = LI->start % InstrSlots::NUM;
Owen Andersona7d223a2008-07-25 23:06:59 +0000150 if (offset == InstrSlots::LOAD) {
Owen Anderson4065ac92008-07-23 21:37:49 +0000151 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersoncadb9b12008-07-25 19:50:48 +0000152 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->start);
Owen Anderson4065ac92008-07-23 21:37:49 +0000153 // Take the pair containing the index
154 std::vector<IdxMBBPair>::const_iterator J =
Owen Anderson3fe23ed2008-07-29 21:15:44 +0000155 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Andersond7848742008-05-29 23:01:22 +0000156
Owen Anderson4065ac92008-07-23 21:37:49 +0000157 LI->start = getMBBStartIdx(J->second);
158 } else {
159 LI->start = mi2iMap_[OldI2MI[index]] + offset;
Owen Andersond7848742008-05-29 23:01:22 +0000160 }
161
162 // Remap the ending index in the same way that we remapped the start,
163 // except for the final step where we always map to the immediately
164 // following instruction.
Owen Andersoncadb9b12008-07-25 19:50:48 +0000165 index = (LI->end - 1) / InstrSlots::NUM;
Owen Anderson4065ac92008-07-23 21:37:49 +0000166 offset = LI->end % InstrSlots::NUM;
Owen Andersonedbeff22008-07-30 00:22:56 +0000167 if (offset == InstrSlots::LOAD) {
168 // VReg dies at end of block.
Owen Anderson4065ac92008-07-23 21:37:49 +0000169 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersoncadb9b12008-07-25 19:50:48 +0000170 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end);
Owen Andersonedbeff22008-07-30 00:22:56 +0000171 --I;
Owen Anderson4065ac92008-07-23 21:37:49 +0000172
Owen Andersonedbeff22008-07-30 00:22:56 +0000173 LI->end = getMBBEndIdx(I->second) + 1;
Owen Anderson5f7420b2008-05-29 18:15:49 +0000174 } else {
Owen Andersoncadb9b12008-07-25 19:50:48 +0000175 unsigned idx = index;
Owen Anderson30d056d2008-07-25 21:07:13 +0000176 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
177
178 if (index != OldI2MI.size())
179 LI->end = mi2iMap_[OldI2MI[index]] + (idx == index ? offset : 0);
180 else
181 LI->end = InstrSlots::NUM * i2miMap_.size();
Owen Anderson5f7420b2008-05-29 18:15:49 +0000182 }
Owen Andersond45a11a2008-08-06 18:35:45 +0000183 }
184
Owen Anderson348d1d82008-08-13 21:49:13 +0000185 for (LiveInterval::vni_iterator VNI = OI->second->vni_begin(),
186 VNE = OI->second->vni_end(); VNI != VNE; ++VNI) {
Owen Andersond45a11a2008-08-06 18:35:45 +0000187 VNInfo* vni = *VNI;
Owen Andersonfdb3f702008-05-28 22:40:08 +0000188
Owen Andersond7848742008-05-29 23:01:22 +0000189 // Remap the VNInfo def index, which works the same as the
Owen Andersond45a11a2008-08-06 18:35:45 +0000190 // start indices above. VN's with special sentinel defs
191 // don't need to be remapped.
Owen Andersonad457832008-07-30 17:42:47 +0000192 if (vni->def != ~0U && vni->def != ~1U) {
Owen Andersond45a11a2008-08-06 18:35:45 +0000193 unsigned index = vni->def / InstrSlots::NUM;
194 unsigned offset = vni->def % InstrSlots::NUM;
Owen Andersonad457832008-07-30 17:42:47 +0000195 if (offset == InstrSlots::LOAD) {
196 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersona7d223a2008-07-25 23:06:59 +0000197 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->def);
Owen Andersonad457832008-07-30 17:42:47 +0000198 // Take the pair containing the index
199 std::vector<IdxMBBPair>::const_iterator J =
Owen Anderson3fe23ed2008-07-29 21:15:44 +0000200 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Andersond7848742008-05-29 23:01:22 +0000201
Owen Andersonad457832008-07-30 17:42:47 +0000202 vni->def = getMBBStartIdx(J->second);
203 } else {
204 vni->def = mi2iMap_[OldI2MI[index]] + offset;
205 }
Owen Andersond7848742008-05-29 23:01:22 +0000206 }
Owen Andersonfdb3f702008-05-28 22:40:08 +0000207
Owen Andersond7848742008-05-29 23:01:22 +0000208 // Remap the VNInfo kill indices, which works the same as
209 // the end indices above.
Owen Anderson5f7420b2008-05-29 18:15:49 +0000210 for (size_t i = 0; i < vni->kills.size(); ++i) {
Owen Andersonedbeff22008-07-30 00:22:56 +0000211 // PHI kills don't need to be remapped.
212 if (!vni->kills[i]) continue;
213
Owen Andersond45a11a2008-08-06 18:35:45 +0000214 unsigned index = (vni->kills[i]-1) / InstrSlots::NUM;
215 unsigned offset = vni->kills[i] % InstrSlots::NUM;
216 if (offset == InstrSlots::STORE) {
Owen Anderson4065ac92008-07-23 21:37:49 +0000217 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersoncadb9b12008-07-25 19:50:48 +0000218 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->kills[i]);
Owen Andersonedbeff22008-07-30 00:22:56 +0000219 --I;
Owen Anderson4065ac92008-07-23 21:37:49 +0000220
Owen Andersond45a11a2008-08-06 18:35:45 +0000221 vni->kills[i] = getMBBEndIdx(I->second);
Owen Anderson4065ac92008-07-23 21:37:49 +0000222 } else {
Owen Andersoncadb9b12008-07-25 19:50:48 +0000223 unsigned idx = index;
Owen Anderson30d056d2008-07-25 21:07:13 +0000224 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
225
226 if (index != OldI2MI.size())
227 vni->kills[i] = mi2iMap_[OldI2MI[index]] +
228 (idx == index ? offset : 0);
229 else
230 vni->kills[i] = InstrSlots::NUM * i2miMap_.size();
Owen Andersond7848742008-05-29 23:01:22 +0000231 }
Owen Anderson5f7420b2008-05-29 18:15:49 +0000232 }
Owen Andersonf47fbec2008-05-28 20:54:50 +0000233 }
Owen Andersond45a11a2008-08-06 18:35:45 +0000234 }
Owen Andersonf47fbec2008-05-28 20:54:50 +0000235}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236
Owen Andersonf47fbec2008-05-28 20:54:50 +0000237/// runOnMachineFunction - Register allocate the whole function
238///
239bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
240 mf_ = &fn;
241 mri_ = &mf_->getRegInfo();
242 tm_ = &fn.getTarget();
243 tri_ = tm_->getRegisterInfo();
244 tii_ = tm_->getInstrInfo();
Dan Gohmane3427532008-07-25 00:02:30 +0000245 aa_ = &getAnalysis<AliasAnalysis>();
Owen Andersonf47fbec2008-05-28 20:54:50 +0000246 lv_ = &getAnalysis<LiveVariables>();
247 allocatableRegs_ = tri_->getAllocatableSet(fn);
248
249 computeNumbering();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 computeIntervals();
251
252 numIntervals += getNumIntervals();
253
254 DOUT << "********** INTERVALS **********\n";
255 for (iterator I = begin(), E = end(); I != E; ++I) {
Owen Anderson348d1d82008-08-13 21:49:13 +0000256 I->second->print(DOUT, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 DOUT << "\n";
258 }
259
260 numIntervalsAfter += getNumIntervals();
261 DEBUG(dump());
262 return true;
263}
264
265/// print - Implement the dump method.
266void LiveIntervals::print(std::ostream &O, const Module* ) const {
267 O << "********** INTERVALS **********\n";
268 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Owen Anderson348d1d82008-08-13 21:49:13 +0000269 I->second->print(O, tri_);
Evan Cheng14f8a502008-06-04 09:18:41 +0000270 O << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 }
272
273 O << "********** MACHINEINSTRS **********\n";
274 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
275 mbbi != mbbe; ++mbbi) {
276 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
277 for (MachineBasicBlock::iterator mii = mbbi->begin(),
278 mie = mbbi->end(); mii != mie; ++mii) {
279 O << getInstructionIndex(mii) << '\t' << *mii;
280 }
281 }
282}
283
Evan Chengc4c75f52007-11-03 07:20:12 +0000284/// conflictsWithPhysRegDef - Returns true if the specified register
285/// is defined during the duration of the specified interval.
286bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
287 VirtRegMap &vrm, unsigned reg) {
288 for (LiveInterval::Ranges::const_iterator
289 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
290 for (unsigned index = getBaseIndex(I->start),
291 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
292 index += InstrSlots::NUM) {
293 // skip deleted instructions
294 while (index != end && !getInstructionFromIndex(index))
295 index += InstrSlots::NUM;
296 if (index == end) break;
297
298 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng58edd782007-11-15 08:13:29 +0000299 unsigned SrcReg, DstReg;
300 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
301 if (SrcReg == li.reg || DstReg == li.reg)
302 continue;
Evan Chengc4c75f52007-11-03 07:20:12 +0000303 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
304 MachineOperand& mop = MI->getOperand(i);
Evan Cheng58edd782007-11-15 08:13:29 +0000305 if (!mop.isRegister())
Evan Chengc4c75f52007-11-03 07:20:12 +0000306 continue;
307 unsigned PhysReg = mop.getReg();
Evan Cheng58edd782007-11-15 08:13:29 +0000308 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc4c75f52007-11-03 07:20:12 +0000309 continue;
Dan Gohman1e57df32008-02-10 18:45:23 +0000310 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng58edd782007-11-15 08:13:29 +0000311 if (!vrm.hasPhys(PhysReg))
312 continue;
Evan Chengc4c75f52007-11-03 07:20:12 +0000313 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng58edd782007-11-15 08:13:29 +0000314 }
Dan Gohman1e57df32008-02-10 18:45:23 +0000315 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000316 return true;
317 }
318 }
319 }
320
321 return false;
322}
323
Evan Cheng1204d172007-08-13 23:45:17 +0000324void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman1e57df32008-02-10 18:45:23 +0000325 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendling9b0baeb2008-02-26 21:47:57 +0000326 cerr << tri_->getName(reg);
Evan Cheng1204d172007-08-13 23:45:17 +0000327 else
328 cerr << "%reg" << reg;
329}
330
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
332 MachineBasicBlock::iterator mi,
Owen Anderson5b691fc2008-06-25 23:39:39 +0000333 unsigned MIIdx, MachineOperand& MO,
Evan Chengf1107fd2008-07-10 07:35:43 +0000334 unsigned MOIdx,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335 LiveInterval &interval) {
336 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
337 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
338
Evan Cheng70f68e92008-04-03 16:39:43 +0000339 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
340 DOUT << "is a implicit_def\n";
341 return;
342 }
343
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 // Virtual registers may be defined multiple times (due to phi
345 // elimination and 2-addr elimination). Much of what we do only has to be
346 // done once for the vreg. We use an empty interval to detect the first
347 // time we see a vreg.
348 if (interval.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 // Get the Idx of the defining instructions.
350 unsigned defIndex = getDefIndex(MIIdx);
Evan Cheng983b81d2007-08-29 20:45:00 +0000351 VNInfo *ValNo;
Evan Cheng7d2b9082008-02-15 18:24:29 +0000352 MachineInstr *CopyMI = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000353 unsigned SrcReg, DstReg;
Evan Cheng7d2b9082008-02-15 18:24:29 +0000354 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng909ab8b42008-04-09 20:57:25 +0000355 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Cheng7d2b9082008-02-15 18:24:29 +0000356 tii_->isMoveInstr(*mi, SrcReg, DstReg))
357 CopyMI = mi;
358 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng983b81d2007-08-29 20:45:00 +0000359
360 assert(ValNo->id == 0 && "First value in interval is not 0?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361
362 // Loop over all of the blocks that the vreg is defined in. There are
363 // two cases we have to handle here. The most common case is a vreg
364 // whose lifetime is contained within a basic block. In this case there
365 // will be a single kill, in MBB, which comes after the definition.
366 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
367 // FIXME: what about dead vars?
368 unsigned killIdx;
369 if (vi.Kills[0] != mi)
370 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
371 else
372 killIdx = defIndex+1;
373
374 // If the kill happens after the definition, we have an intra-block
375 // live range.
376 if (killIdx > defIndex) {
377 assert(vi.AliveBlocks.none() &&
378 "Shouldn't be alive across any blocks!");
Evan Cheng983b81d2007-08-29 20:45:00 +0000379 LiveRange LR(defIndex, killIdx, ValNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380 interval.addRange(LR);
381 DOUT << " +" << LR << "\n";
Evan Cheng319802c2007-09-05 21:46:51 +0000382 interval.addKill(ValNo, killIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383 return;
384 }
385 }
386
387 // The other case we handle is when a virtual register lives to the end
388 // of the defining block, potentially live across some blocks, then is
389 // live into some number of blocks, but gets killed. Start by adding a
390 // range that goes from this definition to the end of the defining block.
Owen Anderson4065ac92008-07-23 21:37:49 +0000391 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 DOUT << " +" << NewLR;
393 interval.addRange(NewLR);
394
395 // Iterate over all of the blocks that the variable is completely
396 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
397 // live interval.
398 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
399 if (vi.AliveBlocks[i]) {
Owen Anderson4bebfea2008-06-16 19:32:40 +0000400 LiveRange LR(getMBBStartIdx(i),
Evan Cheng5ac16ae2008-06-17 20:13:36 +0000401 getMBBEndIdx(i)+1, // MBB ends at -1.
Owen Anderson4bebfea2008-06-16 19:32:40 +0000402 ValNo);
403 interval.addRange(LR);
404 DOUT << " +" << LR;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405 }
406 }
407
408 // Finally, this virtual register is live from the start of any killing
409 // block to the 'use' slot of the killing instruction.
410 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
411 MachineInstr *Kill = vi.Kills[i];
Evan Cheng58c2b762007-08-08 03:00:28 +0000412 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000413 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng983b81d2007-08-29 20:45:00 +0000414 killIdx, ValNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415 interval.addRange(LR);
Evan Cheng319802c2007-09-05 21:46:51 +0000416 interval.addKill(ValNo, killIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417 DOUT << " +" << LR;
418 }
419
420 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421 // If this is the second time we see a virtual register definition, it
422 // must be due to phi elimination or two addr elimination. If this is
423 // the result of two address elimination, then the vreg is one of the
424 // def-and-use register operand.
Evan Chengf1107fd2008-07-10 07:35:43 +0000425 if (mi->isRegReDefinedByTwoAddr(interval.reg, MOIdx)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 // If this is a two-address definition, then we have already processed
427 // the live range. The only problem is that we didn't realize there
428 // are actually two values in the live interval. Because of this we
429 // need to take the LiveRegion that defines this register and split it
430 // into two values.
Evan Cheng06701fc2008-01-10 08:22:10 +0000431 assert(interval.containsOneValue());
432 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 unsigned RedefIndex = getDefIndex(MIIdx);
434
Evan Cheng816a7f32007-08-11 00:59:19 +0000435 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng983b81d2007-08-29 20:45:00 +0000436 VNInfo *OldValNo = OldLR->valno;
Evan Cheng816a7f32007-08-11 00:59:19 +0000437
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 // Delete the initial value, which should be short and continuous,
439 // because the 2-addr copy must be in the same MBB as the redef.
440 interval.removeRange(DefIndex, RedefIndex);
441
442 // Two-address vregs should always only be redefined once. This means
443 // that at this point, there should be exactly one value number in it.
444 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
445
446 // The new value number (#1) is defined by the instruction we claimed
447 // defined value #0.
Evan Cheng7d2b9082008-02-15 18:24:29 +0000448 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
449 VNInfoAllocator);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450
451 // Value#0 is now defined by the 2-addr instruction.
Evan Cheng7d2b9082008-02-15 18:24:29 +0000452 OldValNo->def = RedefIndex;
453 OldValNo->copy = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454
455 // Add the new live interval which replaces the range for the input copy.
456 LiveRange LR(DefIndex, RedefIndex, ValNo);
457 DOUT << " replace range with " << LR;
458 interval.addRange(LR);
Evan Cheng319802c2007-09-05 21:46:51 +0000459 interval.addKill(ValNo, RedefIndex);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460
461 // If this redefinition is dead, we need to add a dummy unit live
462 // range covering the def slot.
Owen Anderson5b691fc2008-06-25 23:39:39 +0000463 if (MO.isDead())
Evan Cheng983b81d2007-08-29 20:45:00 +0000464 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000465
466 DOUT << " RESULT: ";
Dan Gohman1e57df32008-02-10 18:45:23 +0000467 interval.print(DOUT, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000468
469 } else {
470 // Otherwise, this must be because of phi elimination. If this is the
471 // first redefinition of the vreg that we have seen, go back and change
472 // the live range in the PHI block to be a different value number.
473 if (interval.containsOneValue()) {
474 assert(vi.Kills.size() == 1 &&
475 "PHI elimination vreg should have one kill, the PHI itself!");
476
477 // Remove the old range that we now know has an incorrect number.
Evan Cheng319802c2007-09-05 21:46:51 +0000478 VNInfo *VNI = interval.getValNumInfo(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000479 MachineInstr *Killer = vi.Kills[0];
480 unsigned Start = getMBBStartIdx(Killer->getParent());
481 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
482 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman1e57df32008-02-10 18:45:23 +0000483 interval.print(DOUT, tri_); DOUT << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000484 interval.removeRange(Start, End);
Evan Cheng8b70e632007-11-29 09:49:23 +0000485 VNI->hasPHIKill = true;
Dan Gohman1e57df32008-02-10 18:45:23 +0000486 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487
488 // Replace the interval with one of a NEW value number. Note that this
489 // value number isn't actually defined by an instruction, weird huh? :)
Evan Cheng319802c2007-09-05 21:46:51 +0000490 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000491 DOUT << " replace range with " << LR;
492 interval.addRange(LR);
Evan Cheng319802c2007-09-05 21:46:51 +0000493 interval.addKill(LR.valno, End);
Dan Gohman1e57df32008-02-10 18:45:23 +0000494 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000495 }
496
497 // In the case of PHI elimination, each variable definition is only
498 // live until the end of the block. We've already taken care of the
499 // rest of the live range.
500 unsigned defIndex = getDefIndex(MIIdx);
501
Evan Cheng983b81d2007-08-29 20:45:00 +0000502 VNInfo *ValNo;
Evan Cheng7d2b9082008-02-15 18:24:29 +0000503 MachineInstr *CopyMI = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000504 unsigned SrcReg, DstReg;
Evan Cheng7d2b9082008-02-15 18:24:29 +0000505 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng909ab8b42008-04-09 20:57:25 +0000506 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Cheng7d2b9082008-02-15 18:24:29 +0000507 tii_->isMoveInstr(*mi, SrcReg, DstReg))
508 CopyMI = mi;
509 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000510
Owen Anderson4065ac92008-07-23 21:37:49 +0000511 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng983b81d2007-08-29 20:45:00 +0000512 LiveRange LR(defIndex, killIndex, ValNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 interval.addRange(LR);
Evan Cheng8b70e632007-11-29 09:49:23 +0000514 interval.addKill(ValNo, killIndex);
515 ValNo->hasPHIKill = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000516 DOUT << " +" << LR;
517 }
518 }
519
520 DOUT << '\n';
521}
522
523void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
524 MachineBasicBlock::iterator mi,
525 unsigned MIIdx,
Owen Anderson5b691fc2008-06-25 23:39:39 +0000526 MachineOperand& MO,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527 LiveInterval &interval,
Evan Cheng7d2b9082008-02-15 18:24:29 +0000528 MachineInstr *CopyMI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000529 // A physical register cannot be live across basic block, so its
530 // lifetime must end somewhere in its defining basic block.
531 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
532
533 unsigned baseIndex = MIIdx;
534 unsigned start = getDefIndex(baseIndex);
535 unsigned end = start;
536
537 // If it is not used after definition, it is considered dead at
538 // the instruction defining it. Hence its interval is:
539 // [defSlot(def), defSlot(def)+1)
Owen Anderson5b691fc2008-06-25 23:39:39 +0000540 if (MO.isDead()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541 DOUT << " dead";
542 end = getDefIndex(start) + 1;
543 goto exit;
544 }
545
546 // If it is not dead on definition, it must be killed by a
547 // subsequent instruction. Hence its interval is:
548 // [defSlot(def), useSlot(kill)+1)
Owen Anderson4065ac92008-07-23 21:37:49 +0000549 baseIndex += InstrSlots::NUM;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000550 while (++mi != MBB->end()) {
Owen Anderson4065ac92008-07-23 21:37:49 +0000551 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
552 getInstructionFromIndex(baseIndex) == 0)
553 baseIndex += InstrSlots::NUM;
Evan Chengc7daf1f2008-03-05 00:59:57 +0000554 if (mi->killsRegister(interval.reg, tri_)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000555 DOUT << " killed";
556 end = getUseIndex(baseIndex) + 1;
557 goto exit;
Evan Chengc7daf1f2008-03-05 00:59:57 +0000558 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000559 // Another instruction redefines the register before it is ever read.
560 // Then the register is essentially dead at the instruction that defines
561 // it. Hence its interval is:
562 // [defSlot(def), defSlot(def)+1)
563 DOUT << " dead";
564 end = getDefIndex(start) + 1;
565 goto exit;
566 }
Owen Anderson4065ac92008-07-23 21:37:49 +0000567
568 baseIndex += InstrSlots::NUM;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000569 }
570
571 // The only case we should have a dead physreg here without a killing or
572 // instruction where we know it's dead is if it is live-in to the function
573 // and never used.
Evan Cheng7d2b9082008-02-15 18:24:29 +0000574 assert(!CopyMI && "physreg was not killed in defining block!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 end = getDefIndex(start) + 1; // It's dead.
576
577exit:
578 assert(start < end && "did not find end of interval?");
579
580 // Already exists? Extend old live interval.
581 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng983b81d2007-08-29 20:45:00 +0000582 VNInfo *ValNo = (OldLR != interval.end())
Evan Cheng7d2b9082008-02-15 18:24:29 +0000583 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng983b81d2007-08-29 20:45:00 +0000584 LiveRange LR(start, end, ValNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 interval.addRange(LR);
Evan Cheng319802c2007-09-05 21:46:51 +0000586 interval.addKill(LR.valno, end);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000587 DOUT << " +" << LR << '\n';
588}
589
590void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
591 MachineBasicBlock::iterator MI,
592 unsigned MIIdx,
Evan Chengf1107fd2008-07-10 07:35:43 +0000593 MachineOperand& MO,
594 unsigned MOIdx) {
Owen Anderson5b691fc2008-06-25 23:39:39 +0000595 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengf1107fd2008-07-10 07:35:43 +0000596 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson5b691fc2008-06-25 23:39:39 +0000597 getOrCreateInterval(MO.getReg()));
598 else if (allocatableRegs_[MO.getReg()]) {
Evan Cheng7d2b9082008-02-15 18:24:29 +0000599 MachineInstr *CopyMI = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600 unsigned SrcReg, DstReg;
Evan Cheng7d2b9082008-02-15 18:24:29 +0000601 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng909ab8b42008-04-09 20:57:25 +0000602 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Cheng7d2b9082008-02-15 18:24:29 +0000603 tii_->isMoveInstr(*MI, SrcReg, DstReg))
604 CopyMI = MI;
Owen Anderson5b691fc2008-06-25 23:39:39 +0000605 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
606 getOrCreateInterval(MO.getReg()), CopyMI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607 // Def of a register also defines its sub-registers.
Owen Anderson5b691fc2008-06-25 23:39:39 +0000608 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Chengc7daf1f2008-03-05 00:59:57 +0000609 // If MI also modifies the sub-register explicitly, avoid processing it
610 // more than once. Do not pass in TRI here so it checks for exact match.
611 if (!MI->modifiesRegister(*AS))
Owen Anderson5b691fc2008-06-25 23:39:39 +0000612 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
613 getOrCreateInterval(*AS), 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614 }
615}
616
617void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
618 unsigned MIIdx,
619 LiveInterval &interval, bool isAlias) {
620 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
621
622 // Look for kills, if it reaches a def before it's killed, then it shouldn't
623 // be considered a livein.
624 MachineBasicBlock::iterator mi = MBB->begin();
625 unsigned baseIndex = MIIdx;
626 unsigned start = baseIndex;
Owen Andersonb2ae2692008-09-15 22:00:38 +0000627 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
628 getInstructionFromIndex(baseIndex) == 0)
629 baseIndex += InstrSlots::NUM;
630 unsigned end = baseIndex;
631
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 while (mi != MBB->end()) {
Evan Chengc7daf1f2008-03-05 00:59:57 +0000633 if (mi->killsRegister(interval.reg, tri_)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 DOUT << " killed";
635 end = getUseIndex(baseIndex) + 1;
636 goto exit;
Evan Chengc7daf1f2008-03-05 00:59:57 +0000637 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000638 // Another instruction redefines the register before it is ever read.
639 // Then the register is essentially dead at the instruction that defines
640 // it. Hence its interval is:
641 // [defSlot(def), defSlot(def)+1)
642 DOUT << " dead";
643 end = getDefIndex(start) + 1;
644 goto exit;
645 }
646
647 baseIndex += InstrSlots::NUM;
Owen Anderson4065ac92008-07-23 21:37:49 +0000648 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
649 getInstructionFromIndex(baseIndex) == 0)
650 baseIndex += InstrSlots::NUM;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651 ++mi;
652 }
653
654exit:
655 // Live-in register might not be used at all.
656 if (end == MIIdx) {
657 if (isAlias) {
658 DOUT << " dead";
659 end = getDefIndex(MIIdx) + 1;
660 } else {
661 DOUT << " live through";
662 end = baseIndex;
663 }
664 }
665
Owen Andersonb2ae2692008-09-15 22:00:38 +0000666 LiveRange LR(start, end, interval.getNextValue(~0U, 0, VNInfoAllocator));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667 interval.addRange(LR);
Evan Cheng319802c2007-09-05 21:46:51 +0000668 interval.addKill(LR.valno, end);
Evan Cheng0f727342007-08-08 07:03:29 +0000669 DOUT << " +" << LR << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670}
671
672/// computeIntervals - computes the live intervals for virtual
673/// registers. for some ordering of the machine instructions [1,N] a
674/// live interval is an interval [i, j) where 1 <= i <= j < N for
675/// which a variable is live
676void LiveIntervals::computeIntervals() {
677 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
678 << "********** Function: "
679 << ((Value*)mf_->getFunction())->getName() << '\n';
680 // Track the index of the current machine instr.
681 unsigned MIIndex = 0;
Owen Anderson4065ac92008-07-23 21:37:49 +0000682
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
684 MBBI != E; ++MBBI) {
685 MachineBasicBlock *MBB = MBBI;
686 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
687
688 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
689
Dan Gohman3f7d94b2007-10-03 19:26:29 +0000690 // Create intervals for live-ins to this BB first.
691 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
692 LE = MBB->livein_end(); LI != LE; ++LI) {
693 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
694 // Multiple live-ins can alias the same register.
Dan Gohman1e57df32008-02-10 18:45:23 +0000695 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohman3f7d94b2007-10-03 19:26:29 +0000696 if (!hasInterval(*AS))
697 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
698 true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699 }
700
Owen Andersonb2ae2692008-09-15 22:00:38 +0000701 // Skip over empty initial indices.
702 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
703 getInstructionFromIndex(MIIndex) == 0)
704 MIIndex += InstrSlots::NUM;
705
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 for (; MI != miEnd; ++MI) {
707 DOUT << MIIndex << "\t" << *MI;
708
709 // Handle defs.
710 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
711 MachineOperand &MO = MI->getOperand(i);
712 // handle register defs - build intervals
713 if (MO.isRegister() && MO.getReg() && MO.isDef())
Evan Chengf1107fd2008-07-10 07:35:43 +0000714 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 }
716
717 MIIndex += InstrSlots::NUM;
Owen Anderson4065ac92008-07-23 21:37:49 +0000718
719 // Skip over empty indices.
720 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
721 getInstructionFromIndex(MIIndex) == 0)
722 MIIndex += InstrSlots::NUM;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 }
724 }
725}
726
Evan Cheng94262e42007-10-17 02:10:22 +0000727bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Cheng12d6fcb2007-10-17 06:53:44 +0000728 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng94262e42007-10-17 02:10:22 +0000729 std::vector<IdxMBBPair>::const_iterator I =
730 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
731
732 bool ResVal = false;
733 while (I != Idx2MBBMap.end()) {
734 if (LR.end <= I->first)
735 break;
736 MBBs.push_back(I->second);
737 ResVal = true;
738 ++I;
739 }
740 return ResVal;
741}
742
743
Owen Anderson348d1d82008-08-13 21:49:13 +0000744LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Dan Gohman1e57df32008-02-10 18:45:23 +0000745 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 HUGE_VALF : 0.0F;
Owen Anderson348d1d82008-08-13 21:49:13 +0000747 return new LiveInterval(reg, Weight);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000748}
Evan Cheng9b741602007-11-12 06:35:08 +0000749
Evan Cheng7d2b9082008-02-15 18:24:29 +0000750/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
751/// copy field and returns the source register that defines it.
752unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
753 if (!VNI->copy)
754 return 0;
755
756 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
757 return VNI->copy->getOperand(1).getReg();
Evan Cheng909ab8b42008-04-09 20:57:25 +0000758 if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
759 return VNI->copy->getOperand(2).getReg();
Evan Cheng7d2b9082008-02-15 18:24:29 +0000760 unsigned SrcReg, DstReg;
761 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
762 return SrcReg;
763 assert(0 && "Unrecognized copy instruction!");
764 return 0;
765}
Evan Cheng9b741602007-11-12 06:35:08 +0000766
767//===----------------------------------------------------------------------===//
768// Register allocator hooks.
769//
770
Evan Chenga37ecfe2008-02-22 09:24:50 +0000771/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
772/// allow one) virtual register operand, then its uses are implicitly using
773/// the register. Returns the virtual register.
774unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
775 MachineInstr *MI) const {
776 unsigned RegOp = 0;
777 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
778 MachineOperand &MO = MI->getOperand(i);
779 if (!MO.isRegister() || !MO.isUse())
780 continue;
781 unsigned Reg = MO.getReg();
782 if (Reg == 0 || Reg == li.reg)
783 continue;
784 // FIXME: For now, only remat MI with at most one register operand.
785 assert(!RegOp &&
786 "Can't rematerialize instruction with multiple register operand!");
787 RegOp = MO.getReg();
Dan Gohmane3427532008-07-25 00:02:30 +0000788#ifndef NDEBUG
Evan Chenga37ecfe2008-02-22 09:24:50 +0000789 break;
Dan Gohmane3427532008-07-25 00:02:30 +0000790#endif
Evan Chenga37ecfe2008-02-22 09:24:50 +0000791 }
792 return RegOp;
793}
794
795/// isValNoAvailableAt - Return true if the val# of the specified interval
796/// which reaches the given instruction also reaches the specified use index.
797bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
798 unsigned UseIdx) const {
799 unsigned Index = getInstructionIndex(MI);
800 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
801 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
802 return UI != li.end() && UI->valno == ValNo;
803}
804
Evan Cheng9b741602007-11-12 06:35:08 +0000805/// isReMaterializable - Returns true if the definition MI of the specified
806/// val# of the specified interval is re-materializable.
807bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Chenge81fdb92007-12-06 00:01:56 +0000808 const VNInfo *ValNo, MachineInstr *MI,
809 bool &isLoad) {
Evan Cheng9b741602007-11-12 06:35:08 +0000810 if (DisableReMat)
811 return false;
812
Evan Chengfdc17062008-03-15 00:19:36 +0000813 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chenga37ecfe2008-02-22 09:24:50 +0000814 return true;
Evan Chengc2855322008-02-23 01:44:27 +0000815
816 int FrameIdx = 0;
817 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Chengd0201932008-02-23 03:38:34 +0000818 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng70e40de2008-02-25 08:50:41 +0000819 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
820 // this but remember this is not safe to fold into a two-address
821 // instruction.
Evan Chengd0201932008-02-23 03:38:34 +0000822 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengc2855322008-02-23 01:44:27 +0000823 return true;
Evan Chengc2855322008-02-23 01:44:27 +0000824
Dan Gohmane3427532008-07-25 00:02:30 +0000825 // If the target-specific rules don't identify an instruction as
826 // being trivially rematerializable, use some target-independent
827 // rules.
828 if (!MI->getDesc().isRematerializable() ||
829 !tii_->isTriviallyReMaterializable(MI)) {
Dan Gohmanf14c94f2008-07-25 15:08:37 +0000830 if (!EnableAggressiveRemat)
831 return false;
Evan Chenga37ecfe2008-02-22 09:24:50 +0000832
Dan Gohman4306f132008-07-28 18:43:51 +0000833 // If the instruction accesses memory but the memoperands have been lost,
Dan Gohmane3427532008-07-25 00:02:30 +0000834 // we can't analyze it.
835 const TargetInstrDesc &TID = MI->getDesc();
836 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
837 return false;
838
839 // Avoid instructions obviously unsafe for remat.
840 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
841 return false;
842
843 // If the instruction accesses memory and the memory could be non-constant,
844 // assume the instruction is not rematerializable.
Dan Gohman2fcbc7e2008-07-28 21:51:04 +0000845 for (std::list<MachineMemOperand>::const_iterator I = MI->memoperands_begin(),
Dan Gohmane3427532008-07-25 00:02:30 +0000846 E = MI->memoperands_end(); I != E; ++I) {
847 const MachineMemOperand &MMO = *I;
848 if (MMO.isVolatile() || MMO.isStore())
849 return false;
850 const Value *V = MMO.getValue();
851 if (!V)
852 return false;
853 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
854 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chenga37ecfe2008-02-22 09:24:50 +0000855 return false;
Dan Gohmane3427532008-07-25 00:02:30 +0000856 } else if (!aa_->pointsToConstantMemory(V))
857 return false;
858 }
859
860 // If any of the registers accessed are non-constant, conservatively assume
861 // the instruction is not rematerializable.
862 unsigned ImpUse = 0;
863 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
864 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman7f7f3652008-09-13 17:58:21 +0000865 if (MO.isRegister()) {
Dan Gohmane3427532008-07-25 00:02:30 +0000866 unsigned Reg = MO.getReg();
867 if (Reg == 0)
868 continue;
869 if (TargetRegisterInfo::isPhysicalRegister(Reg))
870 return false;
871
872 // Only allow one def, and that in the first operand.
873 if (MO.isDef() != (i == 0))
874 return false;
875
876 // Only allow constant-valued registers.
877 bool IsLiveIn = mri_->isLiveIn(Reg);
878 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
879 E = mri_->def_end();
880
881 // For the def, it should be the only def.
882 if (MO.isDef() && (next(I) != E || IsLiveIn))
883 return false;
884
885 if (MO.isUse()) {
886 // Only allow one use other register use, as that's all the
887 // remat mechanisms support currently.
888 if (Reg != li.reg) {
889 if (ImpUse == 0)
890 ImpUse = Reg;
891 else if (Reg != ImpUse)
892 return false;
893 }
894 // For uses, there should be only one associate def.
895 if (I != E && (next(I) != E || IsLiveIn))
896 return false;
897 }
Evan Chenga37ecfe2008-02-22 09:24:50 +0000898 }
899 }
Evan Chenge81fdb92007-12-06 00:01:56 +0000900 }
Evan Cheng9b741602007-11-12 06:35:08 +0000901
Dan Gohmane3427532008-07-25 00:02:30 +0000902 unsigned ImpUse = getReMatImplicitUse(li, MI);
903 if (ImpUse) {
904 const LiveInterval &ImpLi = getInterval(ImpUse);
905 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
906 re = mri_->use_end(); ri != re; ++ri) {
907 MachineInstr *UseMI = &*ri;
908 unsigned UseIdx = getInstructionIndex(UseMI);
909 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
910 continue;
911 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
912 return false;
913 }
914 }
915 return true;
Evan Chenge81fdb92007-12-06 00:01:56 +0000916}
917
918/// isReMaterializable - Returns true if every definition of MI of every
919/// val# of the specified interval is re-materializable.
920bool LiveIntervals::isReMaterializable(const LiveInterval &li, bool &isLoad) {
921 isLoad = false;
922 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
923 i != e; ++i) {
924 const VNInfo *VNI = *i;
925 unsigned DefIdx = VNI->def;
926 if (DefIdx == ~1U)
927 continue; // Dead val#.
928 // Is the def for the val# rematerializable?
929 if (DefIdx == ~0u)
930 return false;
931 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
932 bool DefIsLoad = false;
Evan Chenga37ecfe2008-02-22 09:24:50 +0000933 if (!ReMatDefMI ||
934 !isReMaterializable(li, VNI, ReMatDefMI, DefIsLoad))
Evan Chenge81fdb92007-12-06 00:01:56 +0000935 return false;
936 isLoad |= DefIsLoad;
Evan Cheng9b741602007-11-12 06:35:08 +0000937 }
938 return true;
939}
940
Evan Cheng70e40de2008-02-25 08:50:41 +0000941/// FilterFoldedOps - Filter out two-address use operands. Return
942/// true if it finds any issue with the operands that ought to prevent
943/// folding.
944static bool FilterFoldedOps(MachineInstr *MI,
945 SmallVector<unsigned, 2> &Ops,
946 unsigned &MRInfo,
947 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner5b930372008-01-07 07:27:27 +0000948 const TargetInstrDesc &TID = MI->getDesc();
Evan Chenge399fbb2007-12-12 23:12:09 +0000949
Evan Cheng70e40de2008-02-25 08:50:41 +0000950 MRInfo = 0;
Evan Chengfd0bd3c2007-12-02 08:30:39 +0000951 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
952 unsigned OpIdx = Ops[i];
Evan Chenga37ecfe2008-02-22 09:24:50 +0000953 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengfd0bd3c2007-12-02 08:30:39 +0000954 // FIXME: fold subreg use.
Evan Chenga37ecfe2008-02-22 09:24:50 +0000955 if (MO.getSubReg())
Evan Cheng70e40de2008-02-25 08:50:41 +0000956 return true;
Evan Chenga37ecfe2008-02-22 09:24:50 +0000957 if (MO.isDef())
Evan Chengfd0bd3c2007-12-02 08:30:39 +0000958 MRInfo |= (unsigned)VirtRegMap::isMod;
959 else {
960 // Filter out two-address use operand(s).
Evan Chenga37ecfe2008-02-22 09:24:50 +0000961 if (!MO.isImplicit() &&
962 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +0000963 MRInfo = VirtRegMap::isModRef;
964 continue;
965 }
966 MRInfo |= (unsigned)VirtRegMap::isRef;
967 }
968 FoldOps.push_back(OpIdx);
Evan Chengff52f082007-12-01 02:07:52 +0000969 }
Evan Cheng70e40de2008-02-25 08:50:41 +0000970 return false;
971}
972
973
974/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
975/// slot / to reg or any rematerialized load into ith operand of specified
976/// MI. If it is successul, MI is updated with the newly created MI and
977/// returns true.
978bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
979 VirtRegMap &vrm, MachineInstr *DefMI,
980 unsigned InstrIdx,
981 SmallVector<unsigned, 2> &Ops,
982 bool isSS, int Slot, unsigned Reg) {
Evan Cheng70e40de2008-02-25 08:50:41 +0000983 // If it is an implicit def instruction, just delete it.
Evan Chengfdc17062008-03-15 00:19:36 +0000984 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng70e40de2008-02-25 08:50:41 +0000985 RemoveMachineInstrFromMaps(MI);
986 vrm.RemoveMachineInstrFromMaps(MI);
987 MI->eraseFromParent();
988 ++numFolds;
989 return true;
990 }
991
992 // Filter the list of operand indexes that are to be folded. Abort if
993 // any operand will prevent folding.
994 unsigned MRInfo = 0;
995 SmallVector<unsigned, 2> FoldOps;
996 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
997 return false;
Evan Chengff52f082007-12-01 02:07:52 +0000998
Evan Cheng4c7ab522008-03-31 23:19:51 +0000999 // The only time it's safe to fold into a two address instruction is when
1000 // it's folding reload and spill from / into a spill stack slot.
1001 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Chengd0201932008-02-23 03:38:34 +00001002 return false;
1003
Evan Cheng3a15a4e2008-02-08 22:05:27 +00001004 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
1005 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Cheng9b741602007-11-12 06:35:08 +00001006 if (fmi) {
Evan Chengda872532008-02-27 03:04:06 +00001007 // Remember this instruction uses the spill slot.
1008 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
1009
Evan Cheng9b741602007-11-12 06:35:08 +00001010 // Attempt to fold the memory reference into the instruction. If
1011 // we can do this, we don't need to insert spill code.
Evan Cheng9b741602007-11-12 06:35:08 +00001012 MachineBasicBlock &MBB = *MI->getParent();
Evan Chengefe93672008-01-10 08:24:38 +00001013 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001014 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Chengcecc8222007-11-17 00:40:40 +00001015 vrm.transferSpillPts(MI, fmi);
Evan Cheng96c61312007-11-29 01:06:25 +00001016 vrm.transferRestorePts(MI, fmi);
Evan Cheng1eeb2ef2008-03-11 21:34:46 +00001017 vrm.transferEmergencySpills(MI, fmi);
Evan Cheng9b741602007-11-12 06:35:08 +00001018 mi2iMap_.erase(MI);
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001019 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
1020 mi2iMap_[fmi] = InstrIdx;
Evan Cheng9b741602007-11-12 06:35:08 +00001021 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng96c61312007-11-29 01:06:25 +00001022 ++numFolds;
Evan Cheng9b741602007-11-12 06:35:08 +00001023 return true;
1024 }
1025 return false;
1026}
1027
Evan Chengebcba1e2007-12-05 03:22:34 +00001028/// canFoldMemoryOperand - Returns true if the specified load / store
1029/// folding is possible.
1030bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng70e40de2008-02-25 08:50:41 +00001031 SmallVector<unsigned, 2> &Ops,
Evan Cheng71f75b42008-04-01 21:37:32 +00001032 bool ReMat) const {
Evan Cheng70e40de2008-02-25 08:50:41 +00001033 // Filter the list of operand indexes that are to be folded. Abort if
1034 // any operand will prevent folding.
1035 unsigned MRInfo = 0;
Evan Chengebcba1e2007-12-05 03:22:34 +00001036 SmallVector<unsigned, 2> FoldOps;
Evan Cheng70e40de2008-02-25 08:50:41 +00001037 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1038 return false;
Evan Chengebcba1e2007-12-05 03:22:34 +00001039
Evan Cheng71f75b42008-04-01 21:37:32 +00001040 // It's only legal to remat for a use, not a def.
1041 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng70e40de2008-02-25 08:50:41 +00001042 return false;
Evan Chengebcba1e2007-12-05 03:22:34 +00001043
Evan Chenga37ecfe2008-02-22 09:24:50 +00001044 return tii_->canFoldMemoryOperand(MI, FoldOps);
1045}
1046
Evan Chengcecc8222007-11-17 00:40:40 +00001047bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1048 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1049 for (LiveInterval::Ranges::const_iterator
1050 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1051 std::vector<IdxMBBPair>::const_iterator II =
1052 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1053 if (II == Idx2MBBMap.end())
1054 continue;
1055 if (I->end > II->first) // crossing a MBB.
1056 return false;
1057 MBBs.insert(II->second);
1058 if (MBBs.size() > 1)
1059 return false;
1060 }
1061 return true;
1062}
1063
Evan Chenga37ecfe2008-02-22 09:24:50 +00001064/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1065/// interval on to-be re-materialized operands of MI) with new register.
1066void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1067 MachineInstr *MI, unsigned NewVReg,
1068 VirtRegMap &vrm) {
1069 // There is an implicit use. That means one of the other operand is
1070 // being remat'ed and the remat'ed instruction has li.reg as an
1071 // use operand. Make sure we rewrite that as well.
1072 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1073 MachineOperand &MO = MI->getOperand(i);
1074 if (!MO.isRegister())
1075 continue;
1076 unsigned Reg = MO.getReg();
1077 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1078 continue;
1079 if (!vrm.isReMaterialized(Reg))
1080 continue;
1081 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Chengc7daf1f2008-03-05 00:59:57 +00001082 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1083 if (UseMO)
1084 UseMO->setReg(NewVReg);
Evan Chenga37ecfe2008-02-22 09:24:50 +00001085 }
1086}
1087
Evan Cheng9b741602007-11-12 06:35:08 +00001088/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1089/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Chengebcba1e2007-12-05 03:22:34 +00001090bool LiveIntervals::
Evan Chenga37ecfe2008-02-22 09:24:50 +00001091rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1092 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Chengcecc8222007-11-17 00:40:40 +00001093 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Cheng9b741602007-11-12 06:35:08 +00001094 unsigned Slot, int LdSlot,
1095 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chenga37ecfe2008-02-22 09:24:50 +00001096 VirtRegMap &vrm,
Evan Cheng9b741602007-11-12 06:35:08 +00001097 const TargetRegisterClass* rc,
1098 SmallVector<int, 4> &ReMatIds,
Evan Cheng26d17df2007-12-11 02:09:15 +00001099 const MachineLoopInfo *loopInfo,
Evan Chengc7666af2008-02-23 00:33:04 +00001100 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Owen Andersonfeab1a82008-08-13 22:28:50 +00001101 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Chengba221ca2008-06-06 07:54:39 +00001102 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
1103 MachineBasicBlock *MBB = MI->getParent();
1104 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengebcba1e2007-12-05 03:22:34 +00001105 bool CanFold = false;
Evan Cheng9b741602007-11-12 06:35:08 +00001106 RestartInstruction:
1107 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1108 MachineOperand& mop = MI->getOperand(i);
1109 if (!mop.isRegister())
1110 continue;
1111 unsigned Reg = mop.getReg();
1112 unsigned RegI = Reg;
Dan Gohman1e57df32008-02-10 18:45:23 +00001113 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Cheng9b741602007-11-12 06:35:08 +00001114 continue;
Evan Cheng9b741602007-11-12 06:35:08 +00001115 if (Reg != li.reg)
1116 continue;
1117
1118 bool TryFold = !DefIsReMat;
Evan Cheng35d47762007-11-29 23:02:50 +00001119 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Cheng9b741602007-11-12 06:35:08 +00001120 int FoldSlot = Slot;
1121 if (DefIsReMat) {
1122 // If this is the rematerializable definition MI itself and
1123 // all of its uses are rematerialized, simply delete it.
Evan Chengcecc8222007-11-17 00:40:40 +00001124 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001125 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1126 DOUT << MI << '\n';
Evan Cheng9b741602007-11-12 06:35:08 +00001127 RemoveMachineInstrFromMaps(MI);
Evan Cheng91e32d02007-11-28 01:28:46 +00001128 vrm.RemoveMachineInstrFromMaps(MI);
Evan Cheng9b741602007-11-12 06:35:08 +00001129 MI->eraseFromParent();
1130 break;
1131 }
1132
1133 // If def for this use can't be rematerialized, then try folding.
Evan Cheng96c61312007-11-29 01:06:25 +00001134 // If def is rematerializable and it's a load, also try folding.
Evan Cheng35d47762007-11-29 23:02:50 +00001135 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Cheng9b741602007-11-12 06:35:08 +00001136 if (isLoad) {
1137 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1138 FoldSS = isLoadSS;
1139 FoldSlot = LdSlot;
1140 }
1141 }
1142
Evan Cheng9b741602007-11-12 06:35:08 +00001143 // Scan all of the operands of this instruction rewriting operands
1144 // to use NewVReg instead of li.reg as appropriate. We do this for
1145 // two reasons:
1146 //
1147 // 1. If the instr reads the same spilled vreg multiple times, we
1148 // want to reuse the NewVReg.
1149 // 2. If the instr is a two-addr instruction, we are required to
1150 // keep the src/dst regs pinned.
1151 //
1152 // Keep track of whether we replace a use and/or def so that we can
1153 // create the spill interval with the appropriate range.
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001154
Evan Chengcecc8222007-11-17 00:40:40 +00001155 HasUse = mop.isUse();
1156 HasDef = mop.isDef();
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001157 SmallVector<unsigned, 2> Ops;
1158 Ops.push_back(i);
Evan Cheng9b741602007-11-12 06:35:08 +00001159 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001160 const MachineOperand &MOj = MI->getOperand(j);
1161 if (!MOj.isRegister())
Evan Cheng9b741602007-11-12 06:35:08 +00001162 continue;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001163 unsigned RegJ = MOj.getReg();
Dan Gohman1e57df32008-02-10 18:45:23 +00001164 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Cheng9b741602007-11-12 06:35:08 +00001165 continue;
1166 if (RegJ == RegI) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001167 Ops.push_back(j);
1168 HasUse |= MOj.isUse();
1169 HasDef |= MOj.isDef();
Evan Cheng9b741602007-11-12 06:35:08 +00001170 }
1171 }
1172
Evan Chengc33577b2008-07-12 01:56:02 +00001173 if (HasUse && !li.liveAt(getUseIndex(index)))
1174 // Must be defined by an implicit def. It should not be spilled. Note,
1175 // this is for correctness reason. e.g.
1176 // 8 %reg1024<def> = IMPLICIT_DEF
1177 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1178 // The live range [12, 14) are not part of the r1024 live interval since
1179 // it's defined by an implicit def. It will not conflicts with live
1180 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengc3c41c92008-07-12 02:22:07 +00001181 // easily see a situation where both registers are reloaded before
Evan Chengc33577b2008-07-12 01:56:02 +00001182 // the INSERT_SUBREG and both target registers that would overlap.
1183 HasUse = false;
1184
Evan Chengba221ca2008-06-06 07:54:39 +00001185 // Update stack slot spill weight if we are splitting.
Evan Chengf7b45f42008-06-21 06:45:54 +00001186 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengba221ca2008-06-06 07:54:39 +00001187 if (!TrySplit)
1188 SSWeight += Weight;
1189
1190 if (!TryFold)
1191 CanFold = false;
1192 else {
Evan Chengebcba1e2007-12-05 03:22:34 +00001193 // Do not fold load / store here if we are splitting. We'll find an
1194 // optimal point to insert a load / store later.
1195 if (!TrySplit) {
1196 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1197 Ops, FoldSS, FoldSlot, Reg)) {
1198 // Folding the load/store can completely change the instruction in
1199 // unpredictable ways, rescan it from the beginning.
1200 HasUse = false;
1201 HasDef = false;
1202 CanFold = false;
Evan Chengba221ca2008-06-06 07:54:39 +00001203 if (isRemoved(MI)) {
1204 SSWeight -= Weight;
Evan Cheng909ab8b42008-04-09 20:57:25 +00001205 break;
Evan Chengba221ca2008-06-06 07:54:39 +00001206 }
Evan Chengebcba1e2007-12-05 03:22:34 +00001207 goto RestartInstruction;
1208 }
1209 } else {
Evan Chengba221ca2008-06-06 07:54:39 +00001210 // We'll try to fold it later if it's profitable.
Evan Cheng71f75b42008-04-01 21:37:32 +00001211 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Chengebcba1e2007-12-05 03:22:34 +00001212 }
Evan Chengba221ca2008-06-06 07:54:39 +00001213 }
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001214
1215 // Create a new virtual register for the spill interval.
1216 bool CreatedNewVReg = false;
1217 if (NewVReg == 0) {
Evan Chenga37ecfe2008-02-22 09:24:50 +00001218 NewVReg = mri_->createVirtualRegister(rc);
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001219 vrm.grow();
1220 CreatedNewVReg = true;
1221 }
1222 mop.setReg(NewVReg);
Evan Chenga37ecfe2008-02-22 09:24:50 +00001223 if (mop.isImplicit())
1224 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001225
1226 // Reuse NewVReg for other reads.
Evan Chenga37ecfe2008-02-22 09:24:50 +00001227 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1228 MachineOperand &mopj = MI->getOperand(Ops[j]);
1229 mopj.setReg(NewVReg);
1230 if (mopj.isImplicit())
1231 rewriteImplicitOps(li, MI, NewVReg, vrm);
1232 }
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001233
Evan Chengcecc8222007-11-17 00:40:40 +00001234 if (CreatedNewVReg) {
1235 if (DefIsReMat) {
1236 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chenga37ecfe2008-02-22 09:24:50 +00001237 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Chengcecc8222007-11-17 00:40:40 +00001238 // Each valnum may have its own remat id.
Evan Chenga37ecfe2008-02-22 09:24:50 +00001239 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Chengcecc8222007-11-17 00:40:40 +00001240 } else {
Evan Chenga37ecfe2008-02-22 09:24:50 +00001241 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Chengcecc8222007-11-17 00:40:40 +00001242 }
1243 if (!CanDelete || (HasUse && HasDef)) {
1244 // If this is a two-addr instruction then its use operands are
1245 // rematerializable but its def is not. It should be assigned a
1246 // stack slot.
1247 vrm.assignVirt2StackSlot(NewVReg, Slot);
1248 }
Evan Cheng9b741602007-11-12 06:35:08 +00001249 } else {
Evan Cheng9b741602007-11-12 06:35:08 +00001250 vrm.assignVirt2StackSlot(NewVReg, Slot);
1251 }
Evan Cheng35d47762007-11-29 23:02:50 +00001252 } else if (HasUse && HasDef &&
1253 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1254 // If this interval hasn't been assigned a stack slot (because earlier
1255 // def is a deleted remat def), do it now.
1256 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1257 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Cheng9b741602007-11-12 06:35:08 +00001258 }
1259
Evan Chengc7666af2008-02-23 00:33:04 +00001260 // Re-matting an instruction with virtual register use. Add the
1261 // register as an implicit use on the use MI.
1262 if (DefIsReMat && ImpUse)
1263 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1264
Evan Cheng9b741602007-11-12 06:35:08 +00001265 // create a new register interval for this spill / remat.
1266 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Chengcecc8222007-11-17 00:40:40 +00001267 if (CreatedNewVReg) {
1268 NewLIs.push_back(&nI);
Evan Cheng7b632362007-11-29 10:12:14 +00001269 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Chengcecc8222007-11-17 00:40:40 +00001270 if (TrySplit)
1271 vrm.setIsSplitFromReg(NewVReg, li.reg);
1272 }
Evan Cheng9b741602007-11-12 06:35:08 +00001273
1274 if (HasUse) {
Evan Chengcecc8222007-11-17 00:40:40 +00001275 if (CreatedNewVReg) {
1276 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1277 nI.getNextValue(~0U, 0, VNInfoAllocator));
1278 DOUT << " +" << LR;
1279 nI.addRange(LR);
1280 } else {
1281 // Extend the split live interval to this def / use.
1282 unsigned End = getUseIndex(index)+1;
1283 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1284 nI.getValNumInfo(nI.getNumValNums()-1));
1285 DOUT << " +" << LR;
1286 nI.addRange(LR);
1287 }
Evan Cheng9b741602007-11-12 06:35:08 +00001288 }
1289 if (HasDef) {
1290 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1291 nI.getNextValue(~0U, 0, VNInfoAllocator));
1292 DOUT << " +" << LR;
1293 nI.addRange(LR);
1294 }
Evan Chengcecc8222007-11-17 00:40:40 +00001295
Evan Cheng9b741602007-11-12 06:35:08 +00001296 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman1e57df32008-02-10 18:45:23 +00001297 nI.print(DOUT, tri_);
Evan Cheng9b741602007-11-12 06:35:08 +00001298 DOUT << '\n';
1299 }
Evan Chengebcba1e2007-12-05 03:22:34 +00001300 return CanFold;
Evan Cheng9b741602007-11-12 06:35:08 +00001301}
Evan Chengcecc8222007-11-17 00:40:40 +00001302bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng96c61312007-11-29 01:06:25 +00001303 const VNInfo *VNI,
1304 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Chengcecc8222007-11-17 00:40:40 +00001305 unsigned End = getMBBEndIdx(MBB);
Evan Cheng96c61312007-11-29 01:06:25 +00001306 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1307 unsigned KillIdx = VNI->kills[j];
1308 if (KillIdx > Idx && KillIdx < End)
1309 return true;
Evan Chengcecc8222007-11-17 00:40:40 +00001310 }
1311 return false;
1312}
1313
Evan Cheng44fccf22008-02-21 00:34:19 +00001314/// RewriteInfo - Keep track of machine instrs that will be rewritten
1315/// during spilling.
Dan Gohman089efff2008-05-13 00:00:25 +00001316namespace {
1317 struct RewriteInfo {
1318 unsigned Index;
1319 MachineInstr *MI;
1320 bool HasUse;
1321 bool HasDef;
1322 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1323 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1324 };
Evan Cheng44fccf22008-02-21 00:34:19 +00001325
Dan Gohman089efff2008-05-13 00:00:25 +00001326 struct RewriteInfoCompare {
1327 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1328 return LHS.Index < RHS.Index;
1329 }
1330 };
1331}
Evan Cheng44fccf22008-02-21 00:34:19 +00001332
Evan Cheng9b741602007-11-12 06:35:08 +00001333void LiveIntervals::
Evan Chengcecc8222007-11-17 00:40:40 +00001334rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Cheng9b741602007-11-12 06:35:08 +00001335 LiveInterval::Ranges::const_iterator &I,
Evan Chengcecc8222007-11-17 00:40:40 +00001336 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Cheng9b741602007-11-12 06:35:08 +00001337 unsigned Slot, int LdSlot,
1338 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chenga37ecfe2008-02-22 09:24:50 +00001339 VirtRegMap &vrm,
Evan Cheng9b741602007-11-12 06:35:08 +00001340 const TargetRegisterClass* rc,
1341 SmallVector<int, 4> &ReMatIds,
Evan Cheng26d17df2007-12-11 02:09:15 +00001342 const MachineLoopInfo *loopInfo,
Evan Chengcecc8222007-11-17 00:40:40 +00001343 BitVector &SpillMBBs,
Owen Andersonfeab1a82008-08-13 22:28:50 +00001344 DenseMap<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng96c61312007-11-29 01:06:25 +00001345 BitVector &RestoreMBBs,
Owen Andersonfeab1a82008-08-13 22:28:50 +00001346 DenseMap<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1347 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Chengba221ca2008-06-06 07:54:39 +00001348 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Chengebcba1e2007-12-05 03:22:34 +00001349 bool AllCanFold = true;
Evan Chengcecc8222007-11-17 00:40:40 +00001350 unsigned NewVReg = 0;
Evan Cheng44fccf22008-02-21 00:34:19 +00001351 unsigned start = getBaseIndex(I->start);
Evan Cheng9b741602007-11-12 06:35:08 +00001352 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Cheng9b741602007-11-12 06:35:08 +00001353
Evan Cheng44fccf22008-02-21 00:34:19 +00001354 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng909ab8b42008-04-09 20:57:25 +00001355 // Make sure they are sorted according to instruction index.
Evan Cheng44fccf22008-02-21 00:34:19 +00001356 std::vector<RewriteInfo> RewriteMIs;
Evan Chenga37ecfe2008-02-22 09:24:50 +00001357 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1358 re = mri_->reg_end(); ri != re; ) {
Evan Cheng70f68e92008-04-03 16:39:43 +00001359 MachineInstr *MI = &*ri;
Evan Cheng44fccf22008-02-21 00:34:19 +00001360 MachineOperand &O = ri.getOperand();
1361 ++ri;
Evan Cheng8adc74e2008-03-31 07:53:30 +00001362 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng44fccf22008-02-21 00:34:19 +00001363 unsigned index = getInstructionIndex(MI);
1364 if (index < start || index >= end)
1365 continue;
Evan Chengc33577b2008-07-12 01:56:02 +00001366 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1367 // Must be defined by an implicit def. It should not be spilled. Note,
1368 // this is for correctness reason. e.g.
1369 // 8 %reg1024<def> = IMPLICIT_DEF
1370 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1371 // The live range [12, 14) are not part of the r1024 live interval since
1372 // it's defined by an implicit def. It will not conflicts with live
1373 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengc3c41c92008-07-12 02:22:07 +00001374 // easily see a situation where both registers are reloaded before
Evan Chengc33577b2008-07-12 01:56:02 +00001375 // the INSERT_SUBREG and both target registers that would overlap.
1376 continue;
Evan Cheng44fccf22008-02-21 00:34:19 +00001377 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1378 }
1379 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1380
Evan Chengc7666af2008-02-23 00:33:04 +00001381 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng44fccf22008-02-21 00:34:19 +00001382 // Now rewrite the defs and uses.
1383 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1384 RewriteInfo &rwi = RewriteMIs[i];
1385 ++i;
1386 unsigned index = rwi.Index;
1387 bool MIHasUse = rwi.HasUse;
1388 bool MIHasDef = rwi.HasDef;
1389 MachineInstr *MI = rwi.MI;
1390 // If MI def and/or use the same register multiple times, then there
1391 // are multiple entries.
Evan Chengc7666af2008-02-23 00:33:04 +00001392 unsigned NumUses = MIHasUse;
Evan Cheng44fccf22008-02-21 00:34:19 +00001393 while (i != e && RewriteMIs[i].MI == MI) {
1394 assert(RewriteMIs[i].Index == index);
Evan Chengc7666af2008-02-23 00:33:04 +00001395 bool isUse = RewriteMIs[i].HasUse;
1396 if (isUse) ++NumUses;
1397 MIHasUse |= isUse;
Evan Cheng44fccf22008-02-21 00:34:19 +00001398 MIHasDef |= RewriteMIs[i].HasDef;
1399 ++i;
1400 }
Evan Chengcecc8222007-11-17 00:40:40 +00001401 MachineBasicBlock *MBB = MI->getParent();
Evan Chengc7666af2008-02-23 00:33:04 +00001402
Evan Cheng9c48ca72008-05-23 23:00:04 +00001403 if (ImpUse && MI != ReMatDefMI) {
Evan Chengc7666af2008-02-23 00:33:04 +00001404 // Re-matting an instruction with virtual register use. Update the
Evan Cheng8adc74e2008-03-31 07:53:30 +00001405 // register interval's spill weight to HUGE_VALF to prevent it from
1406 // being spilled.
Evan Chengc7666af2008-02-23 00:33:04 +00001407 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng8adc74e2008-03-31 07:53:30 +00001408 ImpLi.weight = HUGE_VALF;
Evan Chengc7666af2008-02-23 00:33:04 +00001409 }
1410
Evan Cheng44fccf22008-02-21 00:34:19 +00001411 unsigned MBBId = MBB->getNumber();
Evan Chengebcba1e2007-12-05 03:22:34 +00001412 unsigned ThisVReg = 0;
Evan Cheng1083a2f2007-12-03 09:58:48 +00001413 if (TrySplit) {
Owen Andersonfeab1a82008-08-13 22:28:50 +00001414 DenseMap<unsigned,unsigned>::iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng7b632362007-11-29 10:12:14 +00001415 if (NVI != MBBVRegsMap.end()) {
Evan Chengebcba1e2007-12-05 03:22:34 +00001416 ThisVReg = NVI->second;
Evan Cheng7b632362007-11-29 10:12:14 +00001417 // One common case:
1418 // x = use
1419 // ...
1420 // ...
1421 // def = ...
1422 // = use
1423 // It's better to start a new interval to avoid artifically
1424 // extend the new interval.
Evan Cheng7b632362007-11-29 10:12:14 +00001425 if (MIHasDef && !MIHasUse) {
1426 MBBVRegsMap.erase(MBB->getNumber());
Evan Chengebcba1e2007-12-05 03:22:34 +00001427 ThisVReg = 0;
Evan Cheng7b632362007-11-29 10:12:14 +00001428 }
1429 }
Evan Cheng91e32d02007-11-28 01:28:46 +00001430 }
Evan Chengebcba1e2007-12-05 03:22:34 +00001431
1432 bool IsNew = ThisVReg == 0;
1433 if (IsNew) {
1434 // This ends the previous live interval. If all of its def / use
1435 // can be folded, give it a low spill weight.
1436 if (NewVReg && TrySplit && AllCanFold) {
1437 LiveInterval &nI = getOrCreateInterval(NewVReg);
1438 nI.weight /= 10.0F;
1439 }
1440 AllCanFold = true;
1441 }
1442 NewVReg = ThisVReg;
1443
Evan Chengcecc8222007-11-17 00:40:40 +00001444 bool HasDef = false;
1445 bool HasUse = false;
Evan Chenga37ecfe2008-02-22 09:24:50 +00001446 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Chengba221ca2008-06-06 07:54:39 +00001447 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1448 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1449 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1450 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Chengcecc8222007-11-17 00:40:40 +00001451 if (!HasDef && !HasUse)
1452 continue;
1453
Evan Chengebcba1e2007-12-05 03:22:34 +00001454 AllCanFold &= CanFold;
1455
Evan Chengcecc8222007-11-17 00:40:40 +00001456 // Update weight of spill interval.
1457 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng1083a2f2007-12-03 09:58:48 +00001458 if (!TrySplit) {
Evan Chengcecc8222007-11-17 00:40:40 +00001459 // The spill weight is now infinity as it cannot be spilled again.
1460 nI.weight = HUGE_VALF;
Evan Cheng96c61312007-11-29 01:06:25 +00001461 continue;
Evan Chengcecc8222007-11-17 00:40:40 +00001462 }
Evan Cheng96c61312007-11-29 01:06:25 +00001463
1464 // Keep track of the last def and first use in each MBB.
Evan Cheng96c61312007-11-29 01:06:25 +00001465 if (HasDef) {
1466 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng96c61312007-11-29 01:06:25 +00001467 bool HasKill = false;
1468 if (!HasUse)
1469 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1470 else {
Evan Cheng7b632362007-11-29 10:12:14 +00001471 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng14f8a502008-06-04 09:18:41 +00001472 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng96c61312007-11-29 01:06:25 +00001473 if (VNI)
1474 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1475 }
Owen Andersonfeab1a82008-08-13 22:28:50 +00001476 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng999f9472007-12-01 04:42:39 +00001477 SpillIdxes.find(MBBId);
Evan Cheng96c61312007-11-29 01:06:25 +00001478 if (!HasKill) {
Evan Cheng7b632362007-11-29 10:12:14 +00001479 if (SII == SpillIdxes.end()) {
1480 std::vector<SRInfo> S;
1481 S.push_back(SRInfo(index, NewVReg, true));
1482 SpillIdxes.insert(std::make_pair(MBBId, S));
1483 } else if (SII->second.back().vreg != NewVReg) {
1484 SII->second.push_back(SRInfo(index, NewVReg, true));
1485 } else if ((int)index > SII->second.back().index) {
Evan Cheng96c61312007-11-29 01:06:25 +00001486 // If there is an earlier def and this is a two-address
1487 // instruction, then it's not possible to fold the store (which
1488 // would also fold the load).
Evan Cheng7b632362007-11-29 10:12:14 +00001489 SRInfo &Info = SII->second.back();
1490 Info.index = index;
1491 Info.canFold = !HasUse;
Evan Cheng96c61312007-11-29 01:06:25 +00001492 }
1493 SpillMBBs.set(MBBId);
Evan Cheng999f9472007-12-01 04:42:39 +00001494 } else if (SII != SpillIdxes.end() &&
1495 SII->second.back().vreg == NewVReg &&
1496 (int)index > SII->second.back().index) {
1497 // There is an earlier def that's not killed (must be two-address).
1498 // The spill is no longer needed.
1499 SII->second.pop_back();
1500 if (SII->second.empty()) {
1501 SpillIdxes.erase(MBBId);
1502 SpillMBBs.reset(MBBId);
1503 }
Evan Cheng96c61312007-11-29 01:06:25 +00001504 }
1505 }
Evan Cheng96c61312007-11-29 01:06:25 +00001506 }
1507
1508 if (HasUse) {
Owen Andersonfeab1a82008-08-13 22:28:50 +00001509 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng96c61312007-11-29 01:06:25 +00001510 SpillIdxes.find(MBBId);
Evan Cheng7b632362007-11-29 10:12:14 +00001511 if (SII != SpillIdxes.end() &&
1512 SII->second.back().vreg == NewVReg &&
1513 (int)index > SII->second.back().index)
Evan Cheng96c61312007-11-29 01:06:25 +00001514 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng7b632362007-11-29 10:12:14 +00001515 SII->second.back().canFold = false;
Owen Andersonfeab1a82008-08-13 22:28:50 +00001516 DenseMap<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng96c61312007-11-29 01:06:25 +00001517 RestoreIdxes.find(MBBId);
Evan Cheng7b632362007-11-29 10:12:14 +00001518 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng96c61312007-11-29 01:06:25 +00001519 // If we are splitting live intervals, only fold if it's the first
1520 // use and there isn't another use later in the MBB.
Evan Cheng7b632362007-11-29 10:12:14 +00001521 RII->second.back().canFold = false;
Evan Cheng96c61312007-11-29 01:06:25 +00001522 else if (IsNew) {
1523 // Only need a reload if there isn't an earlier def / use.
Evan Cheng7b632362007-11-29 10:12:14 +00001524 if (RII == RestoreIdxes.end()) {
1525 std::vector<SRInfo> Infos;
1526 Infos.push_back(SRInfo(index, NewVReg, true));
1527 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1528 } else {
1529 RII->second.push_back(SRInfo(index, NewVReg, true));
1530 }
Evan Cheng96c61312007-11-29 01:06:25 +00001531 RestoreMBBs.set(MBBId);
1532 }
1533 }
1534
1535 // Update spill weight.
Evan Cheng26d17df2007-12-11 02:09:15 +00001536 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengf7b45f42008-06-21 06:45:54 +00001537 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng9b741602007-11-12 06:35:08 +00001538 }
Evan Chengebcba1e2007-12-05 03:22:34 +00001539
1540 if (NewVReg && TrySplit && AllCanFold) {
1541 // If all of its def / use can be folded, give it a low spill weight.
1542 LiveInterval &nI = getOrCreateInterval(NewVReg);
1543 nI.weight /= 10.0F;
1544 }
Evan Cheng9b741602007-11-12 06:35:08 +00001545}
1546
Evan Cheng7b632362007-11-29 10:12:14 +00001547bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1548 BitVector &RestoreMBBs,
Owen Andersonfeab1a82008-08-13 22:28:50 +00001549 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng7b632362007-11-29 10:12:14 +00001550 if (!RestoreMBBs[Id])
1551 return false;
1552 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1553 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1554 if (Restores[i].index == index &&
1555 Restores[i].vreg == vr &&
1556 Restores[i].canFold)
1557 return true;
1558 return false;
1559}
1560
1561void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1562 BitVector &RestoreMBBs,
Owen Andersonfeab1a82008-08-13 22:28:50 +00001563 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng7b632362007-11-29 10:12:14 +00001564 if (!RestoreMBBs[Id])
1565 return;
1566 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1567 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1568 if (Restores[i].index == index && Restores[i].vreg)
1569 Restores[i].index = -1;
1570}
Evan Chengcecc8222007-11-17 00:40:40 +00001571
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001572/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1573/// spilled and create empty intervals for their uses.
1574void
1575LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1576 const TargetRegisterClass* rc,
1577 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng70f68e92008-04-03 16:39:43 +00001578 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1579 re = mri_->reg_end(); ri != re; ) {
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001580 MachineOperand &O = ri.getOperand();
Evan Cheng70f68e92008-04-03 16:39:43 +00001581 MachineInstr *MI = &*ri;
1582 ++ri;
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001583 if (O.isDef()) {
1584 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1585 "Register def was not rewritten?");
1586 RemoveMachineInstrFromMaps(MI);
1587 vrm.RemoveMachineInstrFromMaps(MI);
1588 MI->eraseFromParent();
1589 } else {
1590 // This must be an use of an implicit_def so it's not part of the live
1591 // interval. Create a new empty live interval for it.
1592 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1593 unsigned NewVReg = mri_->createVirtualRegister(rc);
1594 vrm.grow();
1595 vrm.setIsImplicitlyDefined(NewVReg);
1596 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1597 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1598 MachineOperand &MO = MI->getOperand(i);
Dan Gohman7f7f3652008-09-13 17:58:21 +00001599 if (MO.isRegister() && MO.getReg() == li.reg)
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001600 MO.setReg(NewVReg);
1601 }
1602 }
Evan Cheng70f68e92008-04-03 16:39:43 +00001603 }
1604}
1605
Owen Anderson1cf81692008-08-18 19:52:22 +00001606namespace {
1607 struct LISorter {
1608 bool operator()(LiveInterval* A, LiveInterval* B) {
1609 return A->beginNumber() < B->beginNumber();
1610 }
1611 };
1612}
Evan Chengcecc8222007-11-17 00:40:40 +00001613
Evan Cheng9b741602007-11-12 06:35:08 +00001614std::vector<LiveInterval*> LiveIntervals::
Owen Anderson29042782008-08-18 18:05:32 +00001615addIntervalsForSpillsFast(const LiveInterval &li,
1616 const MachineLoopInfo *loopInfo,
1617 VirtRegMap &vrm, float& SSWeight) {
Owen Anderson06ab6d72008-08-18 23:41:04 +00001618 unsigned slot = vrm.assignVirt2StackSlot(li.reg);
Owen Anderson29042782008-08-18 18:05:32 +00001619
1620 std::vector<LiveInterval*> added;
1621
1622 assert(li.weight != HUGE_VALF &&
1623 "attempt to spill already spilled interval!");
1624
1625 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
1626 DEBUG(li.dump());
1627 DOUT << '\n';
1628
1629 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
1630
Owen Anderson268000d2008-08-18 21:20:32 +00001631 SSWeight = 0.0f;
1632
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001633 MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg);
1634 while (RI != mri_->reg_end()) {
1635 MachineInstr* MI = &*RI;
1636
1637 SmallVector<unsigned, 2> Indices;
1638 bool HasUse = false;
1639 bool HasDef = false;
1640
1641 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1642 MachineOperand& mop = MI->getOperand(i);
Dan Gohman7f7f3652008-09-13 17:58:21 +00001643 if (!mop.isRegister() || mop.getReg() != li.reg) continue;
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001644
1645 HasUse |= MI->getOperand(i).isUse();
1646 HasDef |= MI->getOperand(i).isDef();
1647
1648 Indices.push_back(i);
1649 }
1650
1651 if (!tryFoldMemoryOperand(MI, vrm, NULL, getInstructionIndex(MI),
1652 Indices, true, slot, li.reg)) {
1653 unsigned NewVReg = mri_->createVirtualRegister(rc);
Owen Anderson268000d2008-08-18 21:20:32 +00001654 vrm.grow();
Owen Anderson06ab6d72008-08-18 23:41:04 +00001655 vrm.assignVirt2StackSlot(NewVReg, slot);
1656
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001657 // create a new register for this spill
1658 LiveInterval &nI = getOrCreateInterval(NewVReg);
Owen Anderson29042782008-08-18 18:05:32 +00001659
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001660 // the spill weight is now infinity as it
1661 // cannot be spilled again
1662 nI.weight = HUGE_VALF;
1663
1664 // Rewrite register operands to use the new vreg.
1665 for (SmallVectorImpl<unsigned>::iterator I = Indices.begin(),
1666 E = Indices.end(); I != E; ++I) {
1667 MI->getOperand(*I).setReg(NewVReg);
1668
1669 if (MI->getOperand(*I).isUse())
1670 MI->getOperand(*I).setIsKill(true);
1671 }
1672
1673 // Fill in the new live interval.
1674 unsigned index = getInstructionIndex(MI);
1675 if (HasUse) {
1676 LiveRange LR(getLoadIndex(index), getUseIndex(index),
1677 nI.getNextValue(~0U, 0, getVNInfoAllocator()));
1678 DOUT << " +" << LR;
1679 nI.addRange(LR);
1680 vrm.addRestorePoint(NewVReg, MI);
1681 }
1682 if (HasDef) {
1683 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1684 nI.getNextValue(~0U, 0, getVNInfoAllocator()));
1685 DOUT << " +" << LR;
1686 nI.addRange(LR);
1687 vrm.addSpillPoint(NewVReg, true, MI);
1688 }
1689
Owen Anderson06ab6d72008-08-18 23:41:04 +00001690 added.push_back(&nI);
Owen Andersonfcfae3e2008-08-18 18:38:12 +00001691
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001692 DOUT << "\t\t\t\tadded new interval: ";
1693 DEBUG(nI.dump());
1694 DOUT << '\n';
1695
1696 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
1697 if (HasUse) {
1698 if (HasDef)
1699 SSWeight += getSpillWeight(true, true, loopDepth);
1700 else
1701 SSWeight += getSpillWeight(false, true, loopDepth);
1702 } else
1703 SSWeight += getSpillWeight(true, false, loopDepth);
1704 }
Owen Anderson268000d2008-08-18 21:20:32 +00001705
Owen Anderson268000d2008-08-18 21:20:32 +00001706
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001707 RI = mri_->reg_begin(li.reg);
Owen Anderson29042782008-08-18 18:05:32 +00001708 }
Owen Anderson29042782008-08-18 18:05:32 +00001709
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001710 // Clients expect the new intervals to be returned in sorted order.
Owen Anderson1cf81692008-08-18 19:52:22 +00001711 std::sort(added.begin(), added.end(), LISorter());
1712
Owen Anderson29042782008-08-18 18:05:32 +00001713 return added;
1714}
1715
1716std::vector<LiveInterval*> LiveIntervals::
Evan Chengcecc8222007-11-17 00:40:40 +00001717addIntervalsForSpills(const LiveInterval &li,
Evan Chengba221ca2008-06-06 07:54:39 +00001718 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1719 float &SSWeight) {
Owen Andersona9205692008-08-19 00:17:30 +00001720
1721 if (EnableFastSpilling)
1722 return addIntervalsForSpillsFast(li, loopInfo, vrm, SSWeight);
1723
Evan Cheng9b741602007-11-12 06:35:08 +00001724 assert(li.weight != HUGE_VALF &&
1725 "attempt to spill already spilled interval!");
1726
1727 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman1e57df32008-02-10 18:45:23 +00001728 li.print(DOUT, tri_);
Evan Cheng9b741602007-11-12 06:35:08 +00001729 DOUT << '\n';
1730
Evan Chengba221ca2008-06-06 07:54:39 +00001731 // Spill slot weight.
1732 SSWeight = 0.0f;
1733
Evan Chengcecc8222007-11-17 00:40:40 +00001734 // Each bit specify whether it a spill is required in the MBB.
1735 BitVector SpillMBBs(mf_->getNumBlockIDs());
Owen Andersonfeab1a82008-08-13 22:28:50 +00001736 DenseMap<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng96c61312007-11-29 01:06:25 +00001737 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Owen Andersonfeab1a82008-08-13 22:28:50 +00001738 DenseMap<unsigned, std::vector<SRInfo> > RestoreIdxes;
1739 DenseMap<unsigned,unsigned> MBBVRegsMap;
Evan Cheng9b741602007-11-12 06:35:08 +00001740 std::vector<LiveInterval*> NewLIs;
Evan Chenga37ecfe2008-02-22 09:24:50 +00001741 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Cheng9b741602007-11-12 06:35:08 +00001742
1743 unsigned NumValNums = li.getNumValNums();
1744 SmallVector<MachineInstr*, 4> ReMatDefs;
1745 ReMatDefs.resize(NumValNums, NULL);
1746 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1747 ReMatOrigDefs.resize(NumValNums, NULL);
1748 SmallVector<int, 4> ReMatIds;
1749 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1750 BitVector ReMatDelete(NumValNums);
1751 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1752
Evan Chengcecc8222007-11-17 00:40:40 +00001753 // Spilling a split live interval. It cannot be split any further. Also,
1754 // it's also guaranteed to be a single val# / range interval.
1755 if (vrm.getPreSplitReg(li.reg)) {
1756 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd9731042007-12-05 10:24:35 +00001757 // Unset the split kill marker on the last use.
1758 unsigned KillIdx = vrm.getKillPoint(li.reg);
1759 if (KillIdx) {
1760 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1761 assert(KillMI && "Last use disappeared?");
1762 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1763 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattner7f2d3b82007-12-30 21:56:09 +00001764 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd9731042007-12-05 10:24:35 +00001765 }
Evan Cheng6f522672007-12-05 09:51:10 +00001766 vrm.removeKillPoint(li.reg);
Evan Chengcecc8222007-11-17 00:40:40 +00001767 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1768 Slot = vrm.getStackSlot(li.reg);
1769 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1770 MachineInstr *ReMatDefMI = DefIsReMat ?
1771 vrm.getReMaterializedMI(li.reg) : NULL;
1772 int LdSlot = 0;
1773 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1774 bool isLoad = isLoadSS ||
Chris Lattner5b930372008-01-07 07:27:27 +00001775 (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
Evan Chengcecc8222007-11-17 00:40:40 +00001776 bool IsFirstRange = true;
1777 for (LiveInterval::Ranges::const_iterator
1778 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1779 // If this is a split live interval with multiple ranges, it means there
1780 // are two-address instructions that re-defined the value. Only the
1781 // first def can be rematerialized!
1782 if (IsFirstRange) {
Evan Cheng35d47762007-11-29 23:02:50 +00001783 // Note ReMatOrigDefMI has already been deleted.
Evan Chengcecc8222007-11-17 00:40:40 +00001784 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1785 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chenga37ecfe2008-02-22 09:24:50 +00001786 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng96c61312007-11-29 01:06:25 +00001787 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengba221ca2008-06-06 07:54:39 +00001788 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengcecc8222007-11-17 00:40:40 +00001789 } else {
1790 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1791 Slot, 0, false, false, false,
Evan Chenga37ecfe2008-02-22 09:24:50 +00001792 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng96c61312007-11-29 01:06:25 +00001793 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengba221ca2008-06-06 07:54:39 +00001794 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengcecc8222007-11-17 00:40:40 +00001795 }
1796 IsFirstRange = false;
1797 }
Evan Cheng70f68e92008-04-03 16:39:43 +00001798
Evan Chengba221ca2008-06-06 07:54:39 +00001799 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001800 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Chengcecc8222007-11-17 00:40:40 +00001801 return NewLIs;
1802 }
1803
1804 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng96c61312007-11-29 01:06:25 +00001805 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1806 TrySplit = false;
1807 if (TrySplit)
1808 ++numSplits;
Evan Cheng9b741602007-11-12 06:35:08 +00001809 bool NeedStackSlot = false;
1810 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1811 i != e; ++i) {
1812 const VNInfo *VNI = *i;
1813 unsigned VN = VNI->id;
1814 unsigned DefIdx = VNI->def;
1815 if (DefIdx == ~1U)
1816 continue; // Dead val#.
1817 // Is the def for the val# rematerializable?
Evan Chengcecc8222007-11-17 00:40:40 +00001818 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1819 ? 0 : getInstructionFromIndex(DefIdx);
Evan Chenge81fdb92007-12-06 00:01:56 +00001820 bool dummy;
1821 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, dummy)) {
Evan Cheng9b741602007-11-12 06:35:08 +00001822 // Remember how to remat the def of this val#.
Evan Chengcecc8222007-11-17 00:40:40 +00001823 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman8b3b5172008-07-17 23:49:46 +00001824 // Original def may be modified so we have to make a copy here.
Evan Cheng4ce1a522008-07-19 00:37:25 +00001825 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1826 ClonedMIs.push_back(Clone);
1827 ReMatDefs[VN] = Clone;
Evan Cheng9b741602007-11-12 06:35:08 +00001828
1829 bool CanDelete = true;
Evan Cheng8b70e632007-11-29 09:49:23 +00001830 if (VNI->hasPHIKill) {
1831 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Cheng9b741602007-11-12 06:35:08 +00001832 // It must not be deleted.
Evan Cheng8b70e632007-11-29 09:49:23 +00001833 CanDelete = false;
1834 // Need a stack slot if there is any live range where uses cannot be
1835 // rematerialized.
1836 NeedStackSlot = true;
Evan Cheng9b741602007-11-12 06:35:08 +00001837 }
Evan Cheng9b741602007-11-12 06:35:08 +00001838 if (CanDelete)
1839 ReMatDelete.set(VN);
1840 } else {
1841 // Need a stack slot if there is any live range where uses cannot be
1842 // rematerialized.
1843 NeedStackSlot = true;
1844 }
1845 }
1846
1847 // One stack slot per live interval.
Evan Chengcecc8222007-11-17 00:40:40 +00001848 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Cheng9b741602007-11-12 06:35:08 +00001849 Slot = vrm.assignVirt2StackSlot(li.reg);
1850
1851 // Create new intervals and rewrite defs and uses.
1852 for (LiveInterval::Ranges::const_iterator
1853 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Chengcecc8222007-11-17 00:40:40 +00001854 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1855 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1856 bool DefIsReMat = ReMatDefMI != NULL;
Evan Cheng9b741602007-11-12 06:35:08 +00001857 bool CanDelete = ReMatDelete[I->valno->id];
1858 int LdSlot = 0;
Evan Chengcecc8222007-11-17 00:40:40 +00001859 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Cheng9b741602007-11-12 06:35:08 +00001860 bool isLoad = isLoadSS ||
Chris Lattner5b930372008-01-07 07:27:27 +00001861 (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
Evan Chengcecc8222007-11-17 00:40:40 +00001862 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng96c61312007-11-29 01:06:25 +00001863 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chenga37ecfe2008-02-22 09:24:50 +00001864 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng96c61312007-11-29 01:06:25 +00001865 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengba221ca2008-06-06 07:54:39 +00001866 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng9b741602007-11-12 06:35:08 +00001867 }
1868
Evan Cheng96c61312007-11-29 01:06:25 +00001869 // Insert spills / restores if we are splitting.
Evan Cheng70f68e92008-04-03 16:39:43 +00001870 if (!TrySplit) {
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001871 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng7b632362007-11-29 10:12:14 +00001872 return NewLIs;
Evan Cheng70f68e92008-04-03 16:39:43 +00001873 }
Evan Cheng7b632362007-11-29 10:12:14 +00001874
Evan Chenged17a892007-12-05 08:16:32 +00001875 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001876 SmallVector<unsigned, 2> Ops;
Evan Cheng7b632362007-11-29 10:12:14 +00001877 if (NeedStackSlot) {
1878 int Id = SpillMBBs.find_first();
1879 while (Id != -1) {
Evan Chengba221ca2008-06-06 07:54:39 +00001880 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1881 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng7b632362007-11-29 10:12:14 +00001882 std::vector<SRInfo> &spills = SpillIdxes[Id];
1883 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1884 int index = spills[i].index;
1885 unsigned VReg = spills[i].vreg;
Evan Cheng3a46f222007-12-04 00:32:23 +00001886 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng96c61312007-11-29 01:06:25 +00001887 bool isReMat = vrm.isReMaterialized(VReg);
1888 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001889 bool CanFold = false;
1890 bool FoundUse = false;
1891 Ops.clear();
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001892 if (spills[i].canFold) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001893 CanFold = true;
Evan Cheng96c61312007-11-29 01:06:25 +00001894 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1895 MachineOperand &MO = MI->getOperand(j);
1896 if (!MO.isRegister() || MO.getReg() != VReg)
1897 continue;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001898
1899 Ops.push_back(j);
1900 if (MO.isDef())
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001901 continue;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001902 if (isReMat ||
1903 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1904 RestoreMBBs, RestoreIdxes))) {
1905 // MI has two-address uses of the same register. If the use
1906 // isn't the first and only use in the BB, then we can't fold
1907 // it. FIXME: Move this to rewriteInstructionsForSpills.
1908 CanFold = false;
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001909 break;
1910 }
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001911 FoundUse = true;
Evan Cheng96c61312007-11-29 01:06:25 +00001912 }
1913 }
1914 // Fold the store into the def if possible.
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001915 bool Folded = false;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001916 if (CanFold && !Ops.empty()) {
1917 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001918 Folded = true;
Evan Cheng550092f2007-12-05 09:05:34 +00001919 if (FoundUse > 0) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001920 // Also folded uses, do not issue a load.
1921 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Cheng550092f2007-12-05 09:05:34 +00001922 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
1923 }
Evan Cheng3a46f222007-12-04 00:32:23 +00001924 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001925 }
Evan Cheng96c61312007-11-29 01:06:25 +00001926 }
1927
Evan Cheng909ab8b42008-04-09 20:57:25 +00001928 // Otherwise tell the spiller to issue a spill.
Evan Chenged17a892007-12-05 08:16:32 +00001929 if (!Folded) {
1930 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
1931 bool isKill = LR->end == getStoreIndex(index);
Evan Cheng87dc7692008-05-20 08:10:37 +00001932 if (!MI->registerDefIsDead(nI.reg))
1933 // No need to spill a dead def.
1934 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chenged17a892007-12-05 08:16:32 +00001935 if (isKill)
1936 AddedKill.insert(&nI);
1937 }
Evan Chengba221ca2008-06-06 07:54:39 +00001938
1939 // Update spill slot weight.
1940 if (!isReMat)
Evan Chengf7b45f42008-06-21 06:45:54 +00001941 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng96c61312007-11-29 01:06:25 +00001942 }
Evan Cheng7b632362007-11-29 10:12:14 +00001943 Id = SpillMBBs.find_next(Id);
Evan Cheng96c61312007-11-29 01:06:25 +00001944 }
Evan Cheng7b632362007-11-29 10:12:14 +00001945 }
Evan Cheng96c61312007-11-29 01:06:25 +00001946
Evan Cheng7b632362007-11-29 10:12:14 +00001947 int Id = RestoreMBBs.find_first();
1948 while (Id != -1) {
Evan Chengba221ca2008-06-06 07:54:39 +00001949 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1950 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
1951
Evan Cheng7b632362007-11-29 10:12:14 +00001952 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1953 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
1954 int index = restores[i].index;
1955 if (index == -1)
1956 continue;
1957 unsigned VReg = restores[i].vreg;
Evan Cheng3a46f222007-12-04 00:32:23 +00001958 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Chengba221ca2008-06-06 07:54:39 +00001959 bool isReMat = vrm.isReMaterialized(VReg);
Evan Chengcecc8222007-11-17 00:40:40 +00001960 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001961 bool CanFold = false;
1962 Ops.clear();
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001963 if (restores[i].canFold) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001964 CanFold = true;
Evan Chengcecc8222007-11-17 00:40:40 +00001965 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1966 MachineOperand &MO = MI->getOperand(j);
1967 if (!MO.isRegister() || MO.getReg() != VReg)
1968 continue;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001969
Evan Cheng96c61312007-11-29 01:06:25 +00001970 if (MO.isDef()) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001971 // If this restore were to be folded, it would have been folded
1972 // already.
1973 CanFold = false;
Evan Chengcecc8222007-11-17 00:40:40 +00001974 break;
1975 }
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001976 Ops.push_back(j);
Evan Chengcecc8222007-11-17 00:40:40 +00001977 }
1978 }
Evan Cheng96c61312007-11-29 01:06:25 +00001979
1980 // Fold the load into the use if possible.
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001981 bool Folded = false;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001982 if (CanFold && !Ops.empty()) {
Evan Chengba221ca2008-06-06 07:54:39 +00001983 if (!isReMat)
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001984 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
1985 else {
Evan Cheng96c61312007-11-29 01:06:25 +00001986 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
1987 int LdSlot = 0;
1988 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1989 // If the rematerializable def is a load, also try to fold it.
Chris Lattner5b930372008-01-07 07:27:27 +00001990 if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001991 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1992 Ops, isLoadSS, LdSlot, VReg);
Evan Chenga37ecfe2008-02-22 09:24:50 +00001993 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
1994 if (ImpUse) {
1995 // Re-matting an instruction with virtual register use. Add the
1996 // register as an implicit use on the use MI and update the register
Evan Cheng8adc74e2008-03-31 07:53:30 +00001997 // interval's spill weight to HUGE_VALF to prevent it from being
1998 // spilled.
Evan Chenga37ecfe2008-02-22 09:24:50 +00001999 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng8adc74e2008-03-31 07:53:30 +00002000 ImpLi.weight = HUGE_VALF;
Evan Chenga37ecfe2008-02-22 09:24:50 +00002001 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
2002 }
Evan Chengfd0bd3c2007-12-02 08:30:39 +00002003 }
Evan Cheng96c61312007-11-29 01:06:25 +00002004 }
2005 // If folding is not possible / failed, then tell the spiller to issue a
2006 // load / rematerialization for us.
Evan Cheng3a46f222007-12-04 00:32:23 +00002007 if (Folded)
2008 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chenged17a892007-12-05 08:16:32 +00002009 else
Evan Cheng96c61312007-11-29 01:06:25 +00002010 vrm.addRestorePoint(VReg, MI);
Evan Chengba221ca2008-06-06 07:54:39 +00002011
2012 // Update spill slot weight.
2013 if (!isReMat)
Evan Chengf7b45f42008-06-21 06:45:54 +00002014 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Chengcecc8222007-11-17 00:40:40 +00002015 }
Evan Cheng7b632362007-11-29 10:12:14 +00002016 Id = RestoreMBBs.find_next(Id);
Evan Chengcecc8222007-11-17 00:40:40 +00002017 }
2018
Evan Chenged17a892007-12-05 08:16:32 +00002019 // Finalize intervals: add kills, finalize spill weights, and filter out
2020 // dead intervals.
Evan Cheng3a46f222007-12-04 00:32:23 +00002021 std::vector<LiveInterval*> RetNewLIs;
2022 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
2023 LiveInterval *LI = NewLIs[i];
2024 if (!LI->empty()) {
Owen Anderson50ca1a22008-07-23 19:47:27 +00002025 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chenged17a892007-12-05 08:16:32 +00002026 if (!AddedKill.count(LI)) {
2027 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd9731042007-12-05 10:24:35 +00002028 unsigned LastUseIdx = getBaseIndex(LR->end);
2029 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Chengc7daf1f2008-03-05 00:59:57 +00002030 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chenged17a892007-12-05 08:16:32 +00002031 assert(UseIdx != -1);
Evan Chenga37ecfe2008-02-22 09:24:50 +00002032 if (LastUse->getOperand(UseIdx).isImplicit() ||
2033 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chenged17a892007-12-05 08:16:32 +00002034 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd9731042007-12-05 10:24:35 +00002035 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Cheng6f522672007-12-05 09:51:10 +00002036 }
Evan Chenged17a892007-12-05 08:16:32 +00002037 }
Evan Cheng3a46f222007-12-04 00:32:23 +00002038 RetNewLIs.push_back(LI);
2039 }
2040 }
Evan Chengcecc8222007-11-17 00:40:40 +00002041
Evan Cheng7b88cbc2008-04-11 17:53:36 +00002042 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng3a46f222007-12-04 00:32:23 +00002043 return RetNewLIs;
Evan Cheng9b741602007-11-12 06:35:08 +00002044}
Evan Cheng14cc83f2008-03-11 07:19:34 +00002045
2046/// hasAllocatableSuperReg - Return true if the specified physical register has
2047/// any super register that's allocatable.
2048bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
2049 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
2050 if (allocatableRegs_[*AS] && hasInterval(*AS))
2051 return true;
2052 return false;
2053}
2054
2055/// getRepresentativeReg - Find the largest super register of the specified
2056/// physical register.
2057unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
2058 // Find the largest super-register that is allocatable.
2059 unsigned BestReg = Reg;
2060 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
2061 unsigned SuperReg = *AS;
2062 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
2063 BestReg = SuperReg;
2064 break;
2065 }
2066 }
2067 return BestReg;
2068}
2069
2070/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
2071/// specified interval that conflicts with the specified physical register.
2072unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
2073 unsigned PhysReg) const {
2074 unsigned NumConflicts = 0;
2075 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
2076 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2077 E = mri_->reg_end(); I != E; ++I) {
2078 MachineOperand &O = I.getOperand();
2079 MachineInstr *MI = O.getParent();
2080 unsigned Index = getInstructionIndex(MI);
2081 if (pli.liveAt(Index))
2082 ++NumConflicts;
2083 }
2084 return NumConflicts;
2085}
2086
2087/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
2088/// around all defs and uses of the specified interval.
2089void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
2090 unsigned PhysReg, VirtRegMap &vrm) {
2091 unsigned SpillReg = getRepresentativeReg(PhysReg);
2092
2093 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
2094 // If there are registers which alias PhysReg, but which are not a
2095 // sub-register of the chosen representative super register. Assert
2096 // since we can't handle it yet.
2097 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
2098 tri_->isSuperRegister(*AS, SpillReg));
2099
2100 LiveInterval &pli = getInterval(SpillReg);
2101 SmallPtrSet<MachineInstr*, 8> SeenMIs;
2102 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2103 E = mri_->reg_end(); I != E; ++I) {
2104 MachineOperand &O = I.getOperand();
2105 MachineInstr *MI = O.getParent();
2106 if (SeenMIs.count(MI))
2107 continue;
2108 SeenMIs.insert(MI);
2109 unsigned Index = getInstructionIndex(MI);
2110 if (pli.liveAt(Index)) {
2111 vrm.addEmergencySpill(SpillReg, MI);
2112 pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
2113 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
2114 if (!hasInterval(*AS))
2115 continue;
2116 LiveInterval &spli = getInterval(*AS);
2117 if (spli.liveAt(Index))
2118 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
2119 }
2120 }
2121 }
2122}
Owen Anderson7399f222008-06-05 17:15:43 +00002123
2124LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
2125 MachineInstr* startInst) {
2126 LiveInterval& Interval = getOrCreateInterval(reg);
2127 VNInfo* VN = Interval.getNextValue(
2128 getInstructionIndex(startInst) + InstrSlots::DEF,
2129 startInst, getVNInfoAllocator());
2130 VN->hasPHIKill = true;
2131 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
2132 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
2133 getMBBEndIdx(startInst->getParent()) + 1, VN);
2134 Interval.addRange(LR);
2135
2136 return LR;
2137}