blob: 8e8e8ff6d0cade934c62d9b31cc73b2858aa1b21 [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");
Evan Cheng0cbb1162007-11-29 01:06:25 +000057STATISTIC(numFolds , "Number of loads/stores folded into instructions");
58STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000059
Devang Patel19974732007-05-03 01:11:54 +000060char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000061static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000062
Chris Lattnerf7da2c72006-08-24 22:43:55 +000063void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman6d69ba82008-07-25 00:02:30 +000064 AU.addRequired<AliasAnalysis>();
65 AU.addPreserved<AliasAnalysis>();
David Greene25133302007-06-08 17:18:56 +000066 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000067 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000068 AU.addPreservedID(MachineLoopInfoID);
69 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +000070
71 if (!StrongPHIElim) {
72 AU.addPreservedID(PHIEliminationID);
73 AU.addRequiredID(PHIEliminationID);
74 }
75
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000077 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000078}
79
Chris Lattnerf7da2c72006-08-24 22:43:55 +000080void LiveIntervals::releaseMemory() {
Owen Anderson03857b22008-08-13 21:49:13 +000081 // Free the live intervals themselves.
Owen Anderson20e28392008-08-13 22:08:30 +000082 for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
Owen Anderson03857b22008-08-13 21:49:13 +000083 E = r2iMap_.end(); I != E; ++I)
84 delete I->second;
85
Evan Cheng3f32d652008-06-04 09:18:41 +000086 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000087 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000088 mi2iMap_.clear();
89 i2miMap_.clear();
90 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000091 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
92 VNInfoAllocator.Reset();
Evan Cheng1ed99222008-07-19 00:37:25 +000093 while (!ClonedMIs.empty()) {
94 MachineInstr *MI = ClonedMIs.back();
95 ClonedMIs.pop_back();
96 mf_->DeleteMachineInstr(MI);
97 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000098}
99
Owen Anderson80b3ce62008-05-28 20:54:50 +0000100void LiveIntervals::computeNumbering() {
101 Index2MiMap OldI2MI = i2miMap_;
Owen Anderson7fbad272008-07-23 21:37:49 +0000102 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Anderson80b3ce62008-05-28 20:54:50 +0000103
104 Idx2MBBMap.clear();
105 MBB2IdxMap.clear();
106 mi2iMap_.clear();
107 i2miMap_.clear();
108
Owen Andersona1566f22008-07-22 22:46:49 +0000109 FunctionSize = 0;
110
Chris Lattner428b92e2006-09-15 03:57:23 +0000111 // Number MachineInstrs and MachineBasicBlocks.
112 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +0000113 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +0000114
115 unsigned MIIndex = 0;
116 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
117 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000118 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000119
Owen Anderson7fbad272008-07-23 21:37:49 +0000120 // Insert an empty slot at the beginning of each block.
121 MIIndex += InstrSlots::NUM;
122 i2miMap_.push_back(0);
123
Chris Lattner428b92e2006-09-15 03:57:23 +0000124 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
125 I != E; ++I) {
126 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000127 assert(inserted && "multiple MachineInstr -> index mappings");
Devang Patel59500c82008-11-21 20:00:59 +0000128 inserted = true;
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
Chris Lattner70ca3582004-09-30 15:59:17 +0000263 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000264 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000265}
266
Chris Lattner70ca3582004-09-30 15:59:17 +0000267/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000268void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000269 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000270 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Owen Anderson03857b22008-08-13 21:49:13 +0000271 I->second->print(O, tri_);
Evan Cheng3f32d652008-06-04 09:18:41 +0000272 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000273 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000274
275 O << "********** MACHINEINSTRS **********\n";
276 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
277 mbbi != mbbe; ++mbbi) {
278 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
279 for (MachineBasicBlock::iterator mii = mbbi->begin(),
280 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000281 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000282 }
283 }
284}
285
Evan Chengc92da382007-11-03 07:20:12 +0000286/// conflictsWithPhysRegDef - Returns true if the specified register
287/// is defined during the duration of the specified interval.
288bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
289 VirtRegMap &vrm, unsigned reg) {
290 for (LiveInterval::Ranges::const_iterator
291 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
292 for (unsigned index = getBaseIndex(I->start),
293 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
294 index += InstrSlots::NUM) {
295 // skip deleted instructions
296 while (index != end && !getInstructionFromIndex(index))
297 index += InstrSlots::NUM;
298 if (index == end) break;
299
300 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000301 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
302 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng5d446262007-11-15 08:13:29 +0000303 if (SrcReg == li.reg || DstReg == li.reg)
304 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000305 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
306 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000307 if (!mop.isReg())
Evan Chengc92da382007-11-03 07:20:12 +0000308 continue;
309 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000310 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000311 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000312 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000313 if (!vrm.hasPhys(PhysReg))
314 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000315 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000316 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000317 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000318 return true;
319 }
320 }
321 }
322
323 return false;
324}
325
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000326/// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
327/// it can check use as well.
328bool LiveIntervals::conflictsWithPhysRegRef(LiveInterval &li,
329 unsigned Reg, bool CheckUse,
330 SmallPtrSet<MachineInstr*,32> &JoinedCopies) {
331 for (LiveInterval::Ranges::const_iterator
332 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
333 for (unsigned index = getBaseIndex(I->start),
334 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
335 index += InstrSlots::NUM) {
336 // Skip deleted instructions.
337 MachineInstr *MI = 0;
338 while (index != end) {
339 MI = getInstructionFromIndex(index);
340 if (MI)
341 break;
342 index += InstrSlots::NUM;
343 }
344 if (index == end) break;
345
346 if (JoinedCopies.count(MI))
347 continue;
348 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
349 MachineOperand& MO = MI->getOperand(i);
350 if (!MO.isReg())
351 continue;
352 if (MO.isUse() && !CheckUse)
353 continue;
354 unsigned PhysReg = MO.getReg();
355 if (PhysReg == 0 || TargetRegisterInfo::isVirtualRegister(PhysReg))
356 continue;
357 if (tri_->isSubRegister(Reg, PhysReg))
358 return true;
359 }
360 }
361 }
362
363 return false;
364}
365
366
Evan Cheng549f27d32007-08-13 23:45:17 +0000367void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000368 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000369 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000370 else
371 cerr << "%reg" << reg;
372}
373
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000374void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000375 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000376 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000377 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000378 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000379 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000380 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000381
Evan Cheng419852c2008-04-03 16:39:43 +0000382 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
383 DOUT << "is a implicit_def\n";
384 return;
385 }
386
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000387 // Virtual registers may be defined multiple times (due to phi
388 // elimination and 2-addr elimination). Much of what we do only has to be
389 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000390 // time we see a vreg.
391 if (interval.empty()) {
392 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000393 unsigned defIndex = getDefIndex(MIIdx);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000394 // Earlyclobbers move back one.
395 if (MO.isEarlyClobber())
396 defIndex = getUseIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000397 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000398 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000399 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000400 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000401 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000402 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000403 CopyMI = mi;
Evan Cheng5379f412008-12-19 20:58:01 +0000404 // Earlyclobbers move back one.
Evan Chengc8d044e2008-02-15 18:24:29 +0000405 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000406
407 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000408
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000409 // Loop over all of the blocks that the vreg is defined in. There are
410 // two cases we have to handle here. The most common case is a vreg
411 // whose lifetime is contained within a basic block. In this case there
412 // will be a single kill, in MBB, which comes after the definition.
413 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
414 // FIXME: what about dead vars?
415 unsigned killIdx;
416 if (vi.Kills[0] != mi)
417 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
418 else
419 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000420
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000421 // If the kill happens after the definition, we have an intra-block
422 // live range.
423 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000424 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000425 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000426 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000427 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000428 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000429 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000430 return;
431 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000432 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000433
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000434 // The other case we handle is when a virtual register lives to the end
435 // of the defining block, potentially live across some blocks, then is
436 // live into some number of blocks, but gets killed. Start by adding a
437 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000438 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000439 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000440 interval.addRange(NewLR);
441
442 // Iterate over all of the blocks that the variable is completely
443 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
444 // live interval.
Dan Gohman4a829ec2008-11-13 16:31:27 +0000445 for (int i = vi.AliveBlocks.find_first(); i != -1;
446 i = vi.AliveBlocks.find_next(i)) {
447 LiveRange LR(getMBBStartIdx(i),
448 getMBBEndIdx(i)+1, // MBB ends at -1.
449 ValNo);
450 interval.addRange(LR);
451 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000452 }
453
454 // Finally, this virtual register is live from the start of any killing
455 // block to the 'use' slot of the killing instruction.
456 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
457 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000458 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000459 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000460 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000461 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000462 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000463 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000464 }
465
466 } else {
467 // If this is the second time we see a virtual register definition, it
468 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000469 // the result of two address elimination, then the vreg is one of the
470 // def-and-use register operand.
Dan Gohman2ce7f202008-12-05 05:45:42 +0000471 if (mi->isRegReDefinedByTwoAddr(MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000472 // If this is a two-address definition, then we have already processed
473 // the live range. The only problem is that we didn't realize there
474 // are actually two values in the live interval. Because of this we
475 // need to take the LiveRegion that defines this register and split it
476 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000477 assert(interval.containsOneValue());
478 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000479 unsigned RedefIndex = getDefIndex(MIIdx);
Evan Cheng5379f412008-12-19 20:58:01 +0000480 // It cannot be an early clobber MO.
481 assert(!MO.isEarlyClobber() && "Unexpected early clobber!");
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000482
Evan Cheng4f8ff162007-08-11 00:59:19 +0000483 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000484 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000485
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000486 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000487 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000488 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000489
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000490 // Two-address vregs should always only be redefined once. This means
491 // that at this point, there should be exactly one value number in it.
492 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
493
Chris Lattner91725b72006-08-31 05:54:43 +0000494 // The new value number (#1) is defined by the instruction we claimed
495 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000496 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
497 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000498
Chris Lattner91725b72006-08-31 05:54:43 +0000499 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000500 OldValNo->def = RedefIndex;
501 OldValNo->copy = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000502
503 // Add the new live interval which replaces the range for the input copy.
504 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000505 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000506 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000507 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000508
509 // If this redefinition is dead, we need to add a dummy unit live
510 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000511 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000512 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000513
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000514 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000515 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000516
517 } else {
518 // Otherwise, this must be because of phi elimination. If this is the
519 // first redefinition of the vreg that we have seen, go back and change
520 // the live range in the PHI block to be a different value number.
521 if (interval.containsOneValue()) {
522 assert(vi.Kills.size() == 1 &&
523 "PHI elimination vreg should have one kill, the PHI itself!");
524
525 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000526 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000527 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000528 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000529 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000530 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000531 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000532 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000533 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000534 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000535
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000536 // Replace the interval with one of a NEW value number. Note that this
537 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000538 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000539 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000540 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000541 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000542 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000543 }
544
545 // In the case of PHI elimination, each variable definition is only
546 // live until the end of the block. We've already taken care of the
547 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000548 unsigned defIndex = getDefIndex(MIIdx);
Evan Cheng5379f412008-12-19 20:58:01 +0000549 // It cannot be an early clobber MO.
550 assert(!MO.isEarlyClobber() && "Unexpected early clobber!");
Chris Lattner91725b72006-08-31 05:54:43 +0000551
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000552 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000553 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000554 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000555 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000556 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000557 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000558 CopyMI = mi;
559 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000560
Owen Anderson7fbad272008-07-23 21:37:49 +0000561 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000562 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000563 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000564 interval.addKill(ValNo, killIndex);
565 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000566 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000567 }
568 }
569
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000570 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000571}
572
Chris Lattnerf35fef72004-07-23 21:24:19 +0000573void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000574 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000575 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000576 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000577 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000578 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000579 // A physical register cannot be live across basic block, so its
580 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000581 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000582
Chris Lattner6b128bd2006-09-03 08:07:11 +0000583 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000584 unsigned start = getDefIndex(baseIndex);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000585 // Earlyclobbers move back one.
586 if (MO.isEarlyClobber())
587 start = getUseIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000588 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000589
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000590 // If it is not used after definition, it is considered dead at
591 // the instruction defining it. Hence its interval is:
592 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000593 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000594 DOUT << " dead";
Dale Johannesen86b49f82008-09-24 01:07:17 +0000595 end = start + 1;
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000596 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000597 }
598
599 // If it is not dead on definition, it must be killed by a
600 // subsequent instruction. Hence its interval is:
601 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000602 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000603 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000604 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
605 getInstructionFromIndex(baseIndex) == 0)
606 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000607 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000608 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000609 end = getUseIndex(baseIndex) + 1;
610 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000611 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000612 // Another instruction redefines the register before it is ever read.
613 // Then the register is essentially dead at the instruction that defines
614 // it. Hence its interval is:
615 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000616 DOUT << " dead";
Dale Johannesen86b49f82008-09-24 01:07:17 +0000617 end = start + 1;
Evan Cheng9a1956a2006-11-15 20:54:11 +0000618 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000619 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000620
621 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000622 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000623
624 // The only case we should have a dead physreg here without a killing or
625 // instruction where we know it's dead is if it is live-in to the function
626 // and never used.
Evan Chengc8d044e2008-02-15 18:24:29 +0000627 assert(!CopyMI && "physreg was not killed in defining block!");
Dale Johannesen86b49f82008-09-24 01:07:17 +0000628 end = start + 1;
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000629
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000630exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000631 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000632
Evan Cheng24a3cc42007-04-25 07:30:23 +0000633 // Already exists? Extend old live interval.
634 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng5379f412008-12-19 20:58:01 +0000635 bool Extend = OldLR != interval.end();
636 VNInfo *ValNo = Extend
Evan Chengc8d044e2008-02-15 18:24:29 +0000637 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng5379f412008-12-19 20:58:01 +0000638 if (MO.isEarlyClobber() && Extend)
639 ValNo->redefByEC = true;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000640 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000641 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000642 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000643 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000644}
645
Chris Lattnerf35fef72004-07-23 21:24:19 +0000646void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
647 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000648 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000649 MachineOperand& MO,
650 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000651 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000652 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000653 getOrCreateInterval(MO.getReg()));
654 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000655 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000656 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000657 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000658 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000659 tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000660 CopyMI = MI;
Owen Anderson6b098de2008-06-25 23:39:39 +0000661 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
662 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000663 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000664 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000665 // If MI also modifies the sub-register explicitly, avoid processing it
666 // more than once. Do not pass in TRI here so it checks for exact match.
667 if (!MI->modifiesRegister(*AS))
Owen Anderson6b098de2008-06-25 23:39:39 +0000668 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
669 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000670 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000671}
672
Evan Chengb371f452007-02-19 21:49:54 +0000673void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000674 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000675 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000676 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
677
678 // Look for kills, if it reaches a def before it's killed, then it shouldn't
679 // be considered a livein.
680 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000681 unsigned baseIndex = MIIdx;
682 unsigned start = baseIndex;
Owen Anderson99500ae2008-09-15 22:00:38 +0000683 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
684 getInstructionFromIndex(baseIndex) == 0)
685 baseIndex += InstrSlots::NUM;
686 unsigned end = baseIndex;
687
Evan Chengb371f452007-02-19 21:49:54 +0000688 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000689 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000690 DOUT << " killed";
691 end = getUseIndex(baseIndex) + 1;
692 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000693 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000694 // Another instruction redefines the register before it is ever read.
695 // Then the register is essentially dead at the instruction that defines
696 // it. Hence its interval is:
697 // [defSlot(def), defSlot(def)+1)
698 DOUT << " dead";
699 end = getDefIndex(start) + 1;
700 goto exit;
701 }
702
703 baseIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000704 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
705 getInstructionFromIndex(baseIndex) == 0)
706 baseIndex += InstrSlots::NUM;
Evan Chengb371f452007-02-19 21:49:54 +0000707 ++mi;
708 }
709
710exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000711 // Live-in register might not be used at all.
712 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000713 if (isAlias) {
714 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000715 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000716 } else {
717 DOUT << " live through";
718 end = baseIndex;
719 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000720 }
721
Owen Anderson99500ae2008-09-15 22:00:38 +0000722 LiveRange LR(start, end, interval.getNextValue(~0U, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000723 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000724 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000725 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000726}
727
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000728/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000729/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000730/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000731/// which a variable is live
Dale Johannesen91aac102008-09-17 21:13:11 +0000732void LiveIntervals::computeIntervals() {
Dale Johannesen91aac102008-09-17 21:13:11 +0000733
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000734 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
735 << "********** Function: "
736 << ((Value*)mf_->getFunction())->getName() << '\n';
Owen Anderson7fbad272008-07-23 21:37:49 +0000737
Chris Lattner428b92e2006-09-15 03:57:23 +0000738 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
739 MBBI != E; ++MBBI) {
740 MachineBasicBlock *MBB = MBBI;
Owen Anderson134eb732008-09-21 20:43:24 +0000741 // Track the index of the current machine instr.
742 unsigned MIIndex = getMBBStartIdx(MBB);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000743 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000744
Chris Lattner428b92e2006-09-15 03:57:23 +0000745 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000746
Dan Gohmancb406c22007-10-03 19:26:29 +0000747 // Create intervals for live-ins to this BB first.
748 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
749 LE = MBB->livein_end(); LI != LE; ++LI) {
750 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
751 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000752 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000753 if (!hasInterval(*AS))
754 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
755 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000756 }
757
Owen Anderson99500ae2008-09-15 22:00:38 +0000758 // Skip over empty initial indices.
759 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
760 getInstructionFromIndex(MIIndex) == 0)
761 MIIndex += InstrSlots::NUM;
762
Chris Lattner428b92e2006-09-15 03:57:23 +0000763 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000764 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000765
Evan Cheng438f7bc2006-11-10 08:43:01 +0000766 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000767 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
768 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000769 // handle register defs - build intervals
Dan Gohmand735b802008-10-03 15:45:36 +0000770 if (MO.isReg() && MO.getReg() && MO.isDef()) {
Evan Chengef0732d2008-07-10 07:35:43 +0000771 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Dale Johannesen91aac102008-09-17 21:13:11 +0000772 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000773 }
Evan Cheng99fe34b2008-10-18 05:18:55 +0000774
775 // Skip over the empty slots after each instruction.
776 unsigned Slots = MI->getDesc().getNumDefs();
777 if (Slots == 0)
778 Slots = 1;
779 MIIndex += InstrSlots::NUM * Slots;
Owen Anderson7fbad272008-07-23 21:37:49 +0000780
781 // Skip over empty indices.
782 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
783 getInstructionFromIndex(MIIndex) == 0)
784 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000785 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000786 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000787}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000788
Evan Chengd0e32c52008-10-29 05:06:14 +0000789bool LiveIntervals::findLiveInMBBs(unsigned Start, unsigned End,
Evan Chenga5bfc972007-10-17 06:53:44 +0000790 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000791 std::vector<IdxMBBPair>::const_iterator I =
Evan Chengd0e32c52008-10-29 05:06:14 +0000792 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start);
Evan Cheng4ca980e2007-10-17 02:10:22 +0000793
794 bool ResVal = false;
795 while (I != Idx2MBBMap.end()) {
Dan Gohman2ad82452008-11-26 05:50:31 +0000796 if (I->first >= End)
Evan Cheng4ca980e2007-10-17 02:10:22 +0000797 break;
798 MBBs.push_back(I->second);
799 ResVal = true;
800 ++I;
801 }
802 return ResVal;
803}
804
Evan Chengd0e32c52008-10-29 05:06:14 +0000805bool LiveIntervals::findReachableMBBs(unsigned Start, unsigned End,
806 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
807 std::vector<IdxMBBPair>::const_iterator I =
808 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start);
809
810 bool ResVal = false;
811 while (I != Idx2MBBMap.end()) {
812 if (I->first > End)
813 break;
814 MachineBasicBlock *MBB = I->second;
815 if (getMBBEndIdx(MBB) > End)
816 break;
817 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
818 SE = MBB->succ_end(); SI != SE; ++SI)
819 MBBs.push_back(*SI);
820 ResVal = true;
821 ++I;
822 }
823 return ResVal;
824}
825
Owen Anderson03857b22008-08-13 21:49:13 +0000826LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000827 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000828 HUGE_VALF : 0.0F;
Owen Anderson03857b22008-08-13 21:49:13 +0000829 return new LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000830}
Evan Chengf2fbca62007-11-12 06:35:08 +0000831
Evan Chengc8d044e2008-02-15 18:24:29 +0000832/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
833/// copy field and returns the source register that defines it.
834unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
835 if (!VNI->copy)
836 return 0;
837
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000838 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
839 // If it's extracting out of a physical register, return the sub-register.
840 unsigned Reg = VNI->copy->getOperand(1).getReg();
841 if (TargetRegisterInfo::isPhysicalRegister(Reg))
842 Reg = tri_->getSubReg(Reg, VNI->copy->getOperand(2).getImm());
843 return Reg;
844 } else if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000845 return VNI->copy->getOperand(2).getReg();
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000846
Evan Cheng04ee5a12009-01-20 19:12:24 +0000847 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
848 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000849 return SrcReg;
850 assert(0 && "Unrecognized copy instruction!");
851 return 0;
852}
Evan Chengf2fbca62007-11-12 06:35:08 +0000853
854//===----------------------------------------------------------------------===//
855// Register allocator hooks.
856//
857
Evan Chengd70dbb52008-02-22 09:24:50 +0000858/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
859/// allow one) virtual register operand, then its uses are implicitly using
860/// the register. Returns the virtual register.
861unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
862 MachineInstr *MI) const {
863 unsigned RegOp = 0;
864 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
865 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000866 if (!MO.isReg() || !MO.isUse())
Evan Chengd70dbb52008-02-22 09:24:50 +0000867 continue;
868 unsigned Reg = MO.getReg();
869 if (Reg == 0 || Reg == li.reg)
870 continue;
871 // FIXME: For now, only remat MI with at most one register operand.
872 assert(!RegOp &&
873 "Can't rematerialize instruction with multiple register operand!");
874 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000875#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +0000876 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000877#endif
Evan Chengd70dbb52008-02-22 09:24:50 +0000878 }
879 return RegOp;
880}
881
882/// isValNoAvailableAt - Return true if the val# of the specified interval
883/// which reaches the given instruction also reaches the specified use index.
884bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
885 unsigned UseIdx) const {
886 unsigned Index = getInstructionIndex(MI);
887 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
888 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
889 return UI != li.end() && UI->valno == ValNo;
890}
891
Evan Chengf2fbca62007-11-12 06:35:08 +0000892/// isReMaterializable - Returns true if the definition MI of the specified
893/// val# of the specified interval is re-materializable.
894bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000895 const VNInfo *ValNo, MachineInstr *MI,
Evan Chengdc377862008-09-30 15:44:16 +0000896 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000897 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000898 if (DisableReMat)
899 return false;
900
Evan Cheng20ccded2008-03-15 00:19:36 +0000901 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000902 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000903
904 int FrameIdx = 0;
905 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000906 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000907 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
908 // this but remember this is not safe to fold into a two-address
909 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000910 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000911 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000912
Dan Gohman6d69ba82008-07-25 00:02:30 +0000913 // If the target-specific rules don't identify an instruction as
914 // being trivially rematerializable, use some target-independent
915 // rules.
916 if (!MI->getDesc().isRematerializable() ||
917 !tii_->isTriviallyReMaterializable(MI)) {
Dan Gohman4c8f8702008-07-25 15:08:37 +0000918 if (!EnableAggressiveRemat)
919 return false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000920
Dan Gohman0471a792008-07-28 18:43:51 +0000921 // If the instruction accesses memory but the memoperands have been lost,
Dan Gohman6d69ba82008-07-25 00:02:30 +0000922 // we can't analyze it.
923 const TargetInstrDesc &TID = MI->getDesc();
924 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
925 return false;
926
927 // Avoid instructions obviously unsafe for remat.
928 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
929 return false;
930
931 // If the instruction accesses memory and the memory could be non-constant,
932 // assume the instruction is not rematerializable.
Evan Chengdc377862008-09-30 15:44:16 +0000933 for (std::list<MachineMemOperand>::const_iterator
934 I = MI->memoperands_begin(), E = MI->memoperands_end(); I != E; ++I){
Dan Gohman6d69ba82008-07-25 00:02:30 +0000935 const MachineMemOperand &MMO = *I;
936 if (MMO.isVolatile() || MMO.isStore())
937 return false;
938 const Value *V = MMO.getValue();
939 if (!V)
940 return false;
941 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
942 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chengd70dbb52008-02-22 09:24:50 +0000943 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000944 } else if (!aa_->pointsToConstantMemory(V))
945 return false;
946 }
947
948 // If any of the registers accessed are non-constant, conservatively assume
949 // the instruction is not rematerializable.
950 unsigned ImpUse = 0;
951 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
952 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000953 if (MO.isReg()) {
Dan Gohman6d69ba82008-07-25 00:02:30 +0000954 unsigned Reg = MO.getReg();
955 if (Reg == 0)
956 continue;
957 if (TargetRegisterInfo::isPhysicalRegister(Reg))
958 return false;
959
960 // Only allow one def, and that in the first operand.
961 if (MO.isDef() != (i == 0))
962 return false;
963
964 // Only allow constant-valued registers.
965 bool IsLiveIn = mri_->isLiveIn(Reg);
966 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
967 E = mri_->def_end();
968
Dan Gohmanc93ced5b2008-12-08 04:53:23 +0000969 // For the def, it should be the only def of that register.
Dan Gohman6d69ba82008-07-25 00:02:30 +0000970 if (MO.isDef() && (next(I) != E || IsLiveIn))
971 return false;
972
973 if (MO.isUse()) {
974 // Only allow one use other register use, as that's all the
975 // remat mechanisms support currently.
976 if (Reg != li.reg) {
977 if (ImpUse == 0)
978 ImpUse = Reg;
979 else if (Reg != ImpUse)
980 return false;
981 }
Dan Gohmanc93ced5b2008-12-08 04:53:23 +0000982 // For the use, there should be only one associated def.
Dan Gohman6d69ba82008-07-25 00:02:30 +0000983 if (I != E && (next(I) != E || IsLiveIn))
984 return false;
985 }
Evan Chengd70dbb52008-02-22 09:24:50 +0000986 }
987 }
Evan Cheng5ef3a042007-12-06 00:01:56 +0000988 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000989
Dan Gohman6d69ba82008-07-25 00:02:30 +0000990 unsigned ImpUse = getReMatImplicitUse(li, MI);
991 if (ImpUse) {
992 const LiveInterval &ImpLi = getInterval(ImpUse);
993 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
994 re = mri_->use_end(); ri != re; ++ri) {
995 MachineInstr *UseMI = &*ri;
996 unsigned UseIdx = getInstructionIndex(UseMI);
997 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
998 continue;
999 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
1000 return false;
1001 }
Evan Chengdc377862008-09-30 15:44:16 +00001002
1003 // If a register operand of the re-materialized instruction is going to
1004 // be spilled next, then it's not legal to re-materialize this instruction.
1005 for (unsigned i = 0, e = SpillIs.size(); i != e; ++i)
1006 if (ImpUse == SpillIs[i]->reg)
1007 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +00001008 }
1009 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +00001010}
1011
Evan Cheng06587492008-10-24 02:05:00 +00001012/// isReMaterializable - Returns true if the definition MI of the specified
1013/// val# of the specified interval is re-materializable.
1014bool LiveIntervals::isReMaterializable(const LiveInterval &li,
1015 const VNInfo *ValNo, MachineInstr *MI) {
1016 SmallVector<LiveInterval*, 4> Dummy1;
1017 bool Dummy2;
1018 return isReMaterializable(li, ValNo, MI, Dummy1, Dummy2);
1019}
1020
Evan Cheng5ef3a042007-12-06 00:01:56 +00001021/// isReMaterializable - Returns true if every definition of MI of every
1022/// val# of the specified interval is re-materializable.
Evan Chengdc377862008-09-30 15:44:16 +00001023bool LiveIntervals::isReMaterializable(const LiveInterval &li,
1024 SmallVectorImpl<LiveInterval*> &SpillIs,
1025 bool &isLoad) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00001026 isLoad = false;
1027 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1028 i != e; ++i) {
1029 const VNInfo *VNI = *i;
1030 unsigned DefIdx = VNI->def;
1031 if (DefIdx == ~1U)
1032 continue; // Dead val#.
1033 // Is the def for the val# rematerializable?
1034 if (DefIdx == ~0u)
1035 return false;
1036 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
1037 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001038 if (!ReMatDefMI ||
Evan Chengdc377862008-09-30 15:44:16 +00001039 !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +00001040 return false;
1041 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +00001042 }
1043 return true;
1044}
1045
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001046/// FilterFoldedOps - Filter out two-address use operands. Return
1047/// true if it finds any issue with the operands that ought to prevent
1048/// folding.
1049static bool FilterFoldedOps(MachineInstr *MI,
1050 SmallVector<unsigned, 2> &Ops,
1051 unsigned &MRInfo,
1052 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner749c6f62008-01-07 07:27:27 +00001053 const TargetInstrDesc &TID = MI->getDesc();
Evan Cheng6e141fd2007-12-12 23:12:09 +00001054
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001055 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +00001056 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1057 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +00001058 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +00001059 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +00001060 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001061 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +00001062 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +00001063 MRInfo |= (unsigned)VirtRegMap::isMod;
1064 else {
1065 // Filter out two-address use operand(s).
Evan Chengd70dbb52008-02-22 09:24:50 +00001066 if (!MO.isImplicit() &&
1067 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengaee4af62007-12-02 08:30:39 +00001068 MRInfo = VirtRegMap::isModRef;
1069 continue;
1070 }
1071 MRInfo |= (unsigned)VirtRegMap::isRef;
1072 }
1073 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +00001074 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001075 return false;
1076}
1077
1078
1079/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
1080/// slot / to reg or any rematerialized load into ith operand of specified
1081/// MI. If it is successul, MI is updated with the newly created MI and
1082/// returns true.
1083bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
1084 VirtRegMap &vrm, MachineInstr *DefMI,
1085 unsigned InstrIdx,
1086 SmallVector<unsigned, 2> &Ops,
1087 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001088 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +00001089 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001090 RemoveMachineInstrFromMaps(MI);
1091 vrm.RemoveMachineInstrFromMaps(MI);
1092 MI->eraseFromParent();
1093 ++numFolds;
1094 return true;
1095 }
1096
1097 // Filter the list of operand indexes that are to be folded. Abort if
1098 // any operand will prevent folding.
1099 unsigned MRInfo = 0;
1100 SmallVector<unsigned, 2> FoldOps;
1101 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1102 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +00001103
Evan Cheng427f4c12008-03-31 23:19:51 +00001104 // The only time it's safe to fold into a two address instruction is when
1105 // it's folding reload and spill from / into a spill stack slot.
1106 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +00001107 return false;
1108
Evan Chengf2f8c2a2008-02-08 22:05:27 +00001109 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
1110 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001111 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +00001112 // Remember this instruction uses the spill slot.
1113 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
1114
Evan Chengf2fbca62007-11-12 06:35:08 +00001115 // Attempt to fold the memory reference into the instruction. If
1116 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +00001117 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +00001118 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +00001119 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +00001120 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001121 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +00001122 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +00001123 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +00001124 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
1125 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +00001126 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001127 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +00001128 return true;
1129 }
1130 return false;
1131}
1132
Evan Cheng018f9b02007-12-05 03:22:34 +00001133/// canFoldMemoryOperand - Returns true if the specified load / store
1134/// folding is possible.
1135bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001136 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001137 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001138 // Filter the list of operand indexes that are to be folded. Abort if
1139 // any operand will prevent folding.
1140 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001141 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001142 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1143 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001144
Evan Cheng3c75ba82008-04-01 21:37:32 +00001145 // It's only legal to remat for a use, not a def.
1146 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001147 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001148
Evan Chengd70dbb52008-02-22 09:24:50 +00001149 return tii_->canFoldMemoryOperand(MI, FoldOps);
1150}
1151
Evan Cheng81a03822007-11-17 00:40:40 +00001152bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1153 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1154 for (LiveInterval::Ranges::const_iterator
1155 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1156 std::vector<IdxMBBPair>::const_iterator II =
1157 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1158 if (II == Idx2MBBMap.end())
1159 continue;
1160 if (I->end > II->first) // crossing a MBB.
1161 return false;
1162 MBBs.insert(II->second);
1163 if (MBBs.size() > 1)
1164 return false;
1165 }
1166 return true;
1167}
1168
Evan Chengd70dbb52008-02-22 09:24:50 +00001169/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1170/// interval on to-be re-materialized operands of MI) with new register.
1171void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1172 MachineInstr *MI, unsigned NewVReg,
1173 VirtRegMap &vrm) {
1174 // There is an implicit use. That means one of the other operand is
1175 // being remat'ed and the remat'ed instruction has li.reg as an
1176 // use operand. Make sure we rewrite that as well.
1177 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1178 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001179 if (!MO.isReg())
Evan Chengd70dbb52008-02-22 09:24:50 +00001180 continue;
1181 unsigned Reg = MO.getReg();
1182 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1183 continue;
1184 if (!vrm.isReMaterialized(Reg))
1185 continue;
1186 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001187 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1188 if (UseMO)
1189 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001190 }
1191}
1192
Evan Chengf2fbca62007-11-12 06:35:08 +00001193/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1194/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001195bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001196rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1197 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001198 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001199 unsigned Slot, int LdSlot,
1200 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001201 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001202 const TargetRegisterClass* rc,
1203 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001204 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001205 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Owen Anderson28998312008-08-13 22:28:50 +00001206 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001207 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
1208 MachineBasicBlock *MBB = MI->getParent();
1209 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng018f9b02007-12-05 03:22:34 +00001210 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001211 RestartInstruction:
1212 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1213 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001214 if (!mop.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001215 continue;
1216 unsigned Reg = mop.getReg();
1217 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001218 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001219 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001220 if (Reg != li.reg)
1221 continue;
1222
1223 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001224 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001225 int FoldSlot = Slot;
1226 if (DefIsReMat) {
1227 // If this is the rematerializable definition MI itself and
1228 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001229 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001230 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1231 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001232 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001233 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001234 MI->eraseFromParent();
1235 break;
1236 }
1237
1238 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001239 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001240 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001241 if (isLoad) {
1242 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1243 FoldSS = isLoadSS;
1244 FoldSlot = LdSlot;
1245 }
1246 }
1247
Evan Chengf2fbca62007-11-12 06:35:08 +00001248 // Scan all of the operands of this instruction rewriting operands
1249 // to use NewVReg instead of li.reg as appropriate. We do this for
1250 // two reasons:
1251 //
1252 // 1. If the instr reads the same spilled vreg multiple times, we
1253 // want to reuse the NewVReg.
1254 // 2. If the instr is a two-addr instruction, we are required to
1255 // keep the src/dst regs pinned.
1256 //
1257 // Keep track of whether we replace a use and/or def so that we can
1258 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001259
Evan Cheng81a03822007-11-17 00:40:40 +00001260 HasUse = mop.isUse();
1261 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001262 SmallVector<unsigned, 2> Ops;
1263 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001264 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001265 const MachineOperand &MOj = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00001266 if (!MOj.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001267 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001268 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001269 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001270 continue;
1271 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001272 Ops.push_back(j);
1273 HasUse |= MOj.isUse();
1274 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001275 }
1276 }
1277
Evan Cheng79a796c2008-07-12 01:56:02 +00001278 if (HasUse && !li.liveAt(getUseIndex(index)))
1279 // Must be defined by an implicit def. It should not be spilled. Note,
1280 // this is for correctness reason. e.g.
1281 // 8 %reg1024<def> = IMPLICIT_DEF
1282 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1283 // The live range [12, 14) are not part of the r1024 live interval since
1284 // it's defined by an implicit def. It will not conflicts with live
1285 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001286 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001287 // the INSERT_SUBREG and both target registers that would overlap.
1288 HasUse = false;
1289
Evan Cheng9c3c2212008-06-06 07:54:39 +00001290 // Update stack slot spill weight if we are splitting.
Evan Chengc3417602008-06-21 06:45:54 +00001291 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001292 if (!TrySplit)
1293 SSWeight += Weight;
1294
David Greene26b86a02008-10-27 17:38:59 +00001295 // Create a new virtual register for the spill interval.
1296 // Create the new register now so we can map the fold instruction
1297 // to the new register so when it is unfolded we get the correct
1298 // answer.
1299 bool CreatedNewVReg = false;
1300 if (NewVReg == 0) {
1301 NewVReg = mri_->createVirtualRegister(rc);
1302 vrm.grow();
1303 CreatedNewVReg = true;
1304 }
1305
Evan Cheng9c3c2212008-06-06 07:54:39 +00001306 if (!TryFold)
1307 CanFold = false;
1308 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001309 // Do not fold load / store here if we are splitting. We'll find an
1310 // optimal point to insert a load / store later.
1311 if (!TrySplit) {
1312 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
David Greene26b86a02008-10-27 17:38:59 +00001313 Ops, FoldSS, FoldSlot, NewVReg)) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001314 // Folding the load/store can completely change the instruction in
1315 // unpredictable ways, rescan it from the beginning.
David Greene26b86a02008-10-27 17:38:59 +00001316
1317 if (FoldSS) {
1318 // We need to give the new vreg the same stack slot as the
1319 // spilled interval.
1320 vrm.assignVirt2StackSlot(NewVReg, FoldSlot);
1321 }
1322
Evan Cheng018f9b02007-12-05 03:22:34 +00001323 HasUse = false;
1324 HasDef = false;
1325 CanFold = false;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001326 if (isRemoved(MI)) {
1327 SSWeight -= Weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001328 break;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001329 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001330 goto RestartInstruction;
1331 }
1332 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001333 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001334 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001335 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001336 }
Evan Chengcddbb832007-11-30 21:23:43 +00001337
Evan Chengcddbb832007-11-30 21:23:43 +00001338 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001339 if (mop.isImplicit())
1340 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001341
1342 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001343 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1344 MachineOperand &mopj = MI->getOperand(Ops[j]);
1345 mopj.setReg(NewVReg);
1346 if (mopj.isImplicit())
1347 rewriteImplicitOps(li, MI, NewVReg, vrm);
1348 }
Evan Chengcddbb832007-11-30 21:23:43 +00001349
Evan Cheng81a03822007-11-17 00:40:40 +00001350 if (CreatedNewVReg) {
1351 if (DefIsReMat) {
1352 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001353 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001354 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001355 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001356 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001357 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001358 }
1359 if (!CanDelete || (HasUse && HasDef)) {
1360 // If this is a two-addr instruction then its use operands are
1361 // rematerializable but its def is not. It should be assigned a
1362 // stack slot.
1363 vrm.assignVirt2StackSlot(NewVReg, Slot);
1364 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001365 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001366 vrm.assignVirt2StackSlot(NewVReg, Slot);
1367 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001368 } else if (HasUse && HasDef &&
1369 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1370 // If this interval hasn't been assigned a stack slot (because earlier
1371 // def is a deleted remat def), do it now.
1372 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1373 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001374 }
1375
Evan Cheng313d4b82008-02-23 00:33:04 +00001376 // Re-matting an instruction with virtual register use. Add the
1377 // register as an implicit use on the use MI.
1378 if (DefIsReMat && ImpUse)
1379 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1380
Evan Chengf2fbca62007-11-12 06:35:08 +00001381 // create a new register interval for this spill / remat.
1382 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001383 if (CreatedNewVReg) {
1384 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001385 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001386 if (TrySplit)
1387 vrm.setIsSplitFromReg(NewVReg, li.reg);
1388 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001389
1390 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001391 if (CreatedNewVReg) {
1392 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1393 nI.getNextValue(~0U, 0, VNInfoAllocator));
1394 DOUT << " +" << LR;
1395 nI.addRange(LR);
1396 } else {
1397 // Extend the split live interval to this def / use.
1398 unsigned End = getUseIndex(index)+1;
1399 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1400 nI.getValNumInfo(nI.getNumValNums()-1));
1401 DOUT << " +" << LR;
1402 nI.addRange(LR);
1403 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001404 }
1405 if (HasDef) {
1406 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1407 nI.getNextValue(~0U, 0, VNInfoAllocator));
1408 DOUT << " +" << LR;
1409 nI.addRange(LR);
1410 }
Evan Cheng81a03822007-11-17 00:40:40 +00001411
Evan Chengf2fbca62007-11-12 06:35:08 +00001412 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001413 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001414 DOUT << '\n';
1415 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001416 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001417}
Evan Cheng81a03822007-11-17 00:40:40 +00001418bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001419 const VNInfo *VNI,
1420 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001421 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001422 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1423 unsigned KillIdx = VNI->kills[j];
1424 if (KillIdx > Idx && KillIdx < End)
1425 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001426 }
1427 return false;
1428}
1429
Evan Cheng063284c2008-02-21 00:34:19 +00001430/// RewriteInfo - Keep track of machine instrs that will be rewritten
1431/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001432namespace {
1433 struct RewriteInfo {
1434 unsigned Index;
1435 MachineInstr *MI;
1436 bool HasUse;
1437 bool HasDef;
1438 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1439 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1440 };
Evan Cheng063284c2008-02-21 00:34:19 +00001441
Dan Gohman844731a2008-05-13 00:00:25 +00001442 struct RewriteInfoCompare {
1443 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1444 return LHS.Index < RHS.Index;
1445 }
1446 };
1447}
Evan Cheng063284c2008-02-21 00:34:19 +00001448
Evan Chengf2fbca62007-11-12 06:35:08 +00001449void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001450rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001451 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001452 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001453 unsigned Slot, int LdSlot,
1454 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001455 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001456 const TargetRegisterClass* rc,
1457 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001458 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001459 BitVector &SpillMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001460 DenseMap<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001461 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001462 DenseMap<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1463 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001464 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001465 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001466 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001467 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001468 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001469
Evan Cheng063284c2008-02-21 00:34:19 +00001470 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001471 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001472 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001473 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1474 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001475 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001476 MachineOperand &O = ri.getOperand();
1477 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001478 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001479 unsigned index = getInstructionIndex(MI);
1480 if (index < start || index >= end)
1481 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001482 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1483 // Must be defined by an implicit def. It should not be spilled. Note,
1484 // this is for correctness reason. e.g.
1485 // 8 %reg1024<def> = IMPLICIT_DEF
1486 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1487 // The live range [12, 14) are not part of the r1024 live interval since
1488 // it's defined by an implicit def. It will not conflicts with live
1489 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001490 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001491 // the INSERT_SUBREG and both target registers that would overlap.
1492 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001493 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1494 }
1495 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1496
Evan Cheng313d4b82008-02-23 00:33:04 +00001497 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001498 // Now rewrite the defs and uses.
1499 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1500 RewriteInfo &rwi = RewriteMIs[i];
1501 ++i;
1502 unsigned index = rwi.Index;
1503 bool MIHasUse = rwi.HasUse;
1504 bool MIHasDef = rwi.HasDef;
1505 MachineInstr *MI = rwi.MI;
1506 // If MI def and/or use the same register multiple times, then there
1507 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001508 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001509 while (i != e && RewriteMIs[i].MI == MI) {
1510 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001511 bool isUse = RewriteMIs[i].HasUse;
1512 if (isUse) ++NumUses;
1513 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001514 MIHasDef |= RewriteMIs[i].HasDef;
1515 ++i;
1516 }
Evan Cheng81a03822007-11-17 00:40:40 +00001517 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001518
Evan Cheng0a891ed2008-05-23 23:00:04 +00001519 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001520 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001521 // register interval's spill weight to HUGE_VALF to prevent it from
1522 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001523 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001524 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001525 }
1526
Evan Cheng063284c2008-02-21 00:34:19 +00001527 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001528 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001529 if (TrySplit) {
Owen Anderson28998312008-08-13 22:28:50 +00001530 DenseMap<unsigned,unsigned>::iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001531 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001532 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001533 // One common case:
1534 // x = use
1535 // ...
1536 // ...
1537 // def = ...
1538 // = use
1539 // It's better to start a new interval to avoid artifically
1540 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001541 if (MIHasDef && !MIHasUse) {
1542 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001543 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001544 }
1545 }
Evan Chengcada2452007-11-28 01:28:46 +00001546 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001547
1548 bool IsNew = ThisVReg == 0;
1549 if (IsNew) {
1550 // This ends the previous live interval. If all of its def / use
1551 // can be folded, give it a low spill weight.
1552 if (NewVReg && TrySplit && AllCanFold) {
1553 LiveInterval &nI = getOrCreateInterval(NewVReg);
1554 nI.weight /= 10.0F;
1555 }
1556 AllCanFold = true;
1557 }
1558 NewVReg = ThisVReg;
1559
Evan Cheng81a03822007-11-17 00:40:40 +00001560 bool HasDef = false;
1561 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001562 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001563 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1564 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1565 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1566 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001567 if (!HasDef && !HasUse)
1568 continue;
1569
Evan Cheng018f9b02007-12-05 03:22:34 +00001570 AllCanFold &= CanFold;
1571
Evan Cheng81a03822007-11-17 00:40:40 +00001572 // Update weight of spill interval.
1573 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001574 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001575 // The spill weight is now infinity as it cannot be spilled again.
1576 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001577 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001578 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001579
1580 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001581 if (HasDef) {
1582 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001583 bool HasKill = false;
1584 if (!HasUse)
1585 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1586 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001587 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001588 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001589 if (VNI)
1590 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1591 }
Owen Anderson28998312008-08-13 22:28:50 +00001592 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Chenge3110d02007-12-01 04:42:39 +00001593 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001594 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001595 if (SII == SpillIdxes.end()) {
1596 std::vector<SRInfo> S;
1597 S.push_back(SRInfo(index, NewVReg, true));
1598 SpillIdxes.insert(std::make_pair(MBBId, S));
1599 } else if (SII->second.back().vreg != NewVReg) {
1600 SII->second.push_back(SRInfo(index, NewVReg, true));
1601 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001602 // If there is an earlier def and this is a two-address
1603 // instruction, then it's not possible to fold the store (which
1604 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001605 SRInfo &Info = SII->second.back();
1606 Info.index = index;
1607 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001608 }
1609 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001610 } else if (SII != SpillIdxes.end() &&
1611 SII->second.back().vreg == NewVReg &&
1612 (int)index > SII->second.back().index) {
1613 // There is an earlier def that's not killed (must be two-address).
1614 // The spill is no longer needed.
1615 SII->second.pop_back();
1616 if (SII->second.empty()) {
1617 SpillIdxes.erase(MBBId);
1618 SpillMBBs.reset(MBBId);
1619 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001620 }
1621 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001622 }
1623
1624 if (HasUse) {
Owen Anderson28998312008-08-13 22:28:50 +00001625 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001626 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001627 if (SII != SpillIdxes.end() &&
1628 SII->second.back().vreg == NewVReg &&
1629 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001630 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001631 SII->second.back().canFold = false;
Owen Anderson28998312008-08-13 22:28:50 +00001632 DenseMap<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001633 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001634 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001635 // If we are splitting live intervals, only fold if it's the first
1636 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001637 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001638 else if (IsNew) {
1639 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001640 if (RII == RestoreIdxes.end()) {
1641 std::vector<SRInfo> Infos;
1642 Infos.push_back(SRInfo(index, NewVReg, true));
1643 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1644 } else {
1645 RII->second.push_back(SRInfo(index, NewVReg, true));
1646 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001647 RestoreMBBs.set(MBBId);
1648 }
1649 }
1650
1651 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001652 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001653 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001654 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001655
1656 if (NewVReg && TrySplit && AllCanFold) {
1657 // If all of its def / use can be folded, give it a low spill weight.
1658 LiveInterval &nI = getOrCreateInterval(NewVReg);
1659 nI.weight /= 10.0F;
1660 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001661}
1662
Evan Cheng1953d0c2007-11-29 10:12:14 +00001663bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1664 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001665 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001666 if (!RestoreMBBs[Id])
1667 return false;
1668 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1669 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1670 if (Restores[i].index == index &&
1671 Restores[i].vreg == vr &&
1672 Restores[i].canFold)
1673 return true;
1674 return false;
1675}
1676
1677void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1678 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001679 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001680 if (!RestoreMBBs[Id])
1681 return;
1682 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1683 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1684 if (Restores[i].index == index && Restores[i].vreg)
1685 Restores[i].index = -1;
1686}
Evan Cheng81a03822007-11-17 00:40:40 +00001687
Evan Cheng4cce6b42008-04-11 17:53:36 +00001688/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1689/// spilled and create empty intervals for their uses.
1690void
1691LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1692 const TargetRegisterClass* rc,
1693 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001694 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1695 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001696 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001697 MachineInstr *MI = &*ri;
1698 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001699 if (O.isDef()) {
1700 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1701 "Register def was not rewritten?");
1702 RemoveMachineInstrFromMaps(MI);
1703 vrm.RemoveMachineInstrFromMaps(MI);
1704 MI->eraseFromParent();
1705 } else {
1706 // This must be an use of an implicit_def so it's not part of the live
1707 // interval. Create a new empty live interval for it.
1708 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1709 unsigned NewVReg = mri_->createVirtualRegister(rc);
1710 vrm.grow();
1711 vrm.setIsImplicitlyDefined(NewVReg);
1712 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1713 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1714 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001715 if (MO.isReg() && MO.getReg() == li.reg)
Evan Cheng4cce6b42008-04-11 17:53:36 +00001716 MO.setReg(NewVReg);
1717 }
1718 }
Evan Cheng419852c2008-04-03 16:39:43 +00001719 }
1720}
1721
Owen Anderson133f10f2008-08-18 19:52:22 +00001722namespace {
1723 struct LISorter {
1724 bool operator()(LiveInterval* A, LiveInterval* B) {
1725 return A->beginNumber() < B->beginNumber();
1726 }
1727 };
1728}
Evan Cheng81a03822007-11-17 00:40:40 +00001729
Evan Chengf2fbca62007-11-12 06:35:08 +00001730std::vector<LiveInterval*> LiveIntervals::
Owen Andersond6664312008-08-18 18:05:32 +00001731addIntervalsForSpillsFast(const LiveInterval &li,
1732 const MachineLoopInfo *loopInfo,
1733 VirtRegMap &vrm, float& SSWeight) {
Owen Anderson17197312008-08-18 23:41:04 +00001734 unsigned slot = vrm.assignVirt2StackSlot(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00001735
1736 std::vector<LiveInterval*> added;
1737
1738 assert(li.weight != HUGE_VALF &&
1739 "attempt to spill already spilled interval!");
1740
1741 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
1742 DEBUG(li.dump());
1743 DOUT << '\n';
1744
1745 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
1746
Owen Anderson9a032932008-08-18 21:20:32 +00001747 SSWeight = 0.0f;
1748
Owen Andersona41e47a2008-08-19 22:12:11 +00001749 MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg);
1750 while (RI != mri_->reg_end()) {
1751 MachineInstr* MI = &*RI;
1752
1753 SmallVector<unsigned, 2> Indices;
1754 bool HasUse = false;
1755 bool HasDef = false;
1756
1757 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1758 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001759 if (!mop.isReg() || mop.getReg() != li.reg) continue;
Owen Andersona41e47a2008-08-19 22:12:11 +00001760
1761 HasUse |= MI->getOperand(i).isUse();
1762 HasDef |= MI->getOperand(i).isDef();
1763
1764 Indices.push_back(i);
1765 }
1766
1767 if (!tryFoldMemoryOperand(MI, vrm, NULL, getInstructionIndex(MI),
1768 Indices, true, slot, li.reg)) {
1769 unsigned NewVReg = mri_->createVirtualRegister(rc);
Owen Anderson9a032932008-08-18 21:20:32 +00001770 vrm.grow();
Owen Anderson17197312008-08-18 23:41:04 +00001771 vrm.assignVirt2StackSlot(NewVReg, slot);
1772
Owen Andersona41e47a2008-08-19 22:12:11 +00001773 // create a new register for this spill
1774 LiveInterval &nI = getOrCreateInterval(NewVReg);
Owen Andersond6664312008-08-18 18:05:32 +00001775
Owen Andersona41e47a2008-08-19 22:12:11 +00001776 // the spill weight is now infinity as it
1777 // cannot be spilled again
1778 nI.weight = HUGE_VALF;
1779
1780 // Rewrite register operands to use the new vreg.
1781 for (SmallVectorImpl<unsigned>::iterator I = Indices.begin(),
1782 E = Indices.end(); I != E; ++I) {
1783 MI->getOperand(*I).setReg(NewVReg);
1784
1785 if (MI->getOperand(*I).isUse())
1786 MI->getOperand(*I).setIsKill(true);
1787 }
1788
1789 // Fill in the new live interval.
1790 unsigned index = getInstructionIndex(MI);
1791 if (HasUse) {
1792 LiveRange LR(getLoadIndex(index), getUseIndex(index),
1793 nI.getNextValue(~0U, 0, getVNInfoAllocator()));
1794 DOUT << " +" << LR;
1795 nI.addRange(LR);
1796 vrm.addRestorePoint(NewVReg, MI);
1797 }
1798 if (HasDef) {
1799 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1800 nI.getNextValue(~0U, 0, getVNInfoAllocator()));
1801 DOUT << " +" << LR;
1802 nI.addRange(LR);
1803 vrm.addSpillPoint(NewVReg, true, MI);
1804 }
1805
Owen Anderson17197312008-08-18 23:41:04 +00001806 added.push_back(&nI);
Owen Anderson8dc2cbe2008-08-18 18:38:12 +00001807
Owen Andersona41e47a2008-08-19 22:12:11 +00001808 DOUT << "\t\t\t\tadded new interval: ";
1809 DEBUG(nI.dump());
1810 DOUT << '\n';
1811
1812 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
1813 if (HasUse) {
1814 if (HasDef)
1815 SSWeight += getSpillWeight(true, true, loopDepth);
1816 else
1817 SSWeight += getSpillWeight(false, true, loopDepth);
1818 } else
1819 SSWeight += getSpillWeight(true, false, loopDepth);
1820 }
Owen Anderson9a032932008-08-18 21:20:32 +00001821
Owen Anderson9a032932008-08-18 21:20:32 +00001822
Owen Andersona41e47a2008-08-19 22:12:11 +00001823 RI = mri_->reg_begin(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00001824 }
Owen Andersond6664312008-08-18 18:05:32 +00001825
Owen Andersona41e47a2008-08-19 22:12:11 +00001826 // Clients expect the new intervals to be returned in sorted order.
Owen Anderson133f10f2008-08-18 19:52:22 +00001827 std::sort(added.begin(), added.end(), LISorter());
1828
Owen Andersond6664312008-08-18 18:05:32 +00001829 return added;
1830}
1831
1832std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001833addIntervalsForSpills(const LiveInterval &li,
Evan Chengdc377862008-09-30 15:44:16 +00001834 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001835 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1836 float &SSWeight) {
Owen Andersonae339ba2008-08-19 00:17:30 +00001837
1838 if (EnableFastSpilling)
1839 return addIntervalsForSpillsFast(li, loopInfo, vrm, SSWeight);
1840
Evan Chengf2fbca62007-11-12 06:35:08 +00001841 assert(li.weight != HUGE_VALF &&
1842 "attempt to spill already spilled interval!");
1843
1844 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001845 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001846 DOUT << '\n';
1847
Evan Cheng9c3c2212008-06-06 07:54:39 +00001848 // Spill slot weight.
1849 SSWeight = 0.0f;
1850
Evan Cheng72eeb942008-12-05 17:00:16 +00001851 // Each bit specify whether a spill is required in the MBB.
Evan Cheng81a03822007-11-17 00:40:40 +00001852 BitVector SpillMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00001853 DenseMap<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001854 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00001855 DenseMap<unsigned, std::vector<SRInfo> > RestoreIdxes;
1856 DenseMap<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001857 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001858 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001859
1860 unsigned NumValNums = li.getNumValNums();
1861 SmallVector<MachineInstr*, 4> ReMatDefs;
1862 ReMatDefs.resize(NumValNums, NULL);
1863 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1864 ReMatOrigDefs.resize(NumValNums, NULL);
1865 SmallVector<int, 4> ReMatIds;
1866 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1867 BitVector ReMatDelete(NumValNums);
1868 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1869
Evan Cheng81a03822007-11-17 00:40:40 +00001870 // Spilling a split live interval. It cannot be split any further. Also,
1871 // it's also guaranteed to be a single val# / range interval.
1872 if (vrm.getPreSplitReg(li.reg)) {
1873 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001874 // Unset the split kill marker on the last use.
1875 unsigned KillIdx = vrm.getKillPoint(li.reg);
1876 if (KillIdx) {
1877 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1878 assert(KillMI && "Last use disappeared?");
1879 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1880 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001881 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001882 }
Evan Chengadf85902007-12-05 09:51:10 +00001883 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001884 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1885 Slot = vrm.getStackSlot(li.reg);
1886 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1887 MachineInstr *ReMatDefMI = DefIsReMat ?
1888 vrm.getReMaterializedMI(li.reg) : NULL;
1889 int LdSlot = 0;
1890 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1891 bool isLoad = isLoadSS ||
Dan Gohman15511cf2008-12-03 18:15:48 +00001892 (DefIsReMat && (ReMatDefMI->getDesc().canFoldAsLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001893 bool IsFirstRange = true;
1894 for (LiveInterval::Ranges::const_iterator
1895 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1896 // If this is a split live interval with multiple ranges, it means there
1897 // are two-address instructions that re-defined the value. Only the
1898 // first def can be rematerialized!
1899 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001900 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001901 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1902 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001903 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001904 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001905 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001906 } else {
1907 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1908 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001909 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001910 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001911 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001912 }
1913 IsFirstRange = false;
1914 }
Evan Cheng419852c2008-04-03 16:39:43 +00001915
Evan Cheng9c3c2212008-06-06 07:54:39 +00001916 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng4cce6b42008-04-11 17:53:36 +00001917 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001918 return NewLIs;
1919 }
1920
1921 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001922 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1923 TrySplit = false;
1924 if (TrySplit)
1925 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001926 bool NeedStackSlot = false;
1927 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1928 i != e; ++i) {
1929 const VNInfo *VNI = *i;
1930 unsigned VN = VNI->id;
1931 unsigned DefIdx = VNI->def;
1932 if (DefIdx == ~1U)
1933 continue; // Dead val#.
1934 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001935 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1936 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001937 bool dummy;
Evan Chengdc377862008-09-30 15:44:16 +00001938 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, SpillIs, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001939 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001940 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001941 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001942 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1943 ClonedMIs.push_back(Clone);
1944 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001945
1946 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001947 if (VNI->hasPHIKill) {
1948 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001949 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001950 CanDelete = false;
1951 // Need a stack slot if there is any live range where uses cannot be
1952 // rematerialized.
1953 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001954 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001955 if (CanDelete)
1956 ReMatDelete.set(VN);
1957 } else {
1958 // Need a stack slot if there is any live range where uses cannot be
1959 // rematerialized.
1960 NeedStackSlot = true;
1961 }
1962 }
1963
1964 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001965 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001966 Slot = vrm.assignVirt2StackSlot(li.reg);
1967
1968 // Create new intervals and rewrite defs and uses.
1969 for (LiveInterval::Ranges::const_iterator
1970 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001971 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1972 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1973 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001974 bool CanDelete = ReMatDelete[I->valno->id];
1975 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001976 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001977 bool isLoad = isLoadSS ||
Dan Gohman15511cf2008-12-03 18:15:48 +00001978 (DefIsReMat && ReMatDefMI->getDesc().canFoldAsLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001979 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001980 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001981 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001982 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001983 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengf2fbca62007-11-12 06:35:08 +00001984 }
1985
Evan Cheng0cbb1162007-11-29 01:06:25 +00001986 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001987 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001988 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001989 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00001990 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001991
Evan Chengb50bb8c2007-12-05 08:16:32 +00001992 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001993 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001994 if (NeedStackSlot) {
1995 int Id = SpillMBBs.find_first();
1996 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001997 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1998 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001999 std::vector<SRInfo> &spills = SpillIdxes[Id];
2000 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
2001 int index = spills[i].index;
2002 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00002003 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002004 bool isReMat = vrm.isReMaterialized(VReg);
2005 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00002006 bool CanFold = false;
2007 bool FoundUse = false;
2008 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00002009 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00002010 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00002011 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
2012 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00002013 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00002014 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002015
2016 Ops.push_back(j);
2017 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00002018 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002019 if (isReMat ||
2020 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
2021 RestoreMBBs, RestoreIdxes))) {
2022 // MI has two-address uses of the same register. If the use
2023 // isn't the first and only use in the BB, then we can't fold
2024 // it. FIXME: Move this to rewriteInstructionsForSpills.
2025 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00002026 break;
2027 }
Evan Chengaee4af62007-12-02 08:30:39 +00002028 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00002029 }
2030 }
2031 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00002032 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00002033 if (CanFold && !Ops.empty()) {
2034 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00002035 Folded = true;
Evan Chengf38d14f2007-12-05 09:05:34 +00002036 if (FoundUse > 0) {
Evan Chengaee4af62007-12-02 08:30:39 +00002037 // Also folded uses, do not issue a load.
2038 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00002039 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
2040 }
Evan Cheng597d10d2007-12-04 00:32:23 +00002041 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00002042 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002043 }
2044
Evan Cheng7e073ba2008-04-09 20:57:25 +00002045 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00002046 if (!Folded) {
2047 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
2048 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00002049 if (!MI->registerDefIsDead(nI.reg))
2050 // No need to spill a dead def.
2051 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002052 if (isKill)
2053 AddedKill.insert(&nI);
2054 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00002055
2056 // Update spill slot weight.
2057 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00002058 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002059 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002060 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002061 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002062 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002063
Evan Cheng1953d0c2007-11-29 10:12:14 +00002064 int Id = RestoreMBBs.find_first();
2065 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00002066 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
2067 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
2068
Evan Cheng1953d0c2007-11-29 10:12:14 +00002069 std::vector<SRInfo> &restores = RestoreIdxes[Id];
2070 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
2071 int index = restores[i].index;
2072 if (index == -1)
2073 continue;
2074 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00002075 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00002076 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00002077 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00002078 bool CanFold = false;
2079 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00002080 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00002081 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00002082 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
2083 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00002084 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng81a03822007-11-17 00:40:40 +00002085 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002086
Evan Cheng0cbb1162007-11-29 01:06:25 +00002087 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00002088 // If this restore were to be folded, it would have been folded
2089 // already.
2090 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00002091 break;
2092 }
Evan Chengaee4af62007-12-02 08:30:39 +00002093 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00002094 }
2095 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002096
2097 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00002098 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00002099 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00002100 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00002101 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
2102 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00002103 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
2104 int LdSlot = 0;
2105 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
2106 // If the rematerializable def is a load, also try to fold it.
Dan Gohman15511cf2008-12-03 18:15:48 +00002107 if (isLoadSS || ReMatDefMI->getDesc().canFoldAsLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00002108 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
2109 Ops, isLoadSS, LdSlot, VReg);
Evan Cheng650d7f32008-12-05 17:41:31 +00002110 if (!Folded) {
2111 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
2112 if (ImpUse) {
2113 // Re-matting an instruction with virtual register use. Add the
2114 // register as an implicit use on the use MI and update the register
2115 // interval's spill weight to HUGE_VALF to prevent it from being
2116 // spilled.
2117 LiveInterval &ImpLi = getInterval(ImpUse);
2118 ImpLi.weight = HUGE_VALF;
2119 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
2120 }
Evan Chengd70dbb52008-02-22 09:24:50 +00002121 }
Evan Chengaee4af62007-12-02 08:30:39 +00002122 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002123 }
2124 // If folding is not possible / failed, then tell the spiller to issue a
2125 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00002126 if (Folded)
2127 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002128 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00002129 vrm.addRestorePoint(VReg, MI);
Evan Cheng9c3c2212008-06-06 07:54:39 +00002130
2131 // Update spill slot weight.
2132 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00002133 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Cheng81a03822007-11-17 00:40:40 +00002134 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002135 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00002136 }
2137
Evan Chengb50bb8c2007-12-05 08:16:32 +00002138 // Finalize intervals: add kills, finalize spill weights, and filter out
2139 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00002140 std::vector<LiveInterval*> RetNewLIs;
2141 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
2142 LiveInterval *LI = NewLIs[i];
2143 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00002144 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002145 if (!AddedKill.count(LI)) {
2146 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00002147 unsigned LastUseIdx = getBaseIndex(LR->end);
2148 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00002149 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002150 assert(UseIdx != -1);
Evan Chengd70dbb52008-02-22 09:24:50 +00002151 if (LastUse->getOperand(UseIdx).isImplicit() ||
2152 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chengb50bb8c2007-12-05 08:16:32 +00002153 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00002154 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00002155 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00002156 }
Evan Cheng597d10d2007-12-04 00:32:23 +00002157 RetNewLIs.push_back(LI);
2158 }
2159 }
Evan Cheng81a03822007-11-17 00:40:40 +00002160
Evan Cheng4cce6b42008-04-11 17:53:36 +00002161 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00002162 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00002163}
Evan Cheng676dd7c2008-03-11 07:19:34 +00002164
2165/// hasAllocatableSuperReg - Return true if the specified physical register has
2166/// any super register that's allocatable.
2167bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
2168 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
2169 if (allocatableRegs_[*AS] && hasInterval(*AS))
2170 return true;
2171 return false;
2172}
2173
2174/// getRepresentativeReg - Find the largest super register of the specified
2175/// physical register.
2176unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
2177 // Find the largest super-register that is allocatable.
2178 unsigned BestReg = Reg;
2179 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
2180 unsigned SuperReg = *AS;
2181 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
2182 BestReg = SuperReg;
2183 break;
2184 }
2185 }
2186 return BestReg;
2187}
2188
2189/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
2190/// specified interval that conflicts with the specified physical register.
2191unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
2192 unsigned PhysReg) const {
2193 unsigned NumConflicts = 0;
2194 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
2195 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2196 E = mri_->reg_end(); I != E; ++I) {
2197 MachineOperand &O = I.getOperand();
2198 MachineInstr *MI = O.getParent();
2199 unsigned Index = getInstructionIndex(MI);
2200 if (pli.liveAt(Index))
2201 ++NumConflicts;
2202 }
2203 return NumConflicts;
2204}
2205
2206/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
2207/// around all defs and uses of the specified interval.
2208void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
2209 unsigned PhysReg, VirtRegMap &vrm) {
2210 unsigned SpillReg = getRepresentativeReg(PhysReg);
2211
2212 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
2213 // If there are registers which alias PhysReg, but which are not a
2214 // sub-register of the chosen representative super register. Assert
2215 // since we can't handle it yet.
2216 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
2217 tri_->isSuperRegister(*AS, SpillReg));
2218
2219 LiveInterval &pli = getInterval(SpillReg);
2220 SmallPtrSet<MachineInstr*, 8> SeenMIs;
2221 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2222 E = mri_->reg_end(); I != E; ++I) {
2223 MachineOperand &O = I.getOperand();
2224 MachineInstr *MI = O.getParent();
2225 if (SeenMIs.count(MI))
2226 continue;
2227 SeenMIs.insert(MI);
2228 unsigned Index = getInstructionIndex(MI);
2229 if (pli.liveAt(Index)) {
2230 vrm.addEmergencySpill(SpillReg, MI);
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002231 unsigned StartIdx = getLoadIndex(Index);
2232 unsigned EndIdx = getStoreIndex(Index)+1;
2233 if (pli.isInOneLiveRange(StartIdx, EndIdx))
2234 pli.removeRange(StartIdx, EndIdx);
2235 else {
2236 cerr << "Ran out of registers during register allocation!\n";
2237 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
2238 cerr << "Please check your inline asm statement for invalid "
2239 << "constraints:\n";
2240 MI->print(cerr.stream(), tm_);
2241 }
2242 exit(1);
2243 }
Evan Cheng676dd7c2008-03-11 07:19:34 +00002244 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
2245 if (!hasInterval(*AS))
2246 continue;
2247 LiveInterval &spli = getInterval(*AS);
2248 if (spli.liveAt(Index))
2249 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
2250 }
2251 }
2252 }
2253}
Owen Andersonc4dc1322008-06-05 17:15:43 +00002254
2255LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
2256 MachineInstr* startInst) {
2257 LiveInterval& Interval = getOrCreateInterval(reg);
2258 VNInfo* VN = Interval.getNextValue(
2259 getInstructionIndex(startInst) + InstrSlots::DEF,
2260 startInst, getVNInfoAllocator());
2261 VN->hasPHIKill = true;
2262 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
2263 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
2264 getMBBEndIdx(startInst->getParent()) + 1, VN);
2265 Interval.addRange(LR);
2266
2267 return LR;
2268}