blob: d7c5544c366f6a3a6a3d32ec1ff10b9bfd8ba624 [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"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000022#include "llvm/CodeGen/LiveVariables.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000025#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000027#include "llvm/CodeGen/Passes.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000028#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000029#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000036#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000037using namespace llvm;
38
Evan Chengbc165e42007-08-16 07:24:22 +000039namespace {
40 // Hidden options for help debugging.
41 cl::opt<bool> DisableReMat("disable-rematerialization",
42 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000043
44 cl::opt<bool> SplitAtBB("split-intervals-at-bb",
Evan Cheng33faddc2007-12-06 08:54:31 +000045 cl::init(true), cl::Hidden);
Evan Cheng0cbb1162007-11-29 01:06:25 +000046 cl::opt<int> SplitLimit("split-limit",
47 cl::init(-1), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000048}
49
Chris Lattnercd3245a2006-12-19 22:41:21 +000050STATISTIC(numIntervals, "Number of original intervals");
51STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
Evan Cheng0cbb1162007-11-29 01:06:25 +000052STATISTIC(numFolds , "Number of loads/stores folded into instructions");
53STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000054
Devang Patel19974732007-05-03 01:11:54 +000055char LiveIntervals::ID = 0;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000056namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +000057 RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Chris Lattnerd74ea2b2006-05-24 17:04:05 +000058}
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000059
Chris Lattnerf7da2c72006-08-24 22:43:55 +000060void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
David Greene25133302007-06-08 17:18:56 +000061 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000062 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000063 AU.addPreservedID(MachineLoopInfoID);
64 AU.addPreservedID(MachineDominatorsID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000065 AU.addPreservedID(PHIEliminationID);
66 AU.addRequiredID(PHIEliminationID);
67 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000068 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000069}
70
Chris Lattnerf7da2c72006-08-24 22:43:55 +000071void LiveIntervals::releaseMemory() {
Evan Cheng4ca980e2007-10-17 02:10:22 +000072 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000073 mi2iMap_.clear();
74 i2miMap_.clear();
75 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000076 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
77 VNInfoAllocator.Reset();
Evan Cheng549f27d32007-08-13 23:45:17 +000078 for (unsigned i = 0, e = ClonedMIs.size(); i != e; ++i)
79 delete ClonedMIs[i];
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000080}
81
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000082/// runOnMachineFunction - Register allocate the whole function
83///
84bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000085 mf_ = &fn;
Evan Chengd70dbb52008-02-22 09:24:50 +000086 mri_ = &mf_->getRegInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000087 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +000088 tri_ = tm_->getRegisterInfo();
Chris Lattnerf768bba2005-03-09 23:05:19 +000089 tii_ = tm_->getInstrInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000090 lv_ = &getAnalysis<LiveVariables>();
Dan Gohman6f0d0242008-02-10 18:45:23 +000091 allocatableRegs_ = tri_->getAllocatableSet(fn);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000092
Chris Lattner428b92e2006-09-15 03:57:23 +000093 // Number MachineInstrs and MachineBasicBlocks.
94 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +000095 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +000096
97 unsigned MIIndex = 0;
98 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
99 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000100 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000101
Chris Lattner428b92e2006-09-15 03:57:23 +0000102 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
103 I != E; ++I) {
104 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000105 assert(inserted && "multiple MachineInstr -> index mappings");
Chris Lattner428b92e2006-09-15 03:57:23 +0000106 i2miMap_.push_back(I);
107 MIIndex += InstrSlots::NUM;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000108 }
Evan Cheng549f27d32007-08-13 23:45:17 +0000109
110 // Set the MBB2IdxMap entry for this MBB.
111 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
Evan Cheng4ca980e2007-10-17 02:10:22 +0000112 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000113 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000114 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000115
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000116 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000117
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000118 numIntervals += getNumIntervals();
119
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000120 DOUT << "********** INTERVALS **********\n";
121 for (iterator I = begin(), E = end(); I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000122 I->second.print(DOUT, tri_);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000123 DOUT << "\n";
124 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000125
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000126 numIntervalsAfter += getNumIntervals();
Chris Lattner70ca3582004-09-30 15:59:17 +0000127 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000128 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000129}
130
Chris Lattner70ca3582004-09-30 15:59:17 +0000131/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000132void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000133 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000134 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000135 I->second.print(DOUT, tri_);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000136 DOUT << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000137 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000138
139 O << "********** MACHINEINSTRS **********\n";
140 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
141 mbbi != mbbe; ++mbbi) {
142 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
143 for (MachineBasicBlock::iterator mii = mbbi->begin(),
144 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000145 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000146 }
147 }
148}
149
Evan Chengc92da382007-11-03 07:20:12 +0000150/// conflictsWithPhysRegDef - Returns true if the specified register
151/// is defined during the duration of the specified interval.
152bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
153 VirtRegMap &vrm, unsigned reg) {
154 for (LiveInterval::Ranges::const_iterator
155 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
156 for (unsigned index = getBaseIndex(I->start),
157 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
158 index += InstrSlots::NUM) {
159 // skip deleted instructions
160 while (index != end && !getInstructionFromIndex(index))
161 index += InstrSlots::NUM;
162 if (index == end) break;
163
164 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng5d446262007-11-15 08:13:29 +0000165 unsigned SrcReg, DstReg;
166 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
167 if (SrcReg == li.reg || DstReg == li.reg)
168 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000169 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
170 MachineOperand& mop = MI->getOperand(i);
Evan Cheng5d446262007-11-15 08:13:29 +0000171 if (!mop.isRegister())
Evan Chengc92da382007-11-03 07:20:12 +0000172 continue;
173 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000174 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000175 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000176 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000177 if (!vrm.hasPhys(PhysReg))
178 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000179 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000180 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000181 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000182 return true;
183 }
184 }
185 }
186
187 return false;
188}
189
Evan Cheng549f27d32007-08-13 23:45:17 +0000190void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000191 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000192 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000193 else
194 cerr << "%reg" << reg;
195}
196
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000197void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000198 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000199 unsigned MIIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000200 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000201 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000202 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000203
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000204 // Virtual registers may be defined multiple times (due to phi
205 // elimination and 2-addr elimination). Much of what we do only has to be
206 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000207 // time we see a vreg.
208 if (interval.empty()) {
209 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000210 unsigned defIndex = getDefIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000211 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000212 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000213 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000214 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
215 tii_->isMoveInstr(*mi, SrcReg, DstReg))
216 CopyMI = mi;
217 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000218
219 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000220
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000221 // Loop over all of the blocks that the vreg is defined in. There are
222 // two cases we have to handle here. The most common case is a vreg
223 // whose lifetime is contained within a basic block. In this case there
224 // will be a single kill, in MBB, which comes after the definition.
225 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
226 // FIXME: what about dead vars?
227 unsigned killIdx;
228 if (vi.Kills[0] != mi)
229 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
230 else
231 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000232
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000233 // If the kill happens after the definition, we have an intra-block
234 // live range.
235 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000236 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000237 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000238 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000239 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000240 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000241 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000242 return;
243 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000244 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000245
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000246 // The other case we handle is when a virtual register lives to the end
247 // of the defining block, potentially live across some blocks, then is
248 // live into some number of blocks, but gets killed. Start by adding a
249 // range that goes from this definition to the end of the defining block.
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000250 LiveRange NewLR(defIndex,
251 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000252 ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000253 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000254 interval.addRange(NewLR);
255
256 // Iterate over all of the blocks that the variable is completely
257 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
258 // live interval.
259 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
260 if (vi.AliveBlocks[i]) {
Chris Lattner428b92e2006-09-15 03:57:23 +0000261 MachineBasicBlock *MBB = mf_->getBlockNumbered(i);
262 if (!MBB->empty()) {
263 LiveRange LR(getMBBStartIdx(i),
264 getInstructionIndex(&MBB->back()) + InstrSlots::NUM,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000265 ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000266 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000267 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000268 }
269 }
270 }
271
272 // Finally, this virtual register is live from the start of any killing
273 // block to the 'use' slot of the killing instruction.
274 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
275 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000276 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000277 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000278 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000279 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000280 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000281 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000282 }
283
284 } else {
285 // If this is the second time we see a virtual register definition, it
286 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000287 // the result of two address elimination, then the vreg is one of the
288 // def-and-use register operand.
Evan Cheng32dfbea2007-10-12 08:50:34 +0000289 if (mi->isRegReDefinedByTwoAddr(interval.reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000290 // If this is a two-address definition, then we have already processed
291 // the live range. The only problem is that we didn't realize there
292 // are actually two values in the live interval. Because of this we
293 // need to take the LiveRegion that defines this register and split it
294 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000295 assert(interval.containsOneValue());
296 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000297 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000298
Evan Cheng4f8ff162007-08-11 00:59:19 +0000299 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000300 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000301
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000302 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000303 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000304 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000305
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000306 // Two-address vregs should always only be redefined once. This means
307 // that at this point, there should be exactly one value number in it.
308 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
309
Chris Lattner91725b72006-08-31 05:54:43 +0000310 // The new value number (#1) is defined by the instruction we claimed
311 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000312 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
313 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000314
Chris Lattner91725b72006-08-31 05:54:43 +0000315 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000316 OldValNo->def = RedefIndex;
317 OldValNo->copy = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000318
319 // Add the new live interval which replaces the range for the input copy.
320 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000321 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000322 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000323 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000324
325 // If this redefinition is dead, we need to add a dummy unit live
326 // range covering the def slot.
Evan Cheng6130f662008-03-05 00:59:57 +0000327 if (mi->registerDefIsDead(interval.reg, tri_))
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000328 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000329
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000330 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000331 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000332
333 } else {
334 // Otherwise, this must be because of phi elimination. If this is the
335 // first redefinition of the vreg that we have seen, go back and change
336 // the live range in the PHI block to be a different value number.
337 if (interval.containsOneValue()) {
338 assert(vi.Kills.size() == 1 &&
339 "PHI elimination vreg should have one kill, the PHI itself!");
340
341 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000342 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000343 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000344 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000345 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000346 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000347 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000349 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000350 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000351
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000352 // Replace the interval with one of a NEW value number. Note that this
353 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000354 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000355 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000356 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000357 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000358 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000359 }
360
361 // In the case of PHI elimination, each variable definition is only
362 // live until the end of the block. We've already taken care of the
363 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000364 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000365
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000366 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000367 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000368 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000369 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
370 tii_->isMoveInstr(*mi, SrcReg, DstReg))
371 CopyMI = mi;
372 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000373
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000374 unsigned killIndex = getInstructionIndex(&mbb->back()) + InstrSlots::NUM;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000375 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000376 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000377 interval.addKill(ValNo, killIndex);
378 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000379 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000380 }
381 }
382
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000383 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000384}
385
Chris Lattnerf35fef72004-07-23 21:24:19 +0000386void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000387 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000388 unsigned MIIdx,
Chris Lattner91725b72006-08-31 05:54:43 +0000389 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000390 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000391 // A physical register cannot be live across basic block, so its
392 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000393 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000394
Chris Lattner6b128bd2006-09-03 08:07:11 +0000395 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000396 unsigned start = getDefIndex(baseIndex);
397 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000398
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000399 // If it is not used after definition, it is considered dead at
400 // the instruction defining it. Hence its interval is:
401 // [defSlot(def), defSlot(def)+1)
Evan Cheng6130f662008-03-05 00:59:57 +0000402 if (mi->registerDefIsDead(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000403 DOUT << " dead";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000404 end = getDefIndex(start) + 1;
405 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000406 }
407
408 // If it is not dead on definition, it must be killed by a
409 // subsequent instruction. Hence its interval is:
410 // [defSlot(def), useSlot(kill)+1)
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000411 while (++mi != MBB->end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000412 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000413 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000414 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000415 end = getUseIndex(baseIndex) + 1;
416 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000417 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000418 // Another instruction redefines the register before it is ever read.
419 // Then the register is essentially dead at the instruction that defines
420 // it. Hence its interval is:
421 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000422 DOUT << " dead";
Evan Cheng9a1956a2006-11-15 20:54:11 +0000423 end = getDefIndex(start) + 1;
424 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000425 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000426 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000427
428 // The only case we should have a dead physreg here without a killing or
429 // instruction where we know it's dead is if it is live-in to the function
430 // and never used.
Evan Chengc8d044e2008-02-15 18:24:29 +0000431 assert(!CopyMI && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000432 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000433
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000434exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000435 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000436
Evan Cheng24a3cc42007-04-25 07:30:23 +0000437 // Already exists? Extend old live interval.
438 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000439 VNInfo *ValNo = (OldLR != interval.end())
Evan Chengc8d044e2008-02-15 18:24:29 +0000440 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000441 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000442 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000443 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000444 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000445}
446
Chris Lattnerf35fef72004-07-23 21:24:19 +0000447void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
448 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000449 unsigned MIIdx,
Chris Lattnerf35fef72004-07-23 21:24:19 +0000450 unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000451 if (TargetRegisterInfo::isVirtualRegister(reg))
Chris Lattner6b128bd2006-09-03 08:07:11 +0000452 handleVirtualRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg));
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000453 else if (allocatableRegs_[reg]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000454 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000455 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000456 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
457 tii_->isMoveInstr(*MI, SrcReg, DstReg))
458 CopyMI = MI;
459 handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000460 // Def of a register also defines its sub-registers.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000461 for (const unsigned* AS = tri_->getSubRegisters(reg); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000462 // If MI also modifies the sub-register explicitly, avoid processing it
463 // more than once. Do not pass in TRI here so it checks for exact match.
464 if (!MI->modifiesRegister(*AS))
Evan Cheng24a3cc42007-04-25 07:30:23 +0000465 handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000466 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000467}
468
Evan Chengb371f452007-02-19 21:49:54 +0000469void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000470 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000471 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000472 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
473
474 // Look for kills, if it reaches a def before it's killed, then it shouldn't
475 // be considered a livein.
476 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000477 unsigned baseIndex = MIIdx;
478 unsigned start = baseIndex;
Evan Chengb371f452007-02-19 21:49:54 +0000479 unsigned end = start;
480 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000481 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000482 DOUT << " killed";
483 end = getUseIndex(baseIndex) + 1;
484 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000485 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000486 // Another instruction redefines the register before it is ever read.
487 // Then the register is essentially dead at the instruction that defines
488 // it. Hence its interval is:
489 // [defSlot(def), defSlot(def)+1)
490 DOUT << " dead";
491 end = getDefIndex(start) + 1;
492 goto exit;
493 }
494
495 baseIndex += InstrSlots::NUM;
496 ++mi;
497 }
498
499exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000500 // Live-in register might not be used at all.
501 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000502 if (isAlias) {
503 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000504 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000505 } else {
506 DOUT << " live through";
507 end = baseIndex;
508 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000509 }
510
Evan Chengf3bb2e62007-09-05 21:46:51 +0000511 LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000512 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000513 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000514 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000515}
516
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000517/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000518/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000519/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000520/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000521void LiveIntervals::computeIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000522 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
523 << "********** Function: "
524 << ((Value*)mf_->getFunction())->getName() << '\n';
Chris Lattner6b128bd2006-09-03 08:07:11 +0000525 // Track the index of the current machine instr.
526 unsigned MIIndex = 0;
Chris Lattner428b92e2006-09-15 03:57:23 +0000527 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
528 MBBI != E; ++MBBI) {
529 MachineBasicBlock *MBB = MBBI;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000530 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000531
Chris Lattner428b92e2006-09-15 03:57:23 +0000532 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000533
Dan Gohmancb406c22007-10-03 19:26:29 +0000534 // Create intervals for live-ins to this BB first.
535 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
536 LE = MBB->livein_end(); LI != LE; ++LI) {
537 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
538 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000539 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000540 if (!hasInterval(*AS))
541 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
542 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000543 }
544
Chris Lattner428b92e2006-09-15 03:57:23 +0000545 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000546 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000547
Evan Cheng438f7bc2006-11-10 08:43:01 +0000548 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000549 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
550 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000551 // handle register defs - build intervals
Chris Lattner428b92e2006-09-15 03:57:23 +0000552 if (MO.isRegister() && MO.getReg() && MO.isDef())
553 handleRegisterDef(MBB, MI, MIIndex, MO.getReg());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000554 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000555
556 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000557 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000558 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000559}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000560
Evan Cheng4ca980e2007-10-17 02:10:22 +0000561bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Chenga5bfc972007-10-17 06:53:44 +0000562 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000563 std::vector<IdxMBBPair>::const_iterator I =
564 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
565
566 bool ResVal = false;
567 while (I != Idx2MBBMap.end()) {
568 if (LR.end <= I->first)
569 break;
570 MBBs.push_back(I->second);
571 ResVal = true;
572 ++I;
573 }
574 return ResVal;
575}
576
577
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000578LiveInterval LiveIntervals::createInterval(unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000579 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000580 HUGE_VALF : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000581 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000582}
Evan Chengf2fbca62007-11-12 06:35:08 +0000583
Evan Chengc8d044e2008-02-15 18:24:29 +0000584/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
585/// copy field and returns the source register that defines it.
586unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
587 if (!VNI->copy)
588 return 0;
589
590 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
591 return VNI->copy->getOperand(1).getReg();
592 unsigned SrcReg, DstReg;
593 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
594 return SrcReg;
595 assert(0 && "Unrecognized copy instruction!");
596 return 0;
597}
Evan Chengf2fbca62007-11-12 06:35:08 +0000598
599//===----------------------------------------------------------------------===//
600// Register allocator hooks.
601//
602
Evan Chengd70dbb52008-02-22 09:24:50 +0000603/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
604/// allow one) virtual register operand, then its uses are implicitly using
605/// the register. Returns the virtual register.
606unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
607 MachineInstr *MI) const {
608 unsigned RegOp = 0;
609 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
610 MachineOperand &MO = MI->getOperand(i);
611 if (!MO.isRegister() || !MO.isUse())
612 continue;
613 unsigned Reg = MO.getReg();
614 if (Reg == 0 || Reg == li.reg)
615 continue;
616 // FIXME: For now, only remat MI with at most one register operand.
617 assert(!RegOp &&
618 "Can't rematerialize instruction with multiple register operand!");
619 RegOp = MO.getReg();
620 break;
621 }
622 return RegOp;
623}
624
625/// isValNoAvailableAt - Return true if the val# of the specified interval
626/// which reaches the given instruction also reaches the specified use index.
627bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
628 unsigned UseIdx) const {
629 unsigned Index = getInstructionIndex(MI);
630 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
631 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
632 return UI != li.end() && UI->valno == ValNo;
633}
634
Evan Chengf2fbca62007-11-12 06:35:08 +0000635/// isReMaterializable - Returns true if the definition MI of the specified
636/// val# of the specified interval is re-materializable.
637bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000638 const VNInfo *ValNo, MachineInstr *MI,
639 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000640 if (DisableReMat)
641 return false;
642
Evan Cheng5ef3a042007-12-06 00:01:56 +0000643 isLoad = false;
Chris Lattner749c6f62008-01-07 07:27:27 +0000644 const TargetInstrDesc &TID = MI->getDesc();
Evan Chengd70dbb52008-02-22 09:24:50 +0000645 if (TID.isImplicitDef())
646 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000647
648 int FrameIdx = 0;
649 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000650 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000651 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
652 // this but remember this is not safe to fold into a two-address
653 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000654 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000655 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000656
Evan Chengd70dbb52008-02-22 09:24:50 +0000657 if (tii_->isTriviallyReMaterializable(MI)) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000658 isLoad = TID.isSimpleLoad();
Evan Chengd70dbb52008-02-22 09:24:50 +0000659
660 unsigned ImpUse = getReMatImplicitUse(li, MI);
661 if (ImpUse) {
662 const LiveInterval &ImpLi = getInterval(ImpUse);
663 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
664 re = mri_->use_end(); ri != re; ++ri) {
665 MachineInstr *UseMI = &*ri;
666 unsigned UseIdx = getInstructionIndex(UseMI);
667 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
668 continue;
Evan Cheng298bbe82008-02-23 02:14:42 +0000669 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
Evan Chengd70dbb52008-02-22 09:24:50 +0000670 return false;
671 }
672 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000673 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000674 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000675
Evan Chengdd3465e2008-02-23 01:44:27 +0000676 return false;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000677}
678
679/// isReMaterializable - Returns true if every definition of MI of every
680/// val# of the specified interval is re-materializable.
681bool LiveIntervals::isReMaterializable(const LiveInterval &li, bool &isLoad) {
682 isLoad = false;
683 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
684 i != e; ++i) {
685 const VNInfo *VNI = *i;
686 unsigned DefIdx = VNI->def;
687 if (DefIdx == ~1U)
688 continue; // Dead val#.
689 // Is the def for the val# rematerializable?
690 if (DefIdx == ~0u)
691 return false;
692 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
693 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000694 if (!ReMatDefMI ||
695 !isReMaterializable(li, VNI, ReMatDefMI, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +0000696 return false;
697 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +0000698 }
699 return true;
700}
701
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000702/// FilterFoldedOps - Filter out two-address use operands. Return
703/// true if it finds any issue with the operands that ought to prevent
704/// folding.
705static bool FilterFoldedOps(MachineInstr *MI,
706 SmallVector<unsigned, 2> &Ops,
707 unsigned &MRInfo,
708 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000709 const TargetInstrDesc &TID = MI->getDesc();
Evan Cheng6e141fd2007-12-12 23:12:09 +0000710
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000711 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +0000712 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
713 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +0000714 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +0000715 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +0000716 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000717 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +0000718 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +0000719 MRInfo |= (unsigned)VirtRegMap::isMod;
720 else {
721 // Filter out two-address use operand(s).
Evan Chengd70dbb52008-02-22 09:24:50 +0000722 if (!MO.isImplicit() &&
723 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengaee4af62007-12-02 08:30:39 +0000724 MRInfo = VirtRegMap::isModRef;
725 continue;
726 }
727 MRInfo |= (unsigned)VirtRegMap::isRef;
728 }
729 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +0000730 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000731 return false;
732}
733
734
735/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
736/// slot / to reg or any rematerialized load into ith operand of specified
737/// MI. If it is successul, MI is updated with the newly created MI and
738/// returns true.
739bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
740 VirtRegMap &vrm, MachineInstr *DefMI,
741 unsigned InstrIdx,
742 SmallVector<unsigned, 2> &Ops,
743 bool isSS, int Slot, unsigned Reg) {
744 const TargetInstrDesc &TID = MI->getDesc();
745 // If it is an implicit def instruction, just delete it.
746 if (TID.isImplicitDef()) {
747 RemoveMachineInstrFromMaps(MI);
748 vrm.RemoveMachineInstrFromMaps(MI);
749 MI->eraseFromParent();
750 ++numFolds;
751 return true;
752 }
753
754 // Filter the list of operand indexes that are to be folded. Abort if
755 // any operand will prevent folding.
756 unsigned MRInfo = 0;
757 SmallVector<unsigned, 2> FoldOps;
758 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
759 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +0000760
Evan Cheng249ded32008-02-23 03:38:34 +0000761 // Can't fold a load from fixed stack slot into a two address instruction.
762 if (isSS && DefMI && (MRInfo & VirtRegMap::isMod))
763 return false;
764
Evan Chengf2f8c2a2008-02-08 22:05:27 +0000765 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
766 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +0000767 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +0000768 // Remember this instruction uses the spill slot.
769 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
770
Evan Chengf2fbca62007-11-12 06:35:08 +0000771 // Attempt to fold the memory reference into the instruction. If
772 // we can do this, we don't need to insert spill code.
773 if (lv_)
774 lv_->instructionChanged(MI, fmi);
Evan Cheng81a03822007-11-17 00:40:40 +0000775 else
Dan Gohman6f0d0242008-02-10 18:45:23 +0000776 fmi->copyKillDeadInfo(MI, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +0000777 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +0000778 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +0000779 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +0000780 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000781 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +0000782 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +0000783 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +0000784 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
785 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +0000786 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000787 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +0000788 return true;
789 }
790 return false;
791}
792
Evan Cheng018f9b02007-12-05 03:22:34 +0000793/// canFoldMemoryOperand - Returns true if the specified load / store
794/// folding is possible.
795bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000796 SmallVector<unsigned, 2> &Ops,
Evan Chenge83a2752008-02-25 19:24:01 +0000797 bool ReMatLoad) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000798 // Filter the list of operand indexes that are to be folded. Abort if
799 // any operand will prevent folding.
800 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +0000801 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000802 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
803 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +0000804
Evan Chenge83a2752008-02-25 19:24:01 +0000805 // Can't fold a remat'ed load into a two address instruction.
806 if (ReMatLoad && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000807 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +0000808
Evan Chengd70dbb52008-02-22 09:24:50 +0000809 return tii_->canFoldMemoryOperand(MI, FoldOps);
810}
811
Evan Cheng81a03822007-11-17 00:40:40 +0000812bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
813 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
814 for (LiveInterval::Ranges::const_iterator
815 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
816 std::vector<IdxMBBPair>::const_iterator II =
817 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
818 if (II == Idx2MBBMap.end())
819 continue;
820 if (I->end > II->first) // crossing a MBB.
821 return false;
822 MBBs.insert(II->second);
823 if (MBBs.size() > 1)
824 return false;
825 }
826 return true;
827}
828
Evan Chengd70dbb52008-02-22 09:24:50 +0000829/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
830/// interval on to-be re-materialized operands of MI) with new register.
831void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
832 MachineInstr *MI, unsigned NewVReg,
833 VirtRegMap &vrm) {
834 // There is an implicit use. That means one of the other operand is
835 // being remat'ed and the remat'ed instruction has li.reg as an
836 // use operand. Make sure we rewrite that as well.
837 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
838 MachineOperand &MO = MI->getOperand(i);
839 if (!MO.isRegister())
840 continue;
841 unsigned Reg = MO.getReg();
842 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
843 continue;
844 if (!vrm.isReMaterialized(Reg))
845 continue;
846 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +0000847 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
848 if (UseMO)
849 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +0000850 }
851}
852
Evan Chengf2fbca62007-11-12 06:35:08 +0000853/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
854/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +0000855bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +0000856rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
857 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +0000858 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +0000859 unsigned Slot, int LdSlot,
860 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +0000861 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +0000862 const TargetRegisterClass* rc,
863 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +0000864 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +0000865 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Evan Cheng1953d0c2007-11-29 10:12:14 +0000866 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Chengf2fbca62007-11-12 06:35:08 +0000867 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng018f9b02007-12-05 03:22:34 +0000868 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +0000869 RestartInstruction:
870 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
871 MachineOperand& mop = MI->getOperand(i);
872 if (!mop.isRegister())
873 continue;
874 unsigned Reg = mop.getReg();
875 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000876 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +0000877 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +0000878 if (Reg != li.reg)
879 continue;
880
881 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +0000882 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +0000883 int FoldSlot = Slot;
884 if (DefIsReMat) {
885 // If this is the rematerializable definition MI itself and
886 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +0000887 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +0000888 DOUT << "\t\t\t\tErasing re-materlizable def: ";
889 DOUT << MI << '\n';
Evan Chengd70dbb52008-02-22 09:24:50 +0000890 unsigned ImpUse = getReMatImplicitUse(li, MI);
891 if (ImpUse) {
892 // To be deleted MI has a virtual register operand, update the
893 // spill weight of the register interval.
894 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
895 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng313d4b82008-02-23 00:33:04 +0000896 ImpLi.weight -=
897 getSpillWeight(false, true, loopDepth) / ImpLi.getSize();
Evan Chengd70dbb52008-02-22 09:24:50 +0000898 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000899 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +0000900 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +0000901 MI->eraseFromParent();
902 break;
903 }
904
905 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +0000906 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +0000907 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +0000908 if (isLoad) {
909 // Try fold loads (from stack slot, constant pool, etc.) into uses.
910 FoldSS = isLoadSS;
911 FoldSlot = LdSlot;
912 }
913 }
914
Evan Chengf2fbca62007-11-12 06:35:08 +0000915 // Scan all of the operands of this instruction rewriting operands
916 // to use NewVReg instead of li.reg as appropriate. We do this for
917 // two reasons:
918 //
919 // 1. If the instr reads the same spilled vreg multiple times, we
920 // want to reuse the NewVReg.
921 // 2. If the instr is a two-addr instruction, we are required to
922 // keep the src/dst regs pinned.
923 //
924 // Keep track of whether we replace a use and/or def so that we can
925 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +0000926
Evan Cheng81a03822007-11-17 00:40:40 +0000927 HasUse = mop.isUse();
928 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +0000929 SmallVector<unsigned, 2> Ops;
930 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +0000931 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +0000932 const MachineOperand &MOj = MI->getOperand(j);
933 if (!MOj.isRegister())
Evan Chengf2fbca62007-11-12 06:35:08 +0000934 continue;
Evan Chengaee4af62007-12-02 08:30:39 +0000935 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +0000936 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +0000937 continue;
938 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +0000939 Ops.push_back(j);
940 HasUse |= MOj.isUse();
941 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +0000942 }
943 }
944
Evan Cheng018f9b02007-12-05 03:22:34 +0000945 if (TryFold) {
946 // Do not fold load / store here if we are splitting. We'll find an
947 // optimal point to insert a load / store later.
948 if (!TrySplit) {
949 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
950 Ops, FoldSS, FoldSlot, Reg)) {
951 // Folding the load/store can completely change the instruction in
952 // unpredictable ways, rescan it from the beginning.
953 HasUse = false;
954 HasDef = false;
955 CanFold = false;
956 goto RestartInstruction;
957 }
958 } else {
Evan Chenge83a2752008-02-25 19:24:01 +0000959 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat && isLoad);
Evan Cheng018f9b02007-12-05 03:22:34 +0000960 }
Evan Cheng6e141fd2007-12-12 23:12:09 +0000961 } else
962 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +0000963
964 // Create a new virtual register for the spill interval.
965 bool CreatedNewVReg = false;
966 if (NewVReg == 0) {
Evan Chengd70dbb52008-02-22 09:24:50 +0000967 NewVReg = mri_->createVirtualRegister(rc);
Evan Chengcddbb832007-11-30 21:23:43 +0000968 vrm.grow();
969 CreatedNewVReg = true;
970 }
971 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +0000972 if (mop.isImplicit())
973 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +0000974
975 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +0000976 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
977 MachineOperand &mopj = MI->getOperand(Ops[j]);
978 mopj.setReg(NewVReg);
979 if (mopj.isImplicit())
980 rewriteImplicitOps(li, MI, NewVReg, vrm);
981 }
Evan Chengcddbb832007-11-30 21:23:43 +0000982
Evan Cheng81a03822007-11-17 00:40:40 +0000983 if (CreatedNewVReg) {
984 if (DefIsReMat) {
985 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +0000986 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +0000987 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +0000988 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +0000989 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +0000990 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +0000991 }
992 if (!CanDelete || (HasUse && HasDef)) {
993 // If this is a two-addr instruction then its use operands are
994 // rematerializable but its def is not. It should be assigned a
995 // stack slot.
996 vrm.assignVirt2StackSlot(NewVReg, Slot);
997 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000998 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +0000999 vrm.assignVirt2StackSlot(NewVReg, Slot);
1000 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001001 } else if (HasUse && HasDef &&
1002 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1003 // If this interval hasn't been assigned a stack slot (because earlier
1004 // def is a deleted remat def), do it now.
1005 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1006 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001007 }
1008
Evan Cheng313d4b82008-02-23 00:33:04 +00001009 // Re-matting an instruction with virtual register use. Add the
1010 // register as an implicit use on the use MI.
1011 if (DefIsReMat && ImpUse)
1012 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1013
Evan Chengf2fbca62007-11-12 06:35:08 +00001014 // create a new register interval for this spill / remat.
1015 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001016 if (CreatedNewVReg) {
1017 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001018 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001019 if (TrySplit)
1020 vrm.setIsSplitFromReg(NewVReg, li.reg);
1021 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001022
1023 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001024 if (CreatedNewVReg) {
1025 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1026 nI.getNextValue(~0U, 0, VNInfoAllocator));
1027 DOUT << " +" << LR;
1028 nI.addRange(LR);
1029 } else {
1030 // Extend the split live interval to this def / use.
1031 unsigned End = getUseIndex(index)+1;
1032 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1033 nI.getValNumInfo(nI.getNumValNums()-1));
1034 DOUT << " +" << LR;
1035 nI.addRange(LR);
1036 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001037 }
1038 if (HasDef) {
1039 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1040 nI.getNextValue(~0U, 0, VNInfoAllocator));
1041 DOUT << " +" << LR;
1042 nI.addRange(LR);
1043 }
Evan Cheng81a03822007-11-17 00:40:40 +00001044
Evan Chengf2fbca62007-11-12 06:35:08 +00001045 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001046 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001047 DOUT << '\n';
1048 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001049 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001050}
Evan Cheng81a03822007-11-17 00:40:40 +00001051bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001052 const VNInfo *VNI,
1053 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001054 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001055 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1056 unsigned KillIdx = VNI->kills[j];
1057 if (KillIdx > Idx && KillIdx < End)
1058 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001059 }
1060 return false;
1061}
1062
Evan Cheng1953d0c2007-11-29 10:12:14 +00001063static const VNInfo *findDefinedVNInfo(const LiveInterval &li, unsigned DefIdx) {
1064 const VNInfo *VNI = NULL;
1065 for (LiveInterval::const_vni_iterator i = li.vni_begin(),
1066 e = li.vni_end(); i != e; ++i)
1067 if ((*i)->def == DefIdx) {
1068 VNI = *i;
1069 break;
1070 }
1071 return VNI;
1072}
1073
Evan Cheng063284c2008-02-21 00:34:19 +00001074/// RewriteInfo - Keep track of machine instrs that will be rewritten
1075/// during spilling.
1076struct RewriteInfo {
1077 unsigned Index;
1078 MachineInstr *MI;
1079 bool HasUse;
1080 bool HasDef;
1081 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1082 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1083};
1084
1085struct RewriteInfoCompare {
1086 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1087 return LHS.Index < RHS.Index;
1088 }
1089};
1090
Evan Chengf2fbca62007-11-12 06:35:08 +00001091void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001092rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001093 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001094 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001095 unsigned Slot, int LdSlot,
1096 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001097 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001098 const TargetRegisterClass* rc,
1099 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001100 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001101 BitVector &SpillMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001102 std::map<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001103 BitVector &RestoreMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001104 std::map<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1105 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Chengf2fbca62007-11-12 06:35:08 +00001106 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001107 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001108 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001109 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001110 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001111
Evan Cheng063284c2008-02-21 00:34:19 +00001112 // First collect all the def / use in this live range that will be rewritten.
1113 // Make sure they are sorted according instruction index.
1114 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001115 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1116 re = mri_->reg_end(); ri != re; ) {
Evan Cheng063284c2008-02-21 00:34:19 +00001117 MachineInstr *MI = &(*ri);
1118 MachineOperand &O = ri.getOperand();
1119 ++ri;
1120 unsigned index = getInstructionIndex(MI);
1121 if (index < start || index >= end)
1122 continue;
1123 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1124 }
1125 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1126
Evan Cheng313d4b82008-02-23 00:33:04 +00001127 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001128 // Now rewrite the defs and uses.
1129 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1130 RewriteInfo &rwi = RewriteMIs[i];
1131 ++i;
1132 unsigned index = rwi.Index;
1133 bool MIHasUse = rwi.HasUse;
1134 bool MIHasDef = rwi.HasDef;
1135 MachineInstr *MI = rwi.MI;
1136 // If MI def and/or use the same register multiple times, then there
1137 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001138 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001139 while (i != e && RewriteMIs[i].MI == MI) {
1140 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001141 bool isUse = RewriteMIs[i].HasUse;
1142 if (isUse) ++NumUses;
1143 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001144 MIHasDef |= RewriteMIs[i].HasDef;
1145 ++i;
1146 }
Evan Cheng81a03822007-11-17 00:40:40 +00001147 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001148
1149 if (ImpUse && MI != ReMatDefMI) {
1150 // Re-matting an instruction with virtual register use. Update the
1151 // register interval's spill weight.
1152 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
1153 LiveInterval &ImpLi = getInterval(ImpUse);
1154 ImpLi.weight +=
1155 getSpillWeight(false, true, loopDepth) * NumUses / ImpLi.getSize();
1156 }
1157
Evan Cheng063284c2008-02-21 00:34:19 +00001158 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001159 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001160 if (TrySplit) {
Evan Cheng063284c2008-02-21 00:34:19 +00001161 std::map<unsigned,unsigned>::const_iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001162 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001163 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001164 // One common case:
1165 // x = use
1166 // ...
1167 // ...
1168 // def = ...
1169 // = use
1170 // It's better to start a new interval to avoid artifically
1171 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001172 if (MIHasDef && !MIHasUse) {
1173 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001174 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001175 }
1176 }
Evan Chengcada2452007-11-28 01:28:46 +00001177 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001178
1179 bool IsNew = ThisVReg == 0;
1180 if (IsNew) {
1181 // This ends the previous live interval. If all of its def / use
1182 // can be folded, give it a low spill weight.
1183 if (NewVReg && TrySplit && AllCanFold) {
1184 LiveInterval &nI = getOrCreateInterval(NewVReg);
1185 nI.weight /= 10.0F;
1186 }
1187 AllCanFold = true;
1188 }
1189 NewVReg = ThisVReg;
1190
Evan Cheng81a03822007-11-17 00:40:40 +00001191 bool HasDef = false;
1192 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001193 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng018f9b02007-12-05 03:22:34 +00001194 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1195 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001196 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
Evan Cheng313d4b82008-02-23 00:33:04 +00001197 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001198 if (!HasDef && !HasUse)
1199 continue;
1200
Evan Cheng018f9b02007-12-05 03:22:34 +00001201 AllCanFold &= CanFold;
1202
Evan Cheng81a03822007-11-17 00:40:40 +00001203 // Update weight of spill interval.
1204 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001205 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001206 // The spill weight is now infinity as it cannot be spilled again.
1207 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001208 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001209 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001210
1211 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001212 if (HasDef) {
1213 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001214 bool HasKill = false;
1215 if (!HasUse)
1216 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1217 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001218 // If this is a two-address code, then this index starts a new VNInfo.
1219 const VNInfo *VNI = findDefinedVNInfo(li, getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001220 if (VNI)
1221 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1222 }
Evan Chenge3110d02007-12-01 04:42:39 +00001223 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
1224 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001225 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001226 if (SII == SpillIdxes.end()) {
1227 std::vector<SRInfo> S;
1228 S.push_back(SRInfo(index, NewVReg, true));
1229 SpillIdxes.insert(std::make_pair(MBBId, S));
1230 } else if (SII->second.back().vreg != NewVReg) {
1231 SII->second.push_back(SRInfo(index, NewVReg, true));
1232 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001233 // If there is an earlier def and this is a two-address
1234 // instruction, then it's not possible to fold the store (which
1235 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001236 SRInfo &Info = SII->second.back();
1237 Info.index = index;
1238 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001239 }
1240 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001241 } else if (SII != SpillIdxes.end() &&
1242 SII->second.back().vreg == NewVReg &&
1243 (int)index > SII->second.back().index) {
1244 // There is an earlier def that's not killed (must be two-address).
1245 // The spill is no longer needed.
1246 SII->second.pop_back();
1247 if (SII->second.empty()) {
1248 SpillIdxes.erase(MBBId);
1249 SpillMBBs.reset(MBBId);
1250 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001251 }
1252 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001253 }
1254
1255 if (HasUse) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001256 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001257 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001258 if (SII != SpillIdxes.end() &&
1259 SII->second.back().vreg == NewVReg &&
1260 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001261 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001262 SII->second.back().canFold = false;
1263 std::map<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001264 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001265 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001266 // If we are splitting live intervals, only fold if it's the first
1267 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001268 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001269 else if (IsNew) {
1270 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001271 if (RII == RestoreIdxes.end()) {
1272 std::vector<SRInfo> Infos;
1273 Infos.push_back(SRInfo(index, NewVReg, true));
1274 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1275 } else {
1276 RII->second.push_back(SRInfo(index, NewVReg, true));
1277 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001278 RestoreMBBs.set(MBBId);
1279 }
1280 }
1281
1282 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001283 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001284 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001285 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001286
1287 if (NewVReg && TrySplit && AllCanFold) {
1288 // If all of its def / use can be folded, give it a low spill weight.
1289 LiveInterval &nI = getOrCreateInterval(NewVReg);
1290 nI.weight /= 10.0F;
1291 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001292}
1293
Evan Cheng1953d0c2007-11-29 10:12:14 +00001294bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1295 BitVector &RestoreMBBs,
1296 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1297 if (!RestoreMBBs[Id])
1298 return false;
1299 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1300 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1301 if (Restores[i].index == index &&
1302 Restores[i].vreg == vr &&
1303 Restores[i].canFold)
1304 return true;
1305 return false;
1306}
1307
1308void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1309 BitVector &RestoreMBBs,
1310 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1311 if (!RestoreMBBs[Id])
1312 return;
1313 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1314 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1315 if (Restores[i].index == index && Restores[i].vreg)
1316 Restores[i].index = -1;
1317}
Evan Cheng81a03822007-11-17 00:40:40 +00001318
1319
Evan Chengf2fbca62007-11-12 06:35:08 +00001320std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001321addIntervalsForSpills(const LiveInterval &li,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001322 const MachineLoopInfo *loopInfo, VirtRegMap &vrm) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001323 // Since this is called after the analysis is done we don't know if
1324 // LiveVariables is available
1325 lv_ = getAnalysisToUpdate<LiveVariables>();
1326
1327 assert(li.weight != HUGE_VALF &&
1328 "attempt to spill already spilled interval!");
1329
1330 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001331 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001332 DOUT << '\n';
1333
Evan Cheng81a03822007-11-17 00:40:40 +00001334 // Each bit specify whether it a spill is required in the MBB.
1335 BitVector SpillMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001336 std::map<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001337 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001338 std::map<unsigned, std::vector<SRInfo> > RestoreIdxes;
1339 std::map<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001340 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001341 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001342
1343 unsigned NumValNums = li.getNumValNums();
1344 SmallVector<MachineInstr*, 4> ReMatDefs;
1345 ReMatDefs.resize(NumValNums, NULL);
1346 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1347 ReMatOrigDefs.resize(NumValNums, NULL);
1348 SmallVector<int, 4> ReMatIds;
1349 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1350 BitVector ReMatDelete(NumValNums);
1351 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1352
Evan Cheng81a03822007-11-17 00:40:40 +00001353 // Spilling a split live interval. It cannot be split any further. Also,
1354 // it's also guaranteed to be a single val# / range interval.
1355 if (vrm.getPreSplitReg(li.reg)) {
1356 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001357 // Unset the split kill marker on the last use.
1358 unsigned KillIdx = vrm.getKillPoint(li.reg);
1359 if (KillIdx) {
1360 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1361 assert(KillMI && "Last use disappeared?");
1362 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1363 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001364 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001365 }
Evan Chengadf85902007-12-05 09:51:10 +00001366 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001367 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1368 Slot = vrm.getStackSlot(li.reg);
1369 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1370 MachineInstr *ReMatDefMI = DefIsReMat ?
1371 vrm.getReMaterializedMI(li.reg) : NULL;
1372 int LdSlot = 0;
1373 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1374 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001375 (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001376 bool IsFirstRange = true;
1377 for (LiveInterval::Ranges::const_iterator
1378 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1379 // If this is a split live interval with multiple ranges, it means there
1380 // are two-address instructions that re-defined the value. Only the
1381 // first def can be rematerialized!
1382 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001383 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001384 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1385 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001386 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001387 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001388 MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001389 } else {
1390 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1391 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001392 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001393 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001394 MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001395 }
1396 IsFirstRange = false;
1397 }
1398 return NewLIs;
1399 }
1400
1401 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001402 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1403 TrySplit = false;
1404 if (TrySplit)
1405 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001406 bool NeedStackSlot = false;
1407 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1408 i != e; ++i) {
1409 const VNInfo *VNI = *i;
1410 unsigned VN = VNI->id;
1411 unsigned DefIdx = VNI->def;
1412 if (DefIdx == ~1U)
1413 continue; // Dead val#.
1414 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001415 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1416 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001417 bool dummy;
1418 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001419 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001420 ReMatOrigDefs[VN] = ReMatDefMI;
Evan Chengf2fbca62007-11-12 06:35:08 +00001421 // Original def may be modified so we have to make a copy here. vrm must
1422 // delete these!
Evan Cheng81a03822007-11-17 00:40:40 +00001423 ReMatDefs[VN] = ReMatDefMI = ReMatDefMI->clone();
Evan Chengf2fbca62007-11-12 06:35:08 +00001424
1425 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001426 if (VNI->hasPHIKill) {
1427 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001428 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001429 CanDelete = false;
1430 // Need a stack slot if there is any live range where uses cannot be
1431 // rematerialized.
1432 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001433 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001434 if (CanDelete)
1435 ReMatDelete.set(VN);
1436 } else {
1437 // Need a stack slot if there is any live range where uses cannot be
1438 // rematerialized.
1439 NeedStackSlot = true;
1440 }
1441 }
1442
1443 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001444 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001445 Slot = vrm.assignVirt2StackSlot(li.reg);
1446
1447 // Create new intervals and rewrite defs and uses.
1448 for (LiveInterval::Ranges::const_iterator
1449 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001450 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1451 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1452 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001453 bool CanDelete = ReMatDelete[I->valno->id];
1454 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001455 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001456 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001457 (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001458 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001459 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001460 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001461 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001462 MBBVRegsMap, NewLIs);
Evan Chengf2fbca62007-11-12 06:35:08 +00001463 }
1464
Evan Cheng0cbb1162007-11-29 01:06:25 +00001465 // Insert spills / restores if we are splitting.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001466 if (!TrySplit)
1467 return NewLIs;
1468
Evan Chengb50bb8c2007-12-05 08:16:32 +00001469 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001470 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001471 if (NeedStackSlot) {
1472 int Id = SpillMBBs.find_first();
1473 while (Id != -1) {
1474 std::vector<SRInfo> &spills = SpillIdxes[Id];
1475 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1476 int index = spills[i].index;
1477 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001478 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001479 bool isReMat = vrm.isReMaterialized(VReg);
1480 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001481 bool CanFold = false;
1482 bool FoundUse = false;
1483 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001484 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001485 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001486 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1487 MachineOperand &MO = MI->getOperand(j);
1488 if (!MO.isRegister() || MO.getReg() != VReg)
1489 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001490
1491 Ops.push_back(j);
1492 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001493 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001494 if (isReMat ||
1495 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1496 RestoreMBBs, RestoreIdxes))) {
1497 // MI has two-address uses of the same register. If the use
1498 // isn't the first and only use in the BB, then we can't fold
1499 // it. FIXME: Move this to rewriteInstructionsForSpills.
1500 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001501 break;
1502 }
Evan Chengaee4af62007-12-02 08:30:39 +00001503 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001504 }
1505 }
1506 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001507 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001508 if (CanFold && !Ops.empty()) {
1509 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001510 Folded = true;
Evan Chengf38d14f2007-12-05 09:05:34 +00001511 if (FoundUse > 0) {
Evan Chengaee4af62007-12-02 08:30:39 +00001512 // Also folded uses, do not issue a load.
1513 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00001514 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
1515 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001516 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00001517 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001518 }
1519
Evan Chengaee4af62007-12-02 08:30:39 +00001520 // Else tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00001521 if (!Folded) {
1522 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
1523 bool isKill = LR->end == getStoreIndex(index);
1524 vrm.addSpillPoint(VReg, isKill, MI);
1525 if (isKill)
1526 AddedKill.insert(&nI);
1527 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001528 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001529 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001530 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001531 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001532
Evan Cheng1953d0c2007-11-29 10:12:14 +00001533 int Id = RestoreMBBs.find_first();
1534 while (Id != -1) {
1535 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1536 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
1537 int index = restores[i].index;
1538 if (index == -1)
1539 continue;
1540 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001541 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001542 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001543 bool CanFold = false;
1544 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001545 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001546 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001547 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1548 MachineOperand &MO = MI->getOperand(j);
1549 if (!MO.isRegister() || MO.getReg() != VReg)
1550 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001551
Evan Cheng0cbb1162007-11-29 01:06:25 +00001552 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00001553 // If this restore were to be folded, it would have been folded
1554 // already.
1555 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00001556 break;
1557 }
Evan Chengaee4af62007-12-02 08:30:39 +00001558 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00001559 }
1560 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001561
1562 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001563 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001564 if (CanFold && !Ops.empty()) {
1565 if (!vrm.isReMaterialized(VReg))
1566 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
1567 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001568 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
1569 int LdSlot = 0;
1570 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1571 // If the rematerializable def is a load, also try to fold it.
Chris Lattner749c6f62008-01-07 07:27:27 +00001572 if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00001573 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1574 Ops, isLoadSS, LdSlot, VReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001575 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
1576 if (ImpUse) {
1577 // Re-matting an instruction with virtual register use. Add the
1578 // register as an implicit use on the use MI and update the register
1579 // interval's spill weight.
1580 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
1581 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng313d4b82008-02-23 00:33:04 +00001582 ImpLi.weight +=
1583 getSpillWeight(false, true, loopDepth) / ImpLi.getSize();
1584
Evan Chengd70dbb52008-02-22 09:24:50 +00001585 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1586 }
Evan Chengaee4af62007-12-02 08:30:39 +00001587 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001588 }
1589 // If folding is not possible / failed, then tell the spiller to issue a
1590 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00001591 if (Folded)
1592 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001593 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00001594 vrm.addRestorePoint(VReg, MI);
Evan Cheng81a03822007-11-17 00:40:40 +00001595 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001596 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00001597 }
1598
Evan Chengb50bb8c2007-12-05 08:16:32 +00001599 // Finalize intervals: add kills, finalize spill weights, and filter out
1600 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00001601 std::vector<LiveInterval*> RetNewLIs;
1602 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
1603 LiveInterval *LI = NewLIs[i];
1604 if (!LI->empty()) {
1605 LI->weight /= LI->getSize();
Evan Chengb50bb8c2007-12-05 08:16:32 +00001606 if (!AddedKill.count(LI)) {
1607 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00001608 unsigned LastUseIdx = getBaseIndex(LR->end);
1609 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00001610 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001611 assert(UseIdx != -1);
Evan Chengd70dbb52008-02-22 09:24:50 +00001612 if (LastUse->getOperand(UseIdx).isImplicit() ||
1613 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chengb50bb8c2007-12-05 08:16:32 +00001614 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00001615 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00001616 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00001617 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001618 RetNewLIs.push_back(LI);
1619 }
1620 }
Evan Cheng81a03822007-11-17 00:40:40 +00001621
Evan Cheng597d10d2007-12-04 00:32:23 +00001622 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00001623}
Evan Cheng676dd7c2008-03-11 07:19:34 +00001624
1625/// hasAllocatableSuperReg - Return true if the specified physical register has
1626/// any super register that's allocatable.
1627bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
1628 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
1629 if (allocatableRegs_[*AS] && hasInterval(*AS))
1630 return true;
1631 return false;
1632}
1633
1634/// getRepresentativeReg - Find the largest super register of the specified
1635/// physical register.
1636unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
1637 // Find the largest super-register that is allocatable.
1638 unsigned BestReg = Reg;
1639 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
1640 unsigned SuperReg = *AS;
1641 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
1642 BestReg = SuperReg;
1643 break;
1644 }
1645 }
1646 return BestReg;
1647}
1648
1649/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
1650/// specified interval that conflicts with the specified physical register.
1651unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
1652 unsigned PhysReg) const {
1653 unsigned NumConflicts = 0;
1654 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
1655 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1656 E = mri_->reg_end(); I != E; ++I) {
1657 MachineOperand &O = I.getOperand();
1658 MachineInstr *MI = O.getParent();
1659 unsigned Index = getInstructionIndex(MI);
1660 if (pli.liveAt(Index))
1661 ++NumConflicts;
1662 }
1663 return NumConflicts;
1664}
1665
1666/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
1667/// around all defs and uses of the specified interval.
1668void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
1669 unsigned PhysReg, VirtRegMap &vrm) {
1670 unsigned SpillReg = getRepresentativeReg(PhysReg);
1671
1672 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
1673 // If there are registers which alias PhysReg, but which are not a
1674 // sub-register of the chosen representative super register. Assert
1675 // since we can't handle it yet.
1676 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
1677 tri_->isSuperRegister(*AS, SpillReg));
1678
1679 LiveInterval &pli = getInterval(SpillReg);
1680 SmallPtrSet<MachineInstr*, 8> SeenMIs;
1681 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1682 E = mri_->reg_end(); I != E; ++I) {
1683 MachineOperand &O = I.getOperand();
1684 MachineInstr *MI = O.getParent();
1685 if (SeenMIs.count(MI))
1686 continue;
1687 SeenMIs.insert(MI);
1688 unsigned Index = getInstructionIndex(MI);
1689 if (pli.liveAt(Index)) {
1690 vrm.addEmergencySpill(SpillReg, MI);
1691 pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1692 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
1693 if (!hasInterval(*AS))
1694 continue;
1695 LiveInterval &spli = getInterval(*AS);
1696 if (spli.liveAt(Index))
1697 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1698 }
1699 }
1700 }
1701}