blob: c91adbadaee4c42e0df092e85b88dc2a6e40e5c1 [file] [log] [blame]
Chris Lattnera3b8b5c2004-07-23 17:56:30 +00001//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveInterval analysis pass which is used
11// by the Linear Scan Register allocator. This pass linearizes the
12// basic blocks of the function in DFS order and uses the
13// LiveVariables pass to conservatively compute live intervals for
14// each virtual and physical register.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "liveintervals"
Chris Lattner3c3fe462005-09-21 04:19:09 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Misha Brukman08a6c762004-09-03 18:25:53 +000020#include "VirtRegMap.h"
Chris Lattner015959e2004-05-01 21:24:39 +000021#include "llvm/Value.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000022#include "llvm/Analysis/AliasAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000023#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000028#include "llvm/CodeGen/Passes.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000029#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000030#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000033#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000038#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000039#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000040using namespace llvm;
41
Dan Gohman844731a2008-05-13 00:00:25 +000042// Hidden options for help debugging.
43static cl::opt<bool> DisableReMat("disable-rematerialization",
44 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000045
Dan Gohman844731a2008-05-13 00:00:25 +000046static cl::opt<bool> SplitAtBB("split-intervals-at-bb",
47 cl::init(true), cl::Hidden);
48static cl::opt<int> SplitLimit("split-limit",
49 cl::init(-1), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000050
Dan Gohman4c8f8702008-07-25 15:08:37 +000051static cl::opt<bool> EnableAggressiveRemat("aggressive-remat", cl::Hidden);
52
Owen Andersonae339ba2008-08-19 00:17:30 +000053static cl::opt<bool> EnableFastSpilling("fast-spill",
54 cl::init(false), cl::Hidden);
55
Chris Lattnercd3245a2006-12-19 22:41:21 +000056STATISTIC(numIntervals, "Number of original intervals");
57STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
Evan Cheng0cbb1162007-11-29 01:06:25 +000058STATISTIC(numFolds , "Number of loads/stores folded into instructions");
59STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000060
Devang Patel19974732007-05-03 01:11:54 +000061char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000062static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000063
Chris Lattnerf7da2c72006-08-24 22:43:55 +000064void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman6d69ba82008-07-25 00:02:30 +000065 AU.addRequired<AliasAnalysis>();
66 AU.addPreserved<AliasAnalysis>();
David Greene25133302007-06-08 17:18:56 +000067 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000068 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000069 AU.addPreservedID(MachineLoopInfoID);
70 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +000071
72 if (!StrongPHIElim) {
73 AU.addPreservedID(PHIEliminationID);
74 AU.addRequiredID(PHIEliminationID);
75 }
76
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000077 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000078 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000079}
80
Chris Lattnerf7da2c72006-08-24 22:43:55 +000081void LiveIntervals::releaseMemory() {
Owen Anderson03857b22008-08-13 21:49:13 +000082 // Free the live intervals themselves.
Owen Anderson20e28392008-08-13 22:08:30 +000083 for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
Owen Anderson03857b22008-08-13 21:49:13 +000084 E = r2iMap_.end(); I != E; ++I)
85 delete I->second;
86
Evan Cheng3f32d652008-06-04 09:18:41 +000087 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000088 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000089 mi2iMap_.clear();
90 i2miMap_.clear();
91 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000092 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
93 VNInfoAllocator.Reset();
Evan Cheng1ed99222008-07-19 00:37:25 +000094 while (!ClonedMIs.empty()) {
95 MachineInstr *MI = ClonedMIs.back();
96 ClonedMIs.pop_back();
97 mf_->DeleteMachineInstr(MI);
98 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000099}
100
Owen Anderson80b3ce62008-05-28 20:54:50 +0000101void LiveIntervals::computeNumbering() {
102 Index2MiMap OldI2MI = i2miMap_;
Owen Anderson7fbad272008-07-23 21:37:49 +0000103 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Anderson80b3ce62008-05-28 20:54:50 +0000104
105 Idx2MBBMap.clear();
106 MBB2IdxMap.clear();
107 mi2iMap_.clear();
108 i2miMap_.clear();
109
Owen Andersona1566f22008-07-22 22:46:49 +0000110 FunctionSize = 0;
111
Chris Lattner428b92e2006-09-15 03:57:23 +0000112 // Number MachineInstrs and MachineBasicBlocks.
113 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +0000114 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +0000115
116 unsigned MIIndex = 0;
117 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
118 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000119 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000120
Owen Anderson7fbad272008-07-23 21:37:49 +0000121 // Insert an empty slot at the beginning of each block.
122 MIIndex += InstrSlots::NUM;
123 i2miMap_.push_back(0);
124
Chris Lattner428b92e2006-09-15 03:57:23 +0000125 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
126 I != E; ++I) {
127 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000128 assert(inserted && "multiple MachineInstr -> index mappings");
Chris Lattner428b92e2006-09-15 03:57:23 +0000129 i2miMap_.push_back(I);
130 MIIndex += InstrSlots::NUM;
Owen Andersona1566f22008-07-22 22:46:49 +0000131 FunctionSize++;
Owen Anderson7fbad272008-07-23 21:37:49 +0000132
Evan Cheng4ed43292008-10-18 05:21:37 +0000133 // Insert max(1, numdefs) empty slots after every instruction.
Evan Cheng99fe34b2008-10-18 05:18:55 +0000134 unsigned Slots = I->getDesc().getNumDefs();
135 if (Slots == 0)
136 Slots = 1;
137 MIIndex += InstrSlots::NUM * Slots;
138 while (Slots--)
139 i2miMap_.push_back(0);
Owen Anderson35578012008-06-16 07:10:49 +0000140 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000141
Owen Anderson1fbb4542008-06-16 16:58:24 +0000142 // Set the MBB2IdxMap entry for this MBB.
143 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
144 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000145 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000146 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000147
148 if (!OldI2MI.empty())
Owen Anderson788d0412008-08-06 18:35:45 +0000149 for (iterator OI = begin(), OE = end(); OI != OE; ++OI) {
Owen Anderson03857b22008-08-13 21:49:13 +0000150 for (LiveInterval::iterator LI = OI->second->begin(),
151 LE = OI->second->end(); LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000152
Owen Anderson7eec0c22008-05-29 23:01:22 +0000153 // Remap the start index of the live range to the corresponding new
154 // number, or our best guess at what it _should_ correspond to if the
155 // original instruction has been erased. This is either the following
156 // instruction or its predecessor.
Owen Anderson7fbad272008-07-23 21:37:49 +0000157 unsigned index = LI->start / InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000158 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson0a7615a2008-07-25 23:06:59 +0000159 if (offset == InstrSlots::LOAD) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000160 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000161 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->start);
Owen Anderson7fbad272008-07-23 21:37:49 +0000162 // Take the pair containing the index
163 std::vector<IdxMBBPair>::const_iterator J =
Owen Andersona0c032f2008-07-29 21:15:44 +0000164 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000165
Owen Anderson7fbad272008-07-23 21:37:49 +0000166 LI->start = getMBBStartIdx(J->second);
167 } else {
168 LI->start = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000169 }
170
171 // Remap the ending index in the same way that we remapped the start,
172 // except for the final step where we always map to the immediately
173 // following instruction.
Owen Andersond7dcbec2008-07-25 19:50:48 +0000174 index = (LI->end - 1) / InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000175 offset = LI->end % InstrSlots::NUM;
Owen Anderson9382b932008-07-30 00:22:56 +0000176 if (offset == InstrSlots::LOAD) {
177 // VReg dies at end of block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000178 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000179 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end);
Owen Anderson9382b932008-07-30 00:22:56 +0000180 --I;
Owen Anderson7fbad272008-07-23 21:37:49 +0000181
Owen Anderson9382b932008-07-30 00:22:56 +0000182 LI->end = getMBBEndIdx(I->second) + 1;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000183 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000184 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000185 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
186
187 if (index != OldI2MI.size())
188 LI->end = mi2iMap_[OldI2MI[index]] + (idx == index ? offset : 0);
189 else
190 LI->end = InstrSlots::NUM * i2miMap_.size();
Owen Anderson4b5b2092008-05-29 18:15:49 +0000191 }
Owen Anderson788d0412008-08-06 18:35:45 +0000192 }
193
Owen Anderson03857b22008-08-13 21:49:13 +0000194 for (LiveInterval::vni_iterator VNI = OI->second->vni_begin(),
195 VNE = OI->second->vni_end(); VNI != VNE; ++VNI) {
Owen Anderson788d0412008-08-06 18:35:45 +0000196 VNInfo* vni = *VNI;
Owen Anderson745825f42008-05-28 22:40:08 +0000197
Owen Anderson7eec0c22008-05-29 23:01:22 +0000198 // Remap the VNInfo def index, which works the same as the
Owen Anderson788d0412008-08-06 18:35:45 +0000199 // start indices above. VN's with special sentinel defs
200 // don't need to be remapped.
Owen Anderson91292392008-07-30 17:42:47 +0000201 if (vni->def != ~0U && vni->def != ~1U) {
Owen Anderson788d0412008-08-06 18:35:45 +0000202 unsigned index = vni->def / InstrSlots::NUM;
203 unsigned offset = vni->def % InstrSlots::NUM;
Owen Anderson91292392008-07-30 17:42:47 +0000204 if (offset == InstrSlots::LOAD) {
205 std::vector<IdxMBBPair>::const_iterator I =
Owen Anderson0a7615a2008-07-25 23:06:59 +0000206 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->def);
Owen Anderson91292392008-07-30 17:42:47 +0000207 // Take the pair containing the index
208 std::vector<IdxMBBPair>::const_iterator J =
Owen Andersona0c032f2008-07-29 21:15:44 +0000209 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000210
Owen Anderson91292392008-07-30 17:42:47 +0000211 vni->def = getMBBStartIdx(J->second);
212 } else {
213 vni->def = mi2iMap_[OldI2MI[index]] + offset;
214 }
Owen Anderson7eec0c22008-05-29 23:01:22 +0000215 }
Owen Anderson745825f42008-05-28 22:40:08 +0000216
Owen Anderson7eec0c22008-05-29 23:01:22 +0000217 // Remap the VNInfo kill indices, which works the same as
218 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000219 for (size_t i = 0; i < vni->kills.size(); ++i) {
Owen Anderson9382b932008-07-30 00:22:56 +0000220 // PHI kills don't need to be remapped.
221 if (!vni->kills[i]) continue;
222
Owen Anderson788d0412008-08-06 18:35:45 +0000223 unsigned index = (vni->kills[i]-1) / InstrSlots::NUM;
224 unsigned offset = vni->kills[i] % InstrSlots::NUM;
Owen Anderson309c6162008-09-30 22:51:54 +0000225 if (offset == InstrSlots::LOAD) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000226 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000227 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->kills[i]);
Owen Anderson9382b932008-07-30 00:22:56 +0000228 --I;
Owen Anderson7fbad272008-07-23 21:37:49 +0000229
Owen Anderson788d0412008-08-06 18:35:45 +0000230 vni->kills[i] = getMBBEndIdx(I->second);
Owen Anderson7fbad272008-07-23 21:37:49 +0000231 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000232 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000233 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
234
235 if (index != OldI2MI.size())
236 vni->kills[i] = mi2iMap_[OldI2MI[index]] +
237 (idx == index ? offset : 0);
238 else
239 vni->kills[i] = InstrSlots::NUM * i2miMap_.size();
Owen Anderson7eec0c22008-05-29 23:01:22 +0000240 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000241 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000242 }
Owen Anderson788d0412008-08-06 18:35:45 +0000243 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000244}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000245
Owen Anderson80b3ce62008-05-28 20:54:50 +0000246/// runOnMachineFunction - Register allocate the whole function
247///
248bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
249 mf_ = &fn;
250 mri_ = &mf_->getRegInfo();
251 tm_ = &fn.getTarget();
252 tri_ = tm_->getRegisterInfo();
253 tii_ = tm_->getInstrInfo();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000254 aa_ = &getAnalysis<AliasAnalysis>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000255 lv_ = &getAnalysis<LiveVariables>();
256 allocatableRegs_ = tri_->getAllocatableSet(fn);
257
258 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000259 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000260
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000261 numIntervals += getNumIntervals();
262
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000263 DOUT << "********** INTERVALS **********\n";
264 for (iterator I = begin(), E = end(); I != E; ++I) {
Owen Anderson03857b22008-08-13 21:49:13 +0000265 I->second->print(DOUT, tri_);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000266 DOUT << "\n";
267 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000268
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000269 numIntervalsAfter += getNumIntervals();
Chris Lattner70ca3582004-09-30 15:59:17 +0000270 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000271 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000272}
273
Chris Lattner70ca3582004-09-30 15:59:17 +0000274/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000275void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000276 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000277 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Owen Anderson03857b22008-08-13 21:49:13 +0000278 I->second->print(O, tri_);
Evan Cheng3f32d652008-06-04 09:18:41 +0000279 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000280 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000281
282 O << "********** MACHINEINSTRS **********\n";
283 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
284 mbbi != mbbe; ++mbbi) {
285 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
286 for (MachineBasicBlock::iterator mii = mbbi->begin(),
287 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000288 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000289 }
290 }
291}
292
Evan Chengc92da382007-11-03 07:20:12 +0000293/// conflictsWithPhysRegDef - Returns true if the specified register
294/// is defined during the duration of the specified interval.
295bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
296 VirtRegMap &vrm, unsigned reg) {
297 for (LiveInterval::Ranges::const_iterator
298 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
299 for (unsigned index = getBaseIndex(I->start),
300 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
301 index += InstrSlots::NUM) {
302 // skip deleted instructions
303 while (index != end && !getInstructionFromIndex(index))
304 index += InstrSlots::NUM;
305 if (index == end) break;
306
307 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng5d446262007-11-15 08:13:29 +0000308 unsigned SrcReg, DstReg;
309 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
310 if (SrcReg == li.reg || DstReg == li.reg)
311 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000312 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
313 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000314 if (!mop.isReg())
Evan Chengc92da382007-11-03 07:20:12 +0000315 continue;
316 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000317 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000318 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000319 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000320 if (!vrm.hasPhys(PhysReg))
321 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000322 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000323 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000324 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000325 return true;
326 }
327 }
328 }
329
330 return false;
331}
332
Evan Cheng549f27d32007-08-13 23:45:17 +0000333void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000334 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000335 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000336 else
337 cerr << "%reg" << reg;
338}
339
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000340void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000341 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000342 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000343 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000344 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000345 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000346 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000347
Evan Cheng419852c2008-04-03 16:39:43 +0000348 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
349 DOUT << "is a implicit_def\n";
350 return;
351 }
352
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000353 // Virtual registers may be defined multiple times (due to phi
354 // elimination and 2-addr elimination). Much of what we do only has to be
355 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000356 // time we see a vreg.
357 if (interval.empty()) {
358 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000359 unsigned defIndex = getDefIndex(MIIdx);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000360 // Earlyclobbers move back one.
361 if (MO.isEarlyClobber())
362 defIndex = getUseIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000363 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000364 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000365 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000366 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000367 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000368 tii_->isMoveInstr(*mi, SrcReg, DstReg))
369 CopyMI = mi;
370 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000371
372 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000373
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000374 // Loop over all of the blocks that the vreg is defined in. There are
375 // two cases we have to handle here. The most common case is a vreg
376 // whose lifetime is contained within a basic block. In this case there
377 // will be a single kill, in MBB, which comes after the definition.
378 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
379 // FIXME: what about dead vars?
380 unsigned killIdx;
381 if (vi.Kills[0] != mi)
382 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
383 else
384 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000385
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000386 // If the kill happens after the definition, we have an intra-block
387 // live range.
388 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000389 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000390 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000391 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000392 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000393 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000394 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000395 return;
396 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000397 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000398
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000399 // The other case we handle is when a virtual register lives to the end
400 // of the defining block, potentially live across some blocks, then is
401 // live into some number of blocks, but gets killed. Start by adding a
402 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000403 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000404 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000405 interval.addRange(NewLR);
406
407 // Iterate over all of the blocks that the variable is completely
408 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
409 // live interval.
410 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
411 if (vi.AliveBlocks[i]) {
Owen Anderson31ec8412008-06-16 19:32:40 +0000412 LiveRange LR(getMBBStartIdx(i),
Evan Chengf26e8552008-06-17 20:13:36 +0000413 getMBBEndIdx(i)+1, // MBB ends at -1.
Owen Anderson31ec8412008-06-16 19:32:40 +0000414 ValNo);
415 interval.addRange(LR);
416 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000417 }
418 }
419
420 // Finally, this virtual register is live from the start of any killing
421 // block to the 'use' slot of the killing instruction.
422 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
423 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000424 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000425 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000426 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000427 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000428 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000429 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000430 }
431
432 } else {
433 // If this is the second time we see a virtual register definition, it
434 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000435 // the result of two address elimination, then the vreg is one of the
436 // def-and-use register operand.
Evan Chengef0732d2008-07-10 07:35:43 +0000437 if (mi->isRegReDefinedByTwoAddr(interval.reg, MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000438 // If this is a two-address definition, then we have already processed
439 // the live range. The only problem is that we didn't realize there
440 // are actually two values in the live interval. Because of this we
441 // need to take the LiveRegion that defines this register and split it
442 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000443 assert(interval.containsOneValue());
444 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000445 unsigned RedefIndex = getDefIndex(MIIdx);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000446 // Earlyclobbers move back one.
447 if (MO.isEarlyClobber())
448 RedefIndex = getUseIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000449
Evan Cheng4f8ff162007-08-11 00:59:19 +0000450 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000451 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000452
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000453 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000454 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000455 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000456
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000457 // Two-address vregs should always only be redefined once. This means
458 // that at this point, there should be exactly one value number in it.
459 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
460
Chris Lattner91725b72006-08-31 05:54:43 +0000461 // The new value number (#1) is defined by the instruction we claimed
462 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000463 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
464 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000465
Chris Lattner91725b72006-08-31 05:54:43 +0000466 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000467 OldValNo->def = RedefIndex;
468 OldValNo->copy = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000469
470 // Add the new live interval which replaces the range for the input copy.
471 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000472 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000473 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000474 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000475
476 // If this redefinition is dead, we need to add a dummy unit live
477 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000478 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000479 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000480
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000481 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000482 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000483
484 } else {
485 // Otherwise, this must be because of phi elimination. If this is the
486 // first redefinition of the vreg that we have seen, go back and change
487 // the live range in the PHI block to be a different value number.
488 if (interval.containsOneValue()) {
489 assert(vi.Kills.size() == 1 &&
490 "PHI elimination vreg should have one kill, the PHI itself!");
491
492 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000493 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000494 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000495 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000496 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000497 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000498 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000499 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000500 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000501 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000502
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000503 // Replace the interval with one of a NEW value number. Note that this
504 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000505 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000506 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000507 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000508 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000509 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000510 }
511
512 // In the case of PHI elimination, each variable definition is only
513 // live until the end of the block. We've already taken care of the
514 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000515 unsigned defIndex = getDefIndex(MIIdx);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000516 // Earlyclobbers move back one.
517 if (MO.isEarlyClobber())
518 defIndex = getUseIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000519
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000520 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000521 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000522 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000523 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000524 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000525 tii_->isMoveInstr(*mi, SrcReg, DstReg))
526 CopyMI = mi;
527 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000528
Owen Anderson7fbad272008-07-23 21:37:49 +0000529 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000530 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000531 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000532 interval.addKill(ValNo, killIndex);
533 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000534 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000535 }
536 }
537
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000538 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000539}
540
Chris Lattnerf35fef72004-07-23 21:24:19 +0000541void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000542 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000543 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000544 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000545 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000546 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000547 // A physical register cannot be live across basic block, so its
548 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000549 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000550
Chris Lattner6b128bd2006-09-03 08:07:11 +0000551 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000552 unsigned start = getDefIndex(baseIndex);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000553 // Earlyclobbers move back one.
554 if (MO.isEarlyClobber())
555 start = getUseIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000556 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000557
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000558 // If it is not used after definition, it is considered dead at
559 // the instruction defining it. Hence its interval is:
560 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000561 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000562 DOUT << " dead";
Dale Johannesen86b49f82008-09-24 01:07:17 +0000563 end = start + 1;
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000564 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000565 }
566
567 // If it is not dead on definition, it must be killed by a
568 // subsequent instruction. Hence its interval is:
569 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000570 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000571 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000572 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
573 getInstructionFromIndex(baseIndex) == 0)
574 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000575 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000576 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000577 end = getUseIndex(baseIndex) + 1;
578 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000579 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000580 // Another instruction redefines the register before it is ever read.
581 // Then the register is essentially dead at the instruction that defines
582 // it. Hence its interval is:
583 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000584 DOUT << " dead";
Dale Johannesen86b49f82008-09-24 01:07:17 +0000585 end = start + 1;
Evan Cheng9a1956a2006-11-15 20:54:11 +0000586 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000587 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000588
589 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000590 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000591
592 // The only case we should have a dead physreg here without a killing or
593 // instruction where we know it's dead is if it is live-in to the function
594 // and never used.
Evan Chengc8d044e2008-02-15 18:24:29 +0000595 assert(!CopyMI && "physreg was not killed in defining block!");
Dale Johannesen86b49f82008-09-24 01:07:17 +0000596 end = start + 1;
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000597
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000598exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000599 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000600
Evan Cheng24a3cc42007-04-25 07:30:23 +0000601 // Already exists? Extend old live interval.
602 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000603 VNInfo *ValNo = (OldLR != interval.end())
Evan Chengc8d044e2008-02-15 18:24:29 +0000604 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000605 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000606 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000607 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000608 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000609}
610
Chris Lattnerf35fef72004-07-23 21:24:19 +0000611void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
612 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000613 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000614 MachineOperand& MO,
615 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000616 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000617 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000618 getOrCreateInterval(MO.getReg()));
619 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000620 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000621 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000622 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000623 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000624 tii_->isMoveInstr(*MI, SrcReg, DstReg))
625 CopyMI = MI;
Owen Anderson6b098de2008-06-25 23:39:39 +0000626 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
627 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000628 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000629 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000630 // If MI also modifies the sub-register explicitly, avoid processing it
631 // more than once. Do not pass in TRI here so it checks for exact match.
632 if (!MI->modifiesRegister(*AS))
Owen Anderson6b098de2008-06-25 23:39:39 +0000633 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
634 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000635 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000636}
637
Evan Chengb371f452007-02-19 21:49:54 +0000638void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000639 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000640 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000641 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
642
643 // Look for kills, if it reaches a def before it's killed, then it shouldn't
644 // be considered a livein.
645 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000646 unsigned baseIndex = MIIdx;
647 unsigned start = baseIndex;
Owen Anderson99500ae2008-09-15 22:00:38 +0000648 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
649 getInstructionFromIndex(baseIndex) == 0)
650 baseIndex += InstrSlots::NUM;
651 unsigned end = baseIndex;
652
Evan Chengb371f452007-02-19 21:49:54 +0000653 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000654 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000655 DOUT << " killed";
656 end = getUseIndex(baseIndex) + 1;
657 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000658 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000659 // Another instruction redefines the register before it is ever read.
660 // Then the register is essentially dead at the instruction that defines
661 // it. Hence its interval is:
662 // [defSlot(def), defSlot(def)+1)
663 DOUT << " dead";
664 end = getDefIndex(start) + 1;
665 goto exit;
666 }
667
668 baseIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000669 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
670 getInstructionFromIndex(baseIndex) == 0)
671 baseIndex += InstrSlots::NUM;
Evan Chengb371f452007-02-19 21:49:54 +0000672 ++mi;
673 }
674
675exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000676 // Live-in register might not be used at all.
677 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000678 if (isAlias) {
679 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000680 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000681 } else {
682 DOUT << " live through";
683 end = baseIndex;
684 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000685 }
686
Owen Anderson99500ae2008-09-15 22:00:38 +0000687 LiveRange LR(start, end, interval.getNextValue(~0U, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000688 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000689 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000690 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000691}
692
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000693/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000694/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000695/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000696/// which a variable is live
Dale Johannesen91aac102008-09-17 21:13:11 +0000697void LiveIntervals::computeIntervals() {
Dale Johannesen91aac102008-09-17 21:13:11 +0000698
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000699 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
700 << "********** Function: "
701 << ((Value*)mf_->getFunction())->getName() << '\n';
Owen Anderson7fbad272008-07-23 21:37:49 +0000702
Chris Lattner428b92e2006-09-15 03:57:23 +0000703 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
704 MBBI != E; ++MBBI) {
705 MachineBasicBlock *MBB = MBBI;
Owen Anderson134eb732008-09-21 20:43:24 +0000706 // Track the index of the current machine instr.
707 unsigned MIIndex = getMBBStartIdx(MBB);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000708 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000709
Chris Lattner428b92e2006-09-15 03:57:23 +0000710 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000711
Dan Gohmancb406c22007-10-03 19:26:29 +0000712 // Create intervals for live-ins to this BB first.
713 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
714 LE = MBB->livein_end(); LI != LE; ++LI) {
715 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
716 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000717 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000718 if (!hasInterval(*AS))
719 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
720 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000721 }
722
Owen Anderson99500ae2008-09-15 22:00:38 +0000723 // Skip over empty initial indices.
724 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
725 getInstructionFromIndex(MIIndex) == 0)
726 MIIndex += InstrSlots::NUM;
727
Chris Lattner428b92e2006-09-15 03:57:23 +0000728 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000729 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000730
Evan Cheng438f7bc2006-11-10 08:43:01 +0000731 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000732 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
733 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000734 // handle register defs - build intervals
Dan Gohmand735b802008-10-03 15:45:36 +0000735 if (MO.isReg() && MO.getReg() && MO.isDef()) {
Evan Chengef0732d2008-07-10 07:35:43 +0000736 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Dale Johannesen91aac102008-09-17 21:13:11 +0000737 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000738 }
Evan Cheng99fe34b2008-10-18 05:18:55 +0000739
740 // Skip over the empty slots after each instruction.
741 unsigned Slots = MI->getDesc().getNumDefs();
742 if (Slots == 0)
743 Slots = 1;
744 MIIndex += InstrSlots::NUM * Slots;
Owen Anderson7fbad272008-07-23 21:37:49 +0000745
746 // Skip over empty indices.
747 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
748 getInstructionFromIndex(MIIndex) == 0)
749 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000750 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000751 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000752}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000753
Evan Cheng4ca980e2007-10-17 02:10:22 +0000754bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Chenga5bfc972007-10-17 06:53:44 +0000755 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000756 std::vector<IdxMBBPair>::const_iterator I =
757 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
758
759 bool ResVal = false;
760 while (I != Idx2MBBMap.end()) {
761 if (LR.end <= I->first)
762 break;
763 MBBs.push_back(I->second);
764 ResVal = true;
765 ++I;
766 }
767 return ResVal;
768}
769
Owen Anderson03857b22008-08-13 21:49:13 +0000770LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000771 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000772 HUGE_VALF : 0.0F;
Owen Anderson03857b22008-08-13 21:49:13 +0000773 return new LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000774}
Evan Chengf2fbca62007-11-12 06:35:08 +0000775
Evan Chengc8d044e2008-02-15 18:24:29 +0000776/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
777/// copy field and returns the source register that defines it.
778unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
779 if (!VNI->copy)
780 return 0;
781
782 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
783 return VNI->copy->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000784 if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
785 return VNI->copy->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000786 unsigned SrcReg, DstReg;
787 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
788 return SrcReg;
789 assert(0 && "Unrecognized copy instruction!");
790 return 0;
791}
Evan Chengf2fbca62007-11-12 06:35:08 +0000792
793//===----------------------------------------------------------------------===//
794// Register allocator hooks.
795//
796
Evan Chengd70dbb52008-02-22 09:24:50 +0000797/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
798/// allow one) virtual register operand, then its uses are implicitly using
799/// the register. Returns the virtual register.
800unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
801 MachineInstr *MI) const {
802 unsigned RegOp = 0;
803 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
804 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000805 if (!MO.isReg() || !MO.isUse())
Evan Chengd70dbb52008-02-22 09:24:50 +0000806 continue;
807 unsigned Reg = MO.getReg();
808 if (Reg == 0 || Reg == li.reg)
809 continue;
810 // FIXME: For now, only remat MI with at most one register operand.
811 assert(!RegOp &&
812 "Can't rematerialize instruction with multiple register operand!");
813 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000814#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +0000815 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000816#endif
Evan Chengd70dbb52008-02-22 09:24:50 +0000817 }
818 return RegOp;
819}
820
821/// isValNoAvailableAt - Return true if the val# of the specified interval
822/// which reaches the given instruction also reaches the specified use index.
823bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
824 unsigned UseIdx) const {
825 unsigned Index = getInstructionIndex(MI);
826 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
827 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
828 return UI != li.end() && UI->valno == ValNo;
829}
830
Evan Chengf2fbca62007-11-12 06:35:08 +0000831/// isReMaterializable - Returns true if the definition MI of the specified
832/// val# of the specified interval is re-materializable.
833bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000834 const VNInfo *ValNo, MachineInstr *MI,
Evan Chengdc377862008-09-30 15:44:16 +0000835 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000836 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000837 if (DisableReMat)
838 return false;
839
Evan Cheng20ccded2008-03-15 00:19:36 +0000840 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000841 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000842
843 int FrameIdx = 0;
844 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000845 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000846 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
847 // this but remember this is not safe to fold into a two-address
848 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000849 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000850 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000851
Dan Gohman6d69ba82008-07-25 00:02:30 +0000852 // If the target-specific rules don't identify an instruction as
853 // being trivially rematerializable, use some target-independent
854 // rules.
855 if (!MI->getDesc().isRematerializable() ||
856 !tii_->isTriviallyReMaterializable(MI)) {
Dan Gohman4c8f8702008-07-25 15:08:37 +0000857 if (!EnableAggressiveRemat)
858 return false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000859
Dan Gohman0471a792008-07-28 18:43:51 +0000860 // If the instruction accesses memory but the memoperands have been lost,
Dan Gohman6d69ba82008-07-25 00:02:30 +0000861 // we can't analyze it.
862 const TargetInstrDesc &TID = MI->getDesc();
863 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
864 return false;
865
866 // Avoid instructions obviously unsafe for remat.
867 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
868 return false;
869
870 // If the instruction accesses memory and the memory could be non-constant,
871 // assume the instruction is not rematerializable.
Evan Chengdc377862008-09-30 15:44:16 +0000872 for (std::list<MachineMemOperand>::const_iterator
873 I = MI->memoperands_begin(), E = MI->memoperands_end(); I != E; ++I){
Dan Gohman6d69ba82008-07-25 00:02:30 +0000874 const MachineMemOperand &MMO = *I;
875 if (MMO.isVolatile() || MMO.isStore())
876 return false;
877 const Value *V = MMO.getValue();
878 if (!V)
879 return false;
880 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
881 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chengd70dbb52008-02-22 09:24:50 +0000882 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000883 } else if (!aa_->pointsToConstantMemory(V))
884 return false;
885 }
886
887 // If any of the registers accessed are non-constant, conservatively assume
888 // the instruction is not rematerializable.
889 unsigned ImpUse = 0;
890 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
891 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000892 if (MO.isReg()) {
Dan Gohman6d69ba82008-07-25 00:02:30 +0000893 unsigned Reg = MO.getReg();
894 if (Reg == 0)
895 continue;
896 if (TargetRegisterInfo::isPhysicalRegister(Reg))
897 return false;
898
899 // Only allow one def, and that in the first operand.
900 if (MO.isDef() != (i == 0))
901 return false;
902
903 // Only allow constant-valued registers.
904 bool IsLiveIn = mri_->isLiveIn(Reg);
905 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
906 E = mri_->def_end();
907
908 // For the def, it should be the only def.
909 if (MO.isDef() && (next(I) != E || IsLiveIn))
910 return false;
911
912 if (MO.isUse()) {
913 // Only allow one use other register use, as that's all the
914 // remat mechanisms support currently.
915 if (Reg != li.reg) {
916 if (ImpUse == 0)
917 ImpUse = Reg;
918 else if (Reg != ImpUse)
919 return false;
920 }
921 // For uses, there should be only one associate def.
922 if (I != E && (next(I) != E || IsLiveIn))
923 return false;
924 }
Evan Chengd70dbb52008-02-22 09:24:50 +0000925 }
926 }
Evan Cheng5ef3a042007-12-06 00:01:56 +0000927 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000928
Dan Gohman6d69ba82008-07-25 00:02:30 +0000929 unsigned ImpUse = getReMatImplicitUse(li, MI);
930 if (ImpUse) {
931 const LiveInterval &ImpLi = getInterval(ImpUse);
932 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
933 re = mri_->use_end(); ri != re; ++ri) {
934 MachineInstr *UseMI = &*ri;
935 unsigned UseIdx = getInstructionIndex(UseMI);
936 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
937 continue;
938 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
939 return false;
940 }
Evan Chengdc377862008-09-30 15:44:16 +0000941
942 // If a register operand of the re-materialized instruction is going to
943 // be spilled next, then it's not legal to re-materialize this instruction.
944 for (unsigned i = 0, e = SpillIs.size(); i != e; ++i)
945 if (ImpUse == SpillIs[i]->reg)
946 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000947 }
948 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000949}
950
Evan Cheng06587492008-10-24 02:05:00 +0000951/// isReMaterializable - Returns true if the definition MI of the specified
952/// val# of the specified interval is re-materializable.
953bool LiveIntervals::isReMaterializable(const LiveInterval &li,
954 const VNInfo *ValNo, MachineInstr *MI) {
955 SmallVector<LiveInterval*, 4> Dummy1;
956 bool Dummy2;
957 return isReMaterializable(li, ValNo, MI, Dummy1, Dummy2);
958}
959
Evan Cheng5ef3a042007-12-06 00:01:56 +0000960/// isReMaterializable - Returns true if every definition of MI of every
961/// val# of the specified interval is re-materializable.
Evan Chengdc377862008-09-30 15:44:16 +0000962bool LiveIntervals::isReMaterializable(const LiveInterval &li,
963 SmallVectorImpl<LiveInterval*> &SpillIs,
964 bool &isLoad) {
Evan Cheng5ef3a042007-12-06 00:01:56 +0000965 isLoad = false;
966 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
967 i != e; ++i) {
968 const VNInfo *VNI = *i;
969 unsigned DefIdx = VNI->def;
970 if (DefIdx == ~1U)
971 continue; // Dead val#.
972 // Is the def for the val# rematerializable?
973 if (DefIdx == ~0u)
974 return false;
975 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
976 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000977 if (!ReMatDefMI ||
Evan Chengdc377862008-09-30 15:44:16 +0000978 !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +0000979 return false;
980 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +0000981 }
982 return true;
983}
984
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000985/// FilterFoldedOps - Filter out two-address use operands. Return
986/// true if it finds any issue with the operands that ought to prevent
987/// folding.
988static bool FilterFoldedOps(MachineInstr *MI,
989 SmallVector<unsigned, 2> &Ops,
990 unsigned &MRInfo,
991 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000992 const TargetInstrDesc &TID = MI->getDesc();
Evan Cheng6e141fd2007-12-12 23:12:09 +0000993
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000994 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +0000995 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
996 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +0000997 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +0000998 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +0000999 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001000 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +00001001 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +00001002 MRInfo |= (unsigned)VirtRegMap::isMod;
1003 else {
1004 // Filter out two-address use operand(s).
Evan Chengd70dbb52008-02-22 09:24:50 +00001005 if (!MO.isImplicit() &&
1006 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengaee4af62007-12-02 08:30:39 +00001007 MRInfo = VirtRegMap::isModRef;
1008 continue;
1009 }
1010 MRInfo |= (unsigned)VirtRegMap::isRef;
1011 }
1012 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +00001013 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001014 return false;
1015}
1016
1017
1018/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
1019/// slot / to reg or any rematerialized load into ith operand of specified
1020/// MI. If it is successul, MI is updated with the newly created MI and
1021/// returns true.
1022bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
1023 VirtRegMap &vrm, MachineInstr *DefMI,
1024 unsigned InstrIdx,
1025 SmallVector<unsigned, 2> &Ops,
1026 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001027 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +00001028 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001029 RemoveMachineInstrFromMaps(MI);
1030 vrm.RemoveMachineInstrFromMaps(MI);
1031 MI->eraseFromParent();
1032 ++numFolds;
1033 return true;
1034 }
1035
1036 // Filter the list of operand indexes that are to be folded. Abort if
1037 // any operand will prevent folding.
1038 unsigned MRInfo = 0;
1039 SmallVector<unsigned, 2> FoldOps;
1040 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1041 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +00001042
Evan Cheng427f4c12008-03-31 23:19:51 +00001043 // The only time it's safe to fold into a two address instruction is when
1044 // it's folding reload and spill from / into a spill stack slot.
1045 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +00001046 return false;
1047
Evan Chengf2f8c2a2008-02-08 22:05:27 +00001048 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
1049 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001050 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +00001051 // Remember this instruction uses the spill slot.
1052 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
1053
Evan Chengf2fbca62007-11-12 06:35:08 +00001054 // Attempt to fold the memory reference into the instruction. If
1055 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +00001056 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +00001057 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +00001058 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +00001059 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001060 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +00001061 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +00001062 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +00001063 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
1064 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +00001065 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001066 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +00001067 return true;
1068 }
1069 return false;
1070}
1071
Evan Cheng018f9b02007-12-05 03:22:34 +00001072/// canFoldMemoryOperand - Returns true if the specified load / store
1073/// folding is possible.
1074bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001075 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001076 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001077 // Filter the list of operand indexes that are to be folded. Abort if
1078 // any operand will prevent folding.
1079 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001080 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001081 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1082 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001083
Evan Cheng3c75ba82008-04-01 21:37:32 +00001084 // It's only legal to remat for a use, not a def.
1085 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001086 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001087
Evan Chengd70dbb52008-02-22 09:24:50 +00001088 return tii_->canFoldMemoryOperand(MI, FoldOps);
1089}
1090
Evan Cheng81a03822007-11-17 00:40:40 +00001091bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1092 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1093 for (LiveInterval::Ranges::const_iterator
1094 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1095 std::vector<IdxMBBPair>::const_iterator II =
1096 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1097 if (II == Idx2MBBMap.end())
1098 continue;
1099 if (I->end > II->first) // crossing a MBB.
1100 return false;
1101 MBBs.insert(II->second);
1102 if (MBBs.size() > 1)
1103 return false;
1104 }
1105 return true;
1106}
1107
Evan Chengd70dbb52008-02-22 09:24:50 +00001108/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1109/// interval on to-be re-materialized operands of MI) with new register.
1110void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1111 MachineInstr *MI, unsigned NewVReg,
1112 VirtRegMap &vrm) {
1113 // There is an implicit use. That means one of the other operand is
1114 // being remat'ed and the remat'ed instruction has li.reg as an
1115 // use operand. Make sure we rewrite that as well.
1116 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1117 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001118 if (!MO.isReg())
Evan Chengd70dbb52008-02-22 09:24:50 +00001119 continue;
1120 unsigned Reg = MO.getReg();
1121 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1122 continue;
1123 if (!vrm.isReMaterialized(Reg))
1124 continue;
1125 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001126 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1127 if (UseMO)
1128 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001129 }
1130}
1131
Evan Chengf2fbca62007-11-12 06:35:08 +00001132/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1133/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001134bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001135rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1136 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001137 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001138 unsigned Slot, int LdSlot,
1139 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001140 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001141 const TargetRegisterClass* rc,
1142 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001143 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001144 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Owen Anderson28998312008-08-13 22:28:50 +00001145 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001146 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
1147 MachineBasicBlock *MBB = MI->getParent();
1148 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng018f9b02007-12-05 03:22:34 +00001149 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001150 RestartInstruction:
1151 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1152 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001153 if (!mop.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001154 continue;
1155 unsigned Reg = mop.getReg();
1156 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001157 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001158 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001159 if (Reg != li.reg)
1160 continue;
1161
1162 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001163 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001164 int FoldSlot = Slot;
1165 if (DefIsReMat) {
1166 // If this is the rematerializable definition MI itself and
1167 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001168 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001169 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1170 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001171 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001172 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001173 MI->eraseFromParent();
1174 break;
1175 }
1176
1177 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001178 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001179 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001180 if (isLoad) {
1181 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1182 FoldSS = isLoadSS;
1183 FoldSlot = LdSlot;
1184 }
1185 }
1186
Evan Chengf2fbca62007-11-12 06:35:08 +00001187 // Scan all of the operands of this instruction rewriting operands
1188 // to use NewVReg instead of li.reg as appropriate. We do this for
1189 // two reasons:
1190 //
1191 // 1. If the instr reads the same spilled vreg multiple times, we
1192 // want to reuse the NewVReg.
1193 // 2. If the instr is a two-addr instruction, we are required to
1194 // keep the src/dst regs pinned.
1195 //
1196 // Keep track of whether we replace a use and/or def so that we can
1197 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001198
Evan Cheng81a03822007-11-17 00:40:40 +00001199 HasUse = mop.isUse();
1200 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001201 SmallVector<unsigned, 2> Ops;
1202 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001203 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001204 const MachineOperand &MOj = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00001205 if (!MOj.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001206 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001207 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001208 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001209 continue;
1210 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001211 Ops.push_back(j);
1212 HasUse |= MOj.isUse();
1213 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001214 }
1215 }
1216
Evan Cheng79a796c2008-07-12 01:56:02 +00001217 if (HasUse && !li.liveAt(getUseIndex(index)))
1218 // Must be defined by an implicit def. It should not be spilled. Note,
1219 // this is for correctness reason. e.g.
1220 // 8 %reg1024<def> = IMPLICIT_DEF
1221 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1222 // The live range [12, 14) are not part of the r1024 live interval since
1223 // it's defined by an implicit def. It will not conflicts with live
1224 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001225 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001226 // the INSERT_SUBREG and both target registers that would overlap.
1227 HasUse = false;
1228
Evan Cheng9c3c2212008-06-06 07:54:39 +00001229 // Update stack slot spill weight if we are splitting.
Evan Chengc3417602008-06-21 06:45:54 +00001230 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001231 if (!TrySplit)
1232 SSWeight += Weight;
1233
David Greene26b86a02008-10-27 17:38:59 +00001234 // Create a new virtual register for the spill interval.
1235 // Create the new register now so we can map the fold instruction
1236 // to the new register so when it is unfolded we get the correct
1237 // answer.
1238 bool CreatedNewVReg = false;
1239 if (NewVReg == 0) {
1240 NewVReg = mri_->createVirtualRegister(rc);
1241 vrm.grow();
1242 CreatedNewVReg = true;
1243 }
1244
Evan Cheng9c3c2212008-06-06 07:54:39 +00001245 if (!TryFold)
1246 CanFold = false;
1247 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001248 // Do not fold load / store here if we are splitting. We'll find an
1249 // optimal point to insert a load / store later.
1250 if (!TrySplit) {
1251 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
David Greene26b86a02008-10-27 17:38:59 +00001252 Ops, FoldSS, FoldSlot, NewVReg)) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001253 // Folding the load/store can completely change the instruction in
1254 // unpredictable ways, rescan it from the beginning.
David Greene26b86a02008-10-27 17:38:59 +00001255
1256 if (FoldSS) {
1257 // We need to give the new vreg the same stack slot as the
1258 // spilled interval.
1259 vrm.assignVirt2StackSlot(NewVReg, FoldSlot);
1260 }
1261
Evan Cheng018f9b02007-12-05 03:22:34 +00001262 HasUse = false;
1263 HasDef = false;
1264 CanFold = false;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001265 if (isRemoved(MI)) {
1266 SSWeight -= Weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001267 break;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001268 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001269 goto RestartInstruction;
1270 }
1271 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001272 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001273 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001274 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001275 }
Evan Chengcddbb832007-11-30 21:23:43 +00001276
Evan Chengcddbb832007-11-30 21:23:43 +00001277 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001278 if (mop.isImplicit())
1279 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001280
1281 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001282 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1283 MachineOperand &mopj = MI->getOperand(Ops[j]);
1284 mopj.setReg(NewVReg);
1285 if (mopj.isImplicit())
1286 rewriteImplicitOps(li, MI, NewVReg, vrm);
1287 }
Evan Chengcddbb832007-11-30 21:23:43 +00001288
Evan Cheng81a03822007-11-17 00:40:40 +00001289 if (CreatedNewVReg) {
1290 if (DefIsReMat) {
1291 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001292 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001293 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001294 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001295 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001296 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001297 }
1298 if (!CanDelete || (HasUse && HasDef)) {
1299 // If this is a two-addr instruction then its use operands are
1300 // rematerializable but its def is not. It should be assigned a
1301 // stack slot.
1302 vrm.assignVirt2StackSlot(NewVReg, Slot);
1303 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001304 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001305 vrm.assignVirt2StackSlot(NewVReg, Slot);
1306 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001307 } else if (HasUse && HasDef &&
1308 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1309 // If this interval hasn't been assigned a stack slot (because earlier
1310 // def is a deleted remat def), do it now.
1311 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1312 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001313 }
1314
Evan Cheng313d4b82008-02-23 00:33:04 +00001315 // Re-matting an instruction with virtual register use. Add the
1316 // register as an implicit use on the use MI.
1317 if (DefIsReMat && ImpUse)
1318 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1319
Evan Chengf2fbca62007-11-12 06:35:08 +00001320 // create a new register interval for this spill / remat.
1321 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001322 if (CreatedNewVReg) {
1323 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001324 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001325 if (TrySplit)
1326 vrm.setIsSplitFromReg(NewVReg, li.reg);
1327 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001328
1329 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001330 if (CreatedNewVReg) {
1331 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1332 nI.getNextValue(~0U, 0, VNInfoAllocator));
1333 DOUT << " +" << LR;
1334 nI.addRange(LR);
1335 } else {
1336 // Extend the split live interval to this def / use.
1337 unsigned End = getUseIndex(index)+1;
1338 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1339 nI.getValNumInfo(nI.getNumValNums()-1));
1340 DOUT << " +" << LR;
1341 nI.addRange(LR);
1342 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001343 }
1344 if (HasDef) {
1345 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1346 nI.getNextValue(~0U, 0, VNInfoAllocator));
1347 DOUT << " +" << LR;
1348 nI.addRange(LR);
1349 }
Evan Cheng81a03822007-11-17 00:40:40 +00001350
Evan Chengf2fbca62007-11-12 06:35:08 +00001351 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001352 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001353 DOUT << '\n';
1354 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001355 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001356}
Evan Cheng81a03822007-11-17 00:40:40 +00001357bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001358 const VNInfo *VNI,
1359 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001360 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001361 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1362 unsigned KillIdx = VNI->kills[j];
1363 if (KillIdx > Idx && KillIdx < End)
1364 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001365 }
1366 return false;
1367}
1368
Evan Cheng063284c2008-02-21 00:34:19 +00001369/// RewriteInfo - Keep track of machine instrs that will be rewritten
1370/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001371namespace {
1372 struct RewriteInfo {
1373 unsigned Index;
1374 MachineInstr *MI;
1375 bool HasUse;
1376 bool HasDef;
1377 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1378 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1379 };
Evan Cheng063284c2008-02-21 00:34:19 +00001380
Dan Gohman844731a2008-05-13 00:00:25 +00001381 struct RewriteInfoCompare {
1382 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1383 return LHS.Index < RHS.Index;
1384 }
1385 };
1386}
Evan Cheng063284c2008-02-21 00:34:19 +00001387
Evan Chengf2fbca62007-11-12 06:35:08 +00001388void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001389rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001390 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001391 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001392 unsigned Slot, int LdSlot,
1393 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001394 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001395 const TargetRegisterClass* rc,
1396 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001397 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001398 BitVector &SpillMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001399 DenseMap<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001400 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001401 DenseMap<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1402 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001403 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001404 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001405 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001406 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001407 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001408
Evan Cheng063284c2008-02-21 00:34:19 +00001409 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001410 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001411 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001412 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1413 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001414 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001415 MachineOperand &O = ri.getOperand();
1416 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001417 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001418 unsigned index = getInstructionIndex(MI);
1419 if (index < start || index >= end)
1420 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001421 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1422 // Must be defined by an implicit def. It should not be spilled. Note,
1423 // this is for correctness reason. e.g.
1424 // 8 %reg1024<def> = IMPLICIT_DEF
1425 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1426 // The live range [12, 14) are not part of the r1024 live interval since
1427 // it's defined by an implicit def. It will not conflicts with live
1428 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001429 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001430 // the INSERT_SUBREG and both target registers that would overlap.
1431 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001432 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1433 }
1434 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1435
Evan Cheng313d4b82008-02-23 00:33:04 +00001436 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001437 // Now rewrite the defs and uses.
1438 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1439 RewriteInfo &rwi = RewriteMIs[i];
1440 ++i;
1441 unsigned index = rwi.Index;
1442 bool MIHasUse = rwi.HasUse;
1443 bool MIHasDef = rwi.HasDef;
1444 MachineInstr *MI = rwi.MI;
1445 // If MI def and/or use the same register multiple times, then there
1446 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001447 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001448 while (i != e && RewriteMIs[i].MI == MI) {
1449 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001450 bool isUse = RewriteMIs[i].HasUse;
1451 if (isUse) ++NumUses;
1452 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001453 MIHasDef |= RewriteMIs[i].HasDef;
1454 ++i;
1455 }
Evan Cheng81a03822007-11-17 00:40:40 +00001456 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001457
Evan Cheng0a891ed2008-05-23 23:00:04 +00001458 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001459 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001460 // register interval's spill weight to HUGE_VALF to prevent it from
1461 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001462 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001463 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001464 }
1465
Evan Cheng063284c2008-02-21 00:34:19 +00001466 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001467 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001468 if (TrySplit) {
Owen Anderson28998312008-08-13 22:28:50 +00001469 DenseMap<unsigned,unsigned>::iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001470 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001471 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001472 // One common case:
1473 // x = use
1474 // ...
1475 // ...
1476 // def = ...
1477 // = use
1478 // It's better to start a new interval to avoid artifically
1479 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001480 if (MIHasDef && !MIHasUse) {
1481 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001482 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001483 }
1484 }
Evan Chengcada2452007-11-28 01:28:46 +00001485 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001486
1487 bool IsNew = ThisVReg == 0;
1488 if (IsNew) {
1489 // This ends the previous live interval. If all of its def / use
1490 // can be folded, give it a low spill weight.
1491 if (NewVReg && TrySplit && AllCanFold) {
1492 LiveInterval &nI = getOrCreateInterval(NewVReg);
1493 nI.weight /= 10.0F;
1494 }
1495 AllCanFold = true;
1496 }
1497 NewVReg = ThisVReg;
1498
Evan Cheng81a03822007-11-17 00:40:40 +00001499 bool HasDef = false;
1500 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001501 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001502 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1503 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1504 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1505 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001506 if (!HasDef && !HasUse)
1507 continue;
1508
Evan Cheng018f9b02007-12-05 03:22:34 +00001509 AllCanFold &= CanFold;
1510
Evan Cheng81a03822007-11-17 00:40:40 +00001511 // Update weight of spill interval.
1512 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001513 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001514 // The spill weight is now infinity as it cannot be spilled again.
1515 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001516 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001517 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001518
1519 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001520 if (HasDef) {
1521 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001522 bool HasKill = false;
1523 if (!HasUse)
1524 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1525 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001526 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001527 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001528 if (VNI)
1529 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1530 }
Owen Anderson28998312008-08-13 22:28:50 +00001531 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Chenge3110d02007-12-01 04:42:39 +00001532 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001533 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001534 if (SII == SpillIdxes.end()) {
1535 std::vector<SRInfo> S;
1536 S.push_back(SRInfo(index, NewVReg, true));
1537 SpillIdxes.insert(std::make_pair(MBBId, S));
1538 } else if (SII->second.back().vreg != NewVReg) {
1539 SII->second.push_back(SRInfo(index, NewVReg, true));
1540 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001541 // If there is an earlier def and this is a two-address
1542 // instruction, then it's not possible to fold the store (which
1543 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001544 SRInfo &Info = SII->second.back();
1545 Info.index = index;
1546 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001547 }
1548 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001549 } else if (SII != SpillIdxes.end() &&
1550 SII->second.back().vreg == NewVReg &&
1551 (int)index > SII->second.back().index) {
1552 // There is an earlier def that's not killed (must be two-address).
1553 // The spill is no longer needed.
1554 SII->second.pop_back();
1555 if (SII->second.empty()) {
1556 SpillIdxes.erase(MBBId);
1557 SpillMBBs.reset(MBBId);
1558 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001559 }
1560 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001561 }
1562
1563 if (HasUse) {
Owen Anderson28998312008-08-13 22:28:50 +00001564 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001565 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001566 if (SII != SpillIdxes.end() &&
1567 SII->second.back().vreg == NewVReg &&
1568 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001569 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001570 SII->second.back().canFold = false;
Owen Anderson28998312008-08-13 22:28:50 +00001571 DenseMap<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001572 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001573 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001574 // If we are splitting live intervals, only fold if it's the first
1575 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001576 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001577 else if (IsNew) {
1578 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001579 if (RII == RestoreIdxes.end()) {
1580 std::vector<SRInfo> Infos;
1581 Infos.push_back(SRInfo(index, NewVReg, true));
1582 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1583 } else {
1584 RII->second.push_back(SRInfo(index, NewVReg, true));
1585 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001586 RestoreMBBs.set(MBBId);
1587 }
1588 }
1589
1590 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001591 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001592 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001593 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001594
1595 if (NewVReg && TrySplit && AllCanFold) {
1596 // If all of its def / use can be folded, give it a low spill weight.
1597 LiveInterval &nI = getOrCreateInterval(NewVReg);
1598 nI.weight /= 10.0F;
1599 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001600}
1601
Evan Cheng1953d0c2007-11-29 10:12:14 +00001602bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1603 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001604 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001605 if (!RestoreMBBs[Id])
1606 return false;
1607 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1608 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1609 if (Restores[i].index == index &&
1610 Restores[i].vreg == vr &&
1611 Restores[i].canFold)
1612 return true;
1613 return false;
1614}
1615
1616void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1617 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001618 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001619 if (!RestoreMBBs[Id])
1620 return;
1621 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1622 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1623 if (Restores[i].index == index && Restores[i].vreg)
1624 Restores[i].index = -1;
1625}
Evan Cheng81a03822007-11-17 00:40:40 +00001626
Evan Cheng4cce6b42008-04-11 17:53:36 +00001627/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1628/// spilled and create empty intervals for their uses.
1629void
1630LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1631 const TargetRegisterClass* rc,
1632 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001633 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1634 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001635 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001636 MachineInstr *MI = &*ri;
1637 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001638 if (O.isDef()) {
1639 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1640 "Register def was not rewritten?");
1641 RemoveMachineInstrFromMaps(MI);
1642 vrm.RemoveMachineInstrFromMaps(MI);
1643 MI->eraseFromParent();
1644 } else {
1645 // This must be an use of an implicit_def so it's not part of the live
1646 // interval. Create a new empty live interval for it.
1647 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1648 unsigned NewVReg = mri_->createVirtualRegister(rc);
1649 vrm.grow();
1650 vrm.setIsImplicitlyDefined(NewVReg);
1651 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1652 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1653 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001654 if (MO.isReg() && MO.getReg() == li.reg)
Evan Cheng4cce6b42008-04-11 17:53:36 +00001655 MO.setReg(NewVReg);
1656 }
1657 }
Evan Cheng419852c2008-04-03 16:39:43 +00001658 }
1659}
1660
Owen Anderson133f10f2008-08-18 19:52:22 +00001661namespace {
1662 struct LISorter {
1663 bool operator()(LiveInterval* A, LiveInterval* B) {
1664 return A->beginNumber() < B->beginNumber();
1665 }
1666 };
1667}
Evan Cheng81a03822007-11-17 00:40:40 +00001668
Evan Chengf2fbca62007-11-12 06:35:08 +00001669std::vector<LiveInterval*> LiveIntervals::
Owen Andersond6664312008-08-18 18:05:32 +00001670addIntervalsForSpillsFast(const LiveInterval &li,
1671 const MachineLoopInfo *loopInfo,
1672 VirtRegMap &vrm, float& SSWeight) {
Owen Anderson17197312008-08-18 23:41:04 +00001673 unsigned slot = vrm.assignVirt2StackSlot(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00001674
1675 std::vector<LiveInterval*> added;
1676
1677 assert(li.weight != HUGE_VALF &&
1678 "attempt to spill already spilled interval!");
1679
1680 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
1681 DEBUG(li.dump());
1682 DOUT << '\n';
1683
1684 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
1685
Owen Anderson9a032932008-08-18 21:20:32 +00001686 SSWeight = 0.0f;
1687
Owen Andersona41e47a2008-08-19 22:12:11 +00001688 MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg);
1689 while (RI != mri_->reg_end()) {
1690 MachineInstr* MI = &*RI;
1691
1692 SmallVector<unsigned, 2> Indices;
1693 bool HasUse = false;
1694 bool HasDef = false;
1695
1696 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1697 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001698 if (!mop.isReg() || mop.getReg() != li.reg) continue;
Owen Andersona41e47a2008-08-19 22:12:11 +00001699
1700 HasUse |= MI->getOperand(i).isUse();
1701 HasDef |= MI->getOperand(i).isDef();
1702
1703 Indices.push_back(i);
1704 }
1705
1706 if (!tryFoldMemoryOperand(MI, vrm, NULL, getInstructionIndex(MI),
1707 Indices, true, slot, li.reg)) {
1708 unsigned NewVReg = mri_->createVirtualRegister(rc);
Owen Anderson9a032932008-08-18 21:20:32 +00001709 vrm.grow();
Owen Anderson17197312008-08-18 23:41:04 +00001710 vrm.assignVirt2StackSlot(NewVReg, slot);
1711
Owen Andersona41e47a2008-08-19 22:12:11 +00001712 // create a new register for this spill
1713 LiveInterval &nI = getOrCreateInterval(NewVReg);
Owen Andersond6664312008-08-18 18:05:32 +00001714
Owen Andersona41e47a2008-08-19 22:12:11 +00001715 // the spill weight is now infinity as it
1716 // cannot be spilled again
1717 nI.weight = HUGE_VALF;
1718
1719 // Rewrite register operands to use the new vreg.
1720 for (SmallVectorImpl<unsigned>::iterator I = Indices.begin(),
1721 E = Indices.end(); I != E; ++I) {
1722 MI->getOperand(*I).setReg(NewVReg);
1723
1724 if (MI->getOperand(*I).isUse())
1725 MI->getOperand(*I).setIsKill(true);
1726 }
1727
1728 // Fill in the new live interval.
1729 unsigned index = getInstructionIndex(MI);
1730 if (HasUse) {
1731 LiveRange LR(getLoadIndex(index), getUseIndex(index),
1732 nI.getNextValue(~0U, 0, getVNInfoAllocator()));
1733 DOUT << " +" << LR;
1734 nI.addRange(LR);
1735 vrm.addRestorePoint(NewVReg, MI);
1736 }
1737 if (HasDef) {
1738 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1739 nI.getNextValue(~0U, 0, getVNInfoAllocator()));
1740 DOUT << " +" << LR;
1741 nI.addRange(LR);
1742 vrm.addSpillPoint(NewVReg, true, MI);
1743 }
1744
Owen Anderson17197312008-08-18 23:41:04 +00001745 added.push_back(&nI);
Owen Anderson8dc2cbe2008-08-18 18:38:12 +00001746
Owen Andersona41e47a2008-08-19 22:12:11 +00001747 DOUT << "\t\t\t\tadded new interval: ";
1748 DEBUG(nI.dump());
1749 DOUT << '\n';
1750
1751 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
1752 if (HasUse) {
1753 if (HasDef)
1754 SSWeight += getSpillWeight(true, true, loopDepth);
1755 else
1756 SSWeight += getSpillWeight(false, true, loopDepth);
1757 } else
1758 SSWeight += getSpillWeight(true, false, loopDepth);
1759 }
Owen Anderson9a032932008-08-18 21:20:32 +00001760
Owen Anderson9a032932008-08-18 21:20:32 +00001761
Owen Andersona41e47a2008-08-19 22:12:11 +00001762 RI = mri_->reg_begin(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00001763 }
Owen Andersond6664312008-08-18 18:05:32 +00001764
Owen Andersona41e47a2008-08-19 22:12:11 +00001765 // Clients expect the new intervals to be returned in sorted order.
Owen Anderson133f10f2008-08-18 19:52:22 +00001766 std::sort(added.begin(), added.end(), LISorter());
1767
Owen Andersond6664312008-08-18 18:05:32 +00001768 return added;
1769}
1770
1771std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001772addIntervalsForSpills(const LiveInterval &li,
Evan Chengdc377862008-09-30 15:44:16 +00001773 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001774 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1775 float &SSWeight) {
Owen Andersonae339ba2008-08-19 00:17:30 +00001776
1777 if (EnableFastSpilling)
1778 return addIntervalsForSpillsFast(li, loopInfo, vrm, SSWeight);
1779
Evan Chengf2fbca62007-11-12 06:35:08 +00001780 assert(li.weight != HUGE_VALF &&
1781 "attempt to spill already spilled interval!");
1782
1783 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001784 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001785 DOUT << '\n';
1786
Evan Cheng9c3c2212008-06-06 07:54:39 +00001787 // Spill slot weight.
1788 SSWeight = 0.0f;
1789
Evan Cheng81a03822007-11-17 00:40:40 +00001790 // Each bit specify whether it a spill is required in the MBB.
1791 BitVector SpillMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00001792 DenseMap<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001793 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00001794 DenseMap<unsigned, std::vector<SRInfo> > RestoreIdxes;
1795 DenseMap<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001796 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001797 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001798
1799 unsigned NumValNums = li.getNumValNums();
1800 SmallVector<MachineInstr*, 4> ReMatDefs;
1801 ReMatDefs.resize(NumValNums, NULL);
1802 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1803 ReMatOrigDefs.resize(NumValNums, NULL);
1804 SmallVector<int, 4> ReMatIds;
1805 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1806 BitVector ReMatDelete(NumValNums);
1807 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1808
Evan Cheng81a03822007-11-17 00:40:40 +00001809 // Spilling a split live interval. It cannot be split any further. Also,
1810 // it's also guaranteed to be a single val# / range interval.
1811 if (vrm.getPreSplitReg(li.reg)) {
1812 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001813 // Unset the split kill marker on the last use.
1814 unsigned KillIdx = vrm.getKillPoint(li.reg);
1815 if (KillIdx) {
1816 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1817 assert(KillMI && "Last use disappeared?");
1818 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1819 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001820 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001821 }
Evan Chengadf85902007-12-05 09:51:10 +00001822 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001823 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1824 Slot = vrm.getStackSlot(li.reg);
1825 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1826 MachineInstr *ReMatDefMI = DefIsReMat ?
1827 vrm.getReMaterializedMI(li.reg) : NULL;
1828 int LdSlot = 0;
1829 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1830 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001831 (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001832 bool IsFirstRange = true;
1833 for (LiveInterval::Ranges::const_iterator
1834 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1835 // If this is a split live interval with multiple ranges, it means there
1836 // are two-address instructions that re-defined the value. Only the
1837 // first def can be rematerialized!
1838 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001839 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001840 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1841 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001842 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001843 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001844 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001845 } else {
1846 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1847 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001848 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001849 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001850 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001851 }
1852 IsFirstRange = false;
1853 }
Evan Cheng419852c2008-04-03 16:39:43 +00001854
Evan Cheng9c3c2212008-06-06 07:54:39 +00001855 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng4cce6b42008-04-11 17:53:36 +00001856 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001857 return NewLIs;
1858 }
1859
1860 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001861 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1862 TrySplit = false;
1863 if (TrySplit)
1864 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001865 bool NeedStackSlot = false;
1866 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1867 i != e; ++i) {
1868 const VNInfo *VNI = *i;
1869 unsigned VN = VNI->id;
1870 unsigned DefIdx = VNI->def;
1871 if (DefIdx == ~1U)
1872 continue; // Dead val#.
1873 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001874 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1875 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001876 bool dummy;
Evan Chengdc377862008-09-30 15:44:16 +00001877 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, SpillIs, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001878 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001879 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001880 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001881 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1882 ClonedMIs.push_back(Clone);
1883 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001884
1885 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001886 if (VNI->hasPHIKill) {
1887 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001888 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001889 CanDelete = false;
1890 // Need a stack slot if there is any live range where uses cannot be
1891 // rematerialized.
1892 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001893 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001894 if (CanDelete)
1895 ReMatDelete.set(VN);
1896 } else {
1897 // Need a stack slot if there is any live range where uses cannot be
1898 // rematerialized.
1899 NeedStackSlot = true;
1900 }
1901 }
1902
1903 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001904 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001905 Slot = vrm.assignVirt2StackSlot(li.reg);
1906
1907 // Create new intervals and rewrite defs and uses.
1908 for (LiveInterval::Ranges::const_iterator
1909 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001910 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1911 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1912 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001913 bool CanDelete = ReMatDelete[I->valno->id];
1914 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001915 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001916 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001917 (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001918 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001919 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001920 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001921 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001922 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengf2fbca62007-11-12 06:35:08 +00001923 }
1924
Evan Cheng0cbb1162007-11-29 01:06:25 +00001925 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001926 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001927 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001928 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00001929 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001930
Evan Chengb50bb8c2007-12-05 08:16:32 +00001931 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001932 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001933 if (NeedStackSlot) {
1934 int Id = SpillMBBs.find_first();
1935 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001936 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1937 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001938 std::vector<SRInfo> &spills = SpillIdxes[Id];
1939 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1940 int index = spills[i].index;
1941 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001942 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001943 bool isReMat = vrm.isReMaterialized(VReg);
1944 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001945 bool CanFold = false;
1946 bool FoundUse = false;
1947 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001948 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001949 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001950 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1951 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00001952 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001953 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001954
1955 Ops.push_back(j);
1956 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001957 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001958 if (isReMat ||
1959 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1960 RestoreMBBs, RestoreIdxes))) {
1961 // MI has two-address uses of the same register. If the use
1962 // isn't the first and only use in the BB, then we can't fold
1963 // it. FIXME: Move this to rewriteInstructionsForSpills.
1964 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001965 break;
1966 }
Evan Chengaee4af62007-12-02 08:30:39 +00001967 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001968 }
1969 }
1970 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001971 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001972 if (CanFold && !Ops.empty()) {
1973 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001974 Folded = true;
Evan Chengf38d14f2007-12-05 09:05:34 +00001975 if (FoundUse > 0) {
Evan Chengaee4af62007-12-02 08:30:39 +00001976 // Also folded uses, do not issue a load.
1977 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00001978 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
1979 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001980 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00001981 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001982 }
1983
Evan Cheng7e073ba2008-04-09 20:57:25 +00001984 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00001985 if (!Folded) {
1986 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
1987 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00001988 if (!MI->registerDefIsDead(nI.reg))
1989 // No need to spill a dead def.
1990 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001991 if (isKill)
1992 AddedKill.insert(&nI);
1993 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001994
1995 // Update spill slot weight.
1996 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001997 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001998 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001999 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002000 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002001 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002002
Evan Cheng1953d0c2007-11-29 10:12:14 +00002003 int Id = RestoreMBBs.find_first();
2004 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00002005 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
2006 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
2007
Evan Cheng1953d0c2007-11-29 10:12:14 +00002008 std::vector<SRInfo> &restores = RestoreIdxes[Id];
2009 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
2010 int index = restores[i].index;
2011 if (index == -1)
2012 continue;
2013 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00002014 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00002015 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00002016 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00002017 bool CanFold = false;
2018 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00002019 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00002020 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00002021 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
2022 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00002023 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng81a03822007-11-17 00:40:40 +00002024 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002025
Evan Cheng0cbb1162007-11-29 01:06:25 +00002026 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00002027 // If this restore were to be folded, it would have been folded
2028 // already.
2029 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00002030 break;
2031 }
Evan Chengaee4af62007-12-02 08:30:39 +00002032 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00002033 }
2034 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002035
2036 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00002037 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00002038 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00002039 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00002040 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
2041 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00002042 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
2043 int LdSlot = 0;
2044 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
2045 // If the rematerializable def is a load, also try to fold it.
Chris Lattner749c6f62008-01-07 07:27:27 +00002046 if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00002047 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
2048 Ops, isLoadSS, LdSlot, VReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00002049 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
2050 if (ImpUse) {
2051 // Re-matting an instruction with virtual register use. Add the
2052 // register as an implicit use on the use MI and update the register
Evan Cheng24d2f8a2008-03-31 07:53:30 +00002053 // interval's spill weight to HUGE_VALF to prevent it from being
2054 // spilled.
Evan Chengd70dbb52008-02-22 09:24:50 +00002055 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00002056 ImpLi.weight = HUGE_VALF;
Evan Chengd70dbb52008-02-22 09:24:50 +00002057 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
2058 }
Evan Chengaee4af62007-12-02 08:30:39 +00002059 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002060 }
2061 // If folding is not possible / failed, then tell the spiller to issue a
2062 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00002063 if (Folded)
2064 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002065 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00002066 vrm.addRestorePoint(VReg, MI);
Evan Cheng9c3c2212008-06-06 07:54:39 +00002067
2068 // Update spill slot weight.
2069 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00002070 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Cheng81a03822007-11-17 00:40:40 +00002071 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002072 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00002073 }
2074
Evan Chengb50bb8c2007-12-05 08:16:32 +00002075 // Finalize intervals: add kills, finalize spill weights, and filter out
2076 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00002077 std::vector<LiveInterval*> RetNewLIs;
2078 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
2079 LiveInterval *LI = NewLIs[i];
2080 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00002081 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002082 if (!AddedKill.count(LI)) {
2083 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00002084 unsigned LastUseIdx = getBaseIndex(LR->end);
2085 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00002086 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002087 assert(UseIdx != -1);
Evan Chengd70dbb52008-02-22 09:24:50 +00002088 if (LastUse->getOperand(UseIdx).isImplicit() ||
2089 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chengb50bb8c2007-12-05 08:16:32 +00002090 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00002091 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00002092 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00002093 }
Evan Cheng597d10d2007-12-04 00:32:23 +00002094 RetNewLIs.push_back(LI);
2095 }
2096 }
Evan Cheng81a03822007-11-17 00:40:40 +00002097
Evan Cheng4cce6b42008-04-11 17:53:36 +00002098 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00002099 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00002100}
Evan Cheng676dd7c2008-03-11 07:19:34 +00002101
2102/// hasAllocatableSuperReg - Return true if the specified physical register has
2103/// any super register that's allocatable.
2104bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
2105 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
2106 if (allocatableRegs_[*AS] && hasInterval(*AS))
2107 return true;
2108 return false;
2109}
2110
2111/// getRepresentativeReg - Find the largest super register of the specified
2112/// physical register.
2113unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
2114 // Find the largest super-register that is allocatable.
2115 unsigned BestReg = Reg;
2116 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
2117 unsigned SuperReg = *AS;
2118 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
2119 BestReg = SuperReg;
2120 break;
2121 }
2122 }
2123 return BestReg;
2124}
2125
2126/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
2127/// specified interval that conflicts with the specified physical register.
2128unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
2129 unsigned PhysReg) const {
2130 unsigned NumConflicts = 0;
2131 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
2132 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2133 E = mri_->reg_end(); I != E; ++I) {
2134 MachineOperand &O = I.getOperand();
2135 MachineInstr *MI = O.getParent();
2136 unsigned Index = getInstructionIndex(MI);
2137 if (pli.liveAt(Index))
2138 ++NumConflicts;
2139 }
2140 return NumConflicts;
2141}
2142
2143/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
2144/// around all defs and uses of the specified interval.
2145void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
2146 unsigned PhysReg, VirtRegMap &vrm) {
2147 unsigned SpillReg = getRepresentativeReg(PhysReg);
2148
2149 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
2150 // If there are registers which alias PhysReg, but which are not a
2151 // sub-register of the chosen representative super register. Assert
2152 // since we can't handle it yet.
2153 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
2154 tri_->isSuperRegister(*AS, SpillReg));
2155
2156 LiveInterval &pli = getInterval(SpillReg);
2157 SmallPtrSet<MachineInstr*, 8> SeenMIs;
2158 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2159 E = mri_->reg_end(); I != E; ++I) {
2160 MachineOperand &O = I.getOperand();
2161 MachineInstr *MI = O.getParent();
2162 if (SeenMIs.count(MI))
2163 continue;
2164 SeenMIs.insert(MI);
2165 unsigned Index = getInstructionIndex(MI);
2166 if (pli.liveAt(Index)) {
2167 vrm.addEmergencySpill(SpillReg, MI);
2168 pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
2169 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
2170 if (!hasInterval(*AS))
2171 continue;
2172 LiveInterval &spli = getInterval(*AS);
2173 if (spli.liveAt(Index))
2174 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
2175 }
2176 }
2177 }
2178}
Owen Andersonc4dc1322008-06-05 17:15:43 +00002179
2180LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
2181 MachineInstr* startInst) {
2182 LiveInterval& Interval = getOrCreateInterval(reg);
2183 VNInfo* VN = Interval.getNextValue(
2184 getInstructionIndex(startInst) + InstrSlots::DEF,
2185 startInst, getVNInfoAllocator());
2186 VN->hasPHIKill = true;
2187 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
2188 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
2189 getMBBEndIdx(startInst->getParent()) + 1, VN);
2190 Interval.addRange(LR);
2191
2192 return LR;
2193}