blob: 0d4ec11266e15b91afca7c9c8c06778abbc4570b [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
Jakob Stoklund Olesen4281e202012-01-07 07:39:47 +000018#define DEBUG_TYPE "regalloc"
Chris Lattner3c3fe462005-09-21 04:19:09 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "LiveRangeCalc.h"
21#include "llvm/ADT/DenseSet.h"
22#include "llvm/ADT/STLExtras.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000023#include "llvm/Analysis/AliasAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/CodeGen/LiveVariables.h"
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +000025#include "llvm/CodeGen/MachineDominators.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000026#include "llvm/CodeGen/MachineInstr.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000028#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000029#include "llvm/CodeGen/VirtRegMap.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/Value.h"
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +000031#include "llvm/Support/CommandLine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000035#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000038#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000039#include <cmath>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000040#include <limits>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000041using namespace llvm;
42
Devang Patel19974732007-05-03 01:11:54 +000043char LiveIntervals::ID = 0;
Jakob Stoklund Olesendcc44362012-08-03 22:12:54 +000044char &llvm::LiveIntervalsID = LiveIntervals::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +000045INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
46 "Live Interval Analysis", false, false)
Andrew Trick8dd26252012-02-10 04:10:36 +000047INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Owen Anderson2ab36d32010-10-12 19:48:12 +000048INITIALIZE_PASS_DEPENDENCY(LiveVariables)
Andrew Trick8dd26252012-02-10 04:10:36 +000049INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Owen Anderson2ab36d32010-10-12 19:48:12 +000050INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
Owen Anderson2ab36d32010-10-12 19:48:12 +000051INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
Owen Andersonce665bd2010-10-07 22:25:06 +000052 "Live Interval Analysis", false, false)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000053
Chris Lattnerf7da2c72006-08-24 22:43:55 +000054void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000055 AU.setPreservesCFG();
Dan Gohman6d69ba82008-07-25 00:02:30 +000056 AU.addRequired<AliasAnalysis>();
57 AU.addPreserved<AliasAnalysis>();
Jakob Stoklund Olesenec7b25d2013-02-09 00:04:07 +000058 // LiveVariables isn't really required by this analysis, it is only required
59 // here to make sure it is live during TwoAddressInstructionPass and
60 // PHIElimination. This is temporary.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000061 AU.addRequired<LiveVariables>();
Evan Cheng148341c2010-08-17 21:00:37 +000062 AU.addPreserved<LiveVariables>();
Andrew Trickd35576b2012-02-13 20:44:42 +000063 AU.addPreservedID(MachineLoopInfoID);
Jakob Stoklund Olesenc4118452012-06-20 23:31:34 +000064 AU.addRequiredTransitiveID(MachineDominatorsID);
Bill Wendling67d65bb2008-01-04 20:54:55 +000065 AU.addPreservedID(MachineDominatorsID);
Lang Hames233a60e2009-11-03 23:52:08 +000066 AU.addPreserved<SlotIndexes>();
67 AU.addRequiredTransitive<SlotIndexes>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000068 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000069}
70
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +000071LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
72 DomTree(0), LRCalc(0) {
73 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
74}
75
76LiveIntervals::~LiveIntervals() {
77 delete LRCalc;
78}
79
Chris Lattnerf7da2c72006-08-24 22:43:55 +000080void LiveIntervals::releaseMemory() {
Owen Anderson03857b22008-08-13 21:49:13 +000081 // Free the live intervals themselves.
Jakob Stoklund Olesen7fa67842012-06-22 20:37:52 +000082 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
83 delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
84 VirtRegIntervals.clear();
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +000085 RegMaskSlots.clear();
86 RegMaskBits.clear();
Jakob Stoklund Olesen34e85d02012-02-10 01:26:29 +000087 RegMaskBlocks.clear();
Lang Hamesffd13262009-07-09 03:57:02 +000088
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +000089 for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
90 delete RegUnitIntervals[i];
91 RegUnitIntervals.clear();
92
Benjamin Kramerce9a20b2010-06-26 11:30:59 +000093 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
94 VNInfoAllocator.Reset();
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000095}
96
Owen Anderson80b3ce62008-05-28 20:54:50 +000097/// runOnMachineFunction - Register allocate the whole function
98///
99bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000100 MF = &fn;
101 MRI = &MF->getRegInfo();
102 TM = &fn.getTarget();
103 TRI = TM->getRegisterInfo();
104 TII = TM->getInstrInfo();
105 AA = &getAnalysis<AliasAnalysis>();
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000106 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenc4118452012-06-20 23:31:34 +0000107 DomTree = &getAnalysis<MachineDominatorTree>();
108 if (!LRCalc)
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000109 LRCalc = new LiveRangeCalc();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000110
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000111 // Allocate space for all virtual registers.
112 VirtRegIntervals.resize(MRI->getNumVirtRegs());
113
Jakob Stoklund Olesenec7b25d2013-02-09 00:04:07 +0000114 computeVirtRegs();
115 computeRegMasks();
Jakob Stoklund Olesenc4118452012-06-20 23:31:34 +0000116 computeLiveInRegUnits();
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000117
Chris Lattner70ca3582004-09-30 15:59:17 +0000118 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000119 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000120}
121
Chris Lattner70ca3582004-09-30 15:59:17 +0000122/// print - Implement the dump method.
Chris Lattner45cfe542009-08-23 06:03:38 +0000123void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
Chris Lattner705e07f2009-08-23 03:41:05 +0000124 OS << "********** INTERVALS **********\n";
Jakob Stoklund Olesenf658af52012-02-14 23:46:21 +0000125
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000126 // Dump the regunits.
127 for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
128 if (LiveInterval *LI = RegUnitIntervals[i])
129 OS << PrintRegUnit(i, TRI) << " = " << *LI << '\n';
130
Jakob Stoklund Olesenf658af52012-02-14 23:46:21 +0000131 // Dump the virtregs.
Jakob Stoklund Olesen7fa67842012-06-22 20:37:52 +0000132 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
133 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
134 if (hasInterval(Reg))
135 OS << PrintReg(Reg) << " = " << getInterval(Reg) << '\n';
136 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000137
Jakob Stoklund Olesen722c9a72012-11-09 19:18:49 +0000138 OS << "RegMasks:";
139 for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
140 OS << ' ' << RegMaskSlots[i];
141 OS << '\n';
142
Evan Cheng752195e2009-09-14 21:33:42 +0000143 printInstrs(OS);
144}
145
146void LiveIntervals::printInstrs(raw_ostream &OS) const {
Chris Lattner705e07f2009-08-23 03:41:05 +0000147 OS << "********** MACHINEINSTRS **********\n";
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000148 MF->print(OS, Indexes);
Chris Lattner70ca3582004-09-30 15:59:17 +0000149}
150
Manman Renb720be62012-09-11 22:23:19 +0000151#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Evan Cheng752195e2009-09-14 21:33:42 +0000152void LiveIntervals::dumpInstrs() const {
David Greene8a342292010-01-04 22:49:02 +0000153 printInstrs(dbgs());
Evan Cheng752195e2009-09-14 21:33:42 +0000154}
Manman Ren77e300e2012-09-06 19:06:06 +0000155#endif
Evan Cheng752195e2009-09-14 21:33:42 +0000156
Owen Anderson03857b22008-08-13 21:49:13 +0000157LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000158 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
Owen Anderson03857b22008-08-13 21:49:13 +0000159 return new LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000160}
Evan Chengf2fbca62007-11-12 06:35:08 +0000161
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000162
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000163/// computeVirtRegInterval - Compute the live interval of a virtual register,
164/// based on defs and uses.
165void LiveIntervals::computeVirtRegInterval(LiveInterval *LI) {
166 assert(LRCalc && "LRCalc not initialized.");
167 assert(LI->empty() && "Should only compute empty intervals.");
168 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
169 LRCalc->createDeadDefs(LI);
170 LRCalc->extendToUses(LI);
171}
172
Jakob Stoklund Olesenc16bf792012-07-27 21:56:39 +0000173void LiveIntervals::computeVirtRegs() {
174 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
175 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
176 if (MRI->reg_nodbg_empty(Reg))
177 continue;
178 LiveInterval *LI = createInterval(Reg);
179 VirtRegIntervals[Reg] = LI;
180 computeVirtRegInterval(LI);
181 }
182}
183
184void LiveIntervals::computeRegMasks() {
185 RegMaskBlocks.resize(MF->getNumBlockIDs());
186
187 // Find all instructions with regmask operands.
188 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
189 MBBI != E; ++MBBI) {
190 MachineBasicBlock *MBB = MBBI;
191 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
192 RMB.first = RegMaskSlots.size();
193 for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
194 MI != ME; ++MI)
195 for (MIOperands MO(MI); MO.isValid(); ++MO) {
196 if (!MO->isRegMask())
197 continue;
198 RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
199 RegMaskBits.push_back(MO->getRegMask());
200 }
201 // Compute the number of register mask instructions in this block.
Dmitri Gribenko2de05722012-09-10 21:26:47 +0000202 RMB.second = RegMaskSlots.size() - RMB.first;
Jakob Stoklund Olesenc16bf792012-07-27 21:56:39 +0000203 }
204}
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000205
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000206//===----------------------------------------------------------------------===//
207// Register Unit Liveness
208//===----------------------------------------------------------------------===//
209//
210// Fixed interference typically comes from ABI boundaries: Function arguments
211// and return values are passed in fixed registers, and so are exception
212// pointers entering landing pads. Certain instructions require values to be
213// present in specific registers. That is also represented through fixed
214// interference.
215//
216
217/// computeRegUnitInterval - Compute the live interval of a register unit, based
218/// on the uses and defs of aliasing registers. The interval should be empty,
219/// or contain only dead phi-defs from ABI blocks.
220void LiveIntervals::computeRegUnitInterval(LiveInterval *LI) {
221 unsigned Unit = LI->reg;
222
223 assert(LRCalc && "LRCalc not initialized.");
224 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
225
226 // The physregs aliasing Unit are the roots and their super-registers.
227 // Create all values as dead defs before extending to uses. Note that roots
228 // may share super-registers. That's OK because createDeadDefs() is
229 // idempotent. It is very rare for a register unit to have multiple roots, so
230 // uniquing super-registers is probably not worthwhile.
231 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
232 unsigned Root = *Roots;
233 if (!MRI->reg_empty(Root))
234 LRCalc->createDeadDefs(LI, Root);
235 for (MCSuperRegIterator Supers(Root, TRI); Supers.isValid(); ++Supers) {
236 if (!MRI->reg_empty(*Supers))
237 LRCalc->createDeadDefs(LI, *Supers);
238 }
239 }
240
241 // Now extend LI to reach all uses.
242 // Ignore uses of reserved registers. We only track defs of those.
243 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
244 unsigned Root = *Roots;
Jakob Stoklund Olesen79004762012-10-15 22:14:34 +0000245 if (!MRI->isReserved(Root) && !MRI->reg_empty(Root))
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000246 LRCalc->extendToUses(LI, Root);
247 for (MCSuperRegIterator Supers(Root, TRI); Supers.isValid(); ++Supers) {
248 unsigned Reg = *Supers;
Jakob Stoklund Olesen79004762012-10-15 22:14:34 +0000249 if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000250 LRCalc->extendToUses(LI, Reg);
251 }
252 }
253}
254
255
256/// computeLiveInRegUnits - Precompute the live ranges of any register units
257/// that are live-in to an ABI block somewhere. Register values can appear
258/// without a corresponding def when entering the entry block or a landing pad.
259///
260void LiveIntervals::computeLiveInRegUnits() {
261 RegUnitIntervals.resize(TRI->getNumRegUnits());
262 DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
263
264 // Keep track of the intervals allocated.
265 SmallVector<LiveInterval*, 8> NewIntvs;
266
267 // Check all basic blocks for live-ins.
268 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
269 MFI != MFE; ++MFI) {
270 const MachineBasicBlock *MBB = MFI;
271
272 // We only care about ABI blocks: Entry + landing pads.
273 if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
274 continue;
275
276 // Create phi-defs at Begin for all live-in registers.
277 SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
278 DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
279 for (MachineBasicBlock::livein_iterator LII = MBB->livein_begin(),
280 LIE = MBB->livein_end(); LII != LIE; ++LII) {
281 for (MCRegUnitIterator Units(*LII, TRI); Units.isValid(); ++Units) {
282 unsigned Unit = *Units;
283 LiveInterval *Intv = RegUnitIntervals[Unit];
284 if (!Intv) {
285 Intv = RegUnitIntervals[Unit] = new LiveInterval(Unit, HUGE_VALF);
286 NewIntvs.push_back(Intv);
287 }
288 VNInfo *VNI = Intv->createDeadDef(Begin, getVNInfoAllocator());
Matt Beaumont-Gay05b46f02012-06-05 23:00:03 +0000289 (void)VNI;
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000290 DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
291 }
292 }
293 DEBUG(dbgs() << '\n');
294 }
295 DEBUG(dbgs() << "Created " << NewIntvs.size() << " new intervals.\n");
296
297 // Compute the 'normal' part of the intervals.
298 for (unsigned i = 0, e = NewIntvs.size(); i != e; ++i)
299 computeRegUnitInterval(NewIntvs[i]);
300}
301
302
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000303/// shrinkToUses - After removing some uses of a register, shrink its live
304/// range to just the remaining uses. This method does not compute reaching
305/// defs for new uses, and it doesn't remove dead defs.
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000306bool LiveIntervals::shrinkToUses(LiveInterval *li,
Jakob Stoklund Olesen0d8ccaa2011-03-07 23:29:10 +0000307 SmallVectorImpl<MachineInstr*> *dead) {
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000308 DEBUG(dbgs() << "Shrink: " << *li << '\n');
309 assert(TargetRegisterInfo::isVirtualRegister(li->reg)
Lang Hames567cdba2012-01-03 20:05:57 +0000310 && "Can only shrink virtual registers");
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000311 // Find all the values used, including PHI kills.
312 SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
313
Jakob Stoklund Olesen031432f2011-09-15 15:24:16 +0000314 // Blocks that have already been added to WorkList as live-out.
315 SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
316
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000317 // Visit all instructions reading li->reg.
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000318 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(li->reg);
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000319 MachineInstr *UseMI = I.skipInstruction();) {
320 if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
321 continue;
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000322 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
Jakob Stoklund Olesen97769fc2012-05-20 02:54:52 +0000323 LiveRangeQuery LRQ(*li, Idx);
324 VNInfo *VNI = LRQ.valueIn();
Jakob Stoklund Olesen9ef931e2011-03-18 03:06:04 +0000325 if (!VNI) {
326 // This shouldn't happen: readsVirtualRegister returns true, but there is
327 // no live value. It is likely caused by a target getting <undef> flags
328 // wrong.
329 DEBUG(dbgs() << Idx << '\t' << *UseMI
330 << "Warning: Instr claims to read non-existent value in "
331 << *li << '\n');
332 continue;
333 }
Jakob Stoklund Olesenf054e192011-11-14 18:45:38 +0000334 // Special case: An early-clobber tied operand reads and writes the
Jakob Stoklund Olesen97769fc2012-05-20 02:54:52 +0000335 // register one slot early.
336 if (VNInfo *DefVNI = LRQ.valueDefined())
337 Idx = DefVNI->def;
338
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000339 WorkList.push_back(std::make_pair(Idx, VNI));
340 }
341
342 // Create a new live interval with only minimal live segments per def.
343 LiveInterval NewLI(li->reg, 0);
344 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
345 I != E; ++I) {
346 VNInfo *VNI = *I;
347 if (VNI->isUnused())
348 continue;
Jakob Stoklund Olesen1f81e312011-11-13 22:42:13 +0000349 NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000350 }
351
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000352 // Keep track of the PHIs that are in use.
353 SmallPtrSet<VNInfo*, 8> UsedPHIs;
354
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000355 // Extend intervals to reach all uses in WorkList.
356 while (!WorkList.empty()) {
357 SlotIndex Idx = WorkList.back().first;
358 VNInfo *VNI = WorkList.back().second;
359 WorkList.pop_back();
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000360 const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000361 SlotIndex BlockStart = getMBBStartIdx(MBB);
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000362
363 // Extend the live range for VNI to be live at Idx.
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000364 if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
Nick Lewycky4b11a702011-03-02 01:43:30 +0000365 (void)ExtVNI;
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000366 assert(ExtVNI == VNI && "Unexpected existing value number");
367 // Is this a PHIDef we haven't seen before?
Jakob Stoklund Olesenc29d9b32011-03-03 00:20:51 +0000368 if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000369 continue;
370 // The PHI is live, make sure the predecessors are live-out.
371 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
372 PE = MBB->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen031432f2011-09-15 15:24:16 +0000373 if (!LiveOut.insert(*PI))
374 continue;
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000375 SlotIndex Stop = getMBBEndIdx(*PI);
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000376 // A predecessor is not required to have a live-out value for a PHI.
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000377 if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000378 WorkList.push_back(std::make_pair(Stop, PVNI));
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000379 }
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000380 continue;
381 }
382
383 // VNI is live-in to MBB.
384 DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000385 NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000386
387 // Make sure VNI is live-out from the predecessors.
388 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
389 PE = MBB->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen031432f2011-09-15 15:24:16 +0000390 if (!LiveOut.insert(*PI))
391 continue;
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000392 SlotIndex Stop = getMBBEndIdx(*PI);
393 assert(li->getVNInfoBefore(Stop) == VNI &&
394 "Wrong value out of predecessor");
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000395 WorkList.push_back(std::make_pair(Stop, VNI));
396 }
397 }
398
399 // Handle dead values.
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000400 bool CanSeparate = false;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000401 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
402 I != E; ++I) {
403 VNInfo *VNI = *I;
404 if (VNI->isUnused())
405 continue;
406 LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
407 assert(LII != NewLI.end() && "Missing live range for PHI");
Jakob Stoklund Olesen1f81e312011-11-13 22:42:13 +0000408 if (LII->end != VNI->def.getDeadSlot())
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000409 continue;
Jakob Stoklund Olesena4d34732011-03-02 00:33:01 +0000410 if (VNI->isPHIDef()) {
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000411 // This is a dead PHI. Remove it.
Jakob Stoklund Olesenb2beac22012-08-03 20:59:32 +0000412 VNI->markUnused();
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000413 NewLI.removeRange(*LII);
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000414 DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
415 CanSeparate = true;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000416 } else {
417 // This is a dead def. Make sure the instruction knows.
418 MachineInstr *MI = getInstructionFromIndex(VNI->def);
419 assert(MI && "No instruction defining live value");
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000420 MI->addRegisterDead(li->reg, TRI);
Jakob Stoklund Olesen0d8ccaa2011-03-07 23:29:10 +0000421 if (dead && MI->allDefsAreDead()) {
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000422 DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
Jakob Stoklund Olesen0d8ccaa2011-03-07 23:29:10 +0000423 dead->push_back(MI);
424 }
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000425 }
426 }
427
428 // Move the trimmed ranges back.
429 li->ranges.swap(NewLI.ranges);
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000430 DEBUG(dbgs() << "Shrunk: " << *li << '\n');
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000431 return CanSeparate;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000432}
433
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000434void LiveIntervals::extendToIndices(LiveInterval *LI,
435 ArrayRef<SlotIndex> Indices) {
436 assert(LRCalc && "LRCalc not initialized.");
437 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
438 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
439 LRCalc->extend(LI, Indices[i]);
440}
441
442void LiveIntervals::pruneValue(LiveInterval *LI, SlotIndex Kill,
443 SmallVectorImpl<SlotIndex> *EndPoints) {
444 LiveRangeQuery LRQ(*LI, Kill);
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000445 VNInfo *VNI = LRQ.valueOut();
446 if (!VNI)
447 return;
448
449 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
450 SlotIndex MBBStart, MBBEnd;
451 tie(MBBStart, MBBEnd) = Indexes->getMBBRange(KillMBB);
452
453 // If VNI isn't live out from KillMBB, the value is trivially pruned.
454 if (LRQ.endPoint() < MBBEnd) {
455 LI->removeRange(Kill, LRQ.endPoint());
456 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
457 return;
458 }
459
460 // VNI is live out of KillMBB.
461 LI->removeRange(Kill, MBBEnd);
462 if (EndPoints) EndPoints->push_back(MBBEnd);
463
Jakob Stoklund Olesenaf896902012-10-13 16:15:31 +0000464 // Find all blocks that are reachable from KillMBB without leaving VNI's live
465 // range. It is possible that KillMBB itself is reachable, so start a DFS
466 // from each successor.
467 typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
468 VisitedTy Visited;
469 for (MachineBasicBlock::succ_iterator
470 SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
471 SuccI != SuccE; ++SuccI) {
472 for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
473 I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
474 I != E;) {
475 MachineBasicBlock *MBB = *I;
476
477 // Check if VNI is live in to MBB.
478 tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
479 LiveRangeQuery LRQ(*LI, MBBStart);
480 if (LRQ.valueIn() != VNI) {
481 // This block isn't part of the VNI live range. Prune the search.
482 I.skipChildren();
483 continue;
484 }
485
486 // Prune the search if VNI is killed in MBB.
487 if (LRQ.endPoint() < MBBEnd) {
488 LI->removeRange(MBBStart, LRQ.endPoint());
489 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
490 I.skipChildren();
491 continue;
492 }
493
494 // VNI is live through MBB.
495 LI->removeRange(MBBStart, MBBEnd);
496 if (EndPoints) EndPoints->push_back(MBBEnd);
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000497 ++I;
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000498 }
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000499 }
500}
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000501
Evan Chengf2fbca62007-11-12 06:35:08 +0000502//===----------------------------------------------------------------------===//
503// Register allocator hooks.
504//
505
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000506void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
507 // Keep track of regunit ranges.
508 SmallVector<std::pair<LiveInterval*, LiveInterval::iterator>, 8> RU;
509
Jakob Stoklund Olesen12a7be92012-06-20 23:23:59 +0000510 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
511 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000512 if (MRI->reg_nodbg_empty(Reg))
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000513 continue;
Jakob Stoklund Olesen12a7be92012-06-20 23:23:59 +0000514 LiveInterval *LI = &getInterval(Reg);
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000515 if (LI->empty())
516 continue;
517
518 // Find the regunit intervals for the assigned register. They may overlap
519 // the virtual register live range, cancelling any kills.
520 RU.clear();
521 for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
522 ++Units) {
523 LiveInterval *RUInt = &getRegUnit(*Units);
524 if (RUInt->empty())
525 continue;
526 RU.push_back(std::make_pair(RUInt, RUInt->find(LI->begin()->end)));
527 }
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000528
529 // Every instruction that kills Reg corresponds to a live range end point.
530 for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
531 ++RI) {
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000532 // A block index indicates an MBB edge.
533 if (RI->end.isBlock())
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000534 continue;
535 MachineInstr *MI = getInstructionFromIndex(RI->end);
536 if (!MI)
537 continue;
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000538
539 // Check if any of the reguints are live beyond the end of RI. That could
540 // happen when a physreg is defined as a copy of a virtreg:
541 //
542 // %EAX = COPY %vreg5
543 // FOO %vreg5 <--- MI, cancel kill because %EAX is live.
544 // BAR %EAX<kill>
545 //
546 // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
547 bool CancelKill = false;
548 for (unsigned u = 0, e = RU.size(); u != e; ++u) {
549 LiveInterval *RInt = RU[u].first;
550 LiveInterval::iterator &I = RU[u].second;
551 if (I == RInt->end())
552 continue;
553 I = RInt->advanceTo(I, RI->end);
554 if (I == RInt->end() || I->start >= RI->end)
555 continue;
556 // I is overlapping RI.
557 CancelKill = true;
558 break;
559 }
560 if (CancelKill)
561 MI->clearRegisterKills(Reg, NULL);
562 else
563 MI->addRegisterKilled(Reg, NULL);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000564 }
565 }
566}
567
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000568MachineBasicBlock*
569LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
570 // A local live range must be fully contained inside the block, meaning it is
571 // defined and killed at instructions, not at block boundaries. It is not
572 // live in or or out of any block.
573 //
574 // It is technically possible to have a PHI-defined live range identical to a
575 // single block, but we are going to return false in that case.
Lang Hames233a60e2009-11-03 23:52:08 +0000576
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000577 SlotIndex Start = LI.beginIndex();
578 if (Start.isBlock())
579 return NULL;
Lang Hames233a60e2009-11-03 23:52:08 +0000580
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000581 SlotIndex Stop = LI.endIndex();
582 if (Stop.isBlock())
583 return NULL;
Lang Hames233a60e2009-11-03 23:52:08 +0000584
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000585 // getMBBFromIndex doesn't need to search the MBB table when both indexes
586 // belong to proper instructions.
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000587 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
588 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000589 return MBB1 == MBB2 ? MBB1 : NULL;
Evan Cheng81a03822007-11-17 00:40:40 +0000590}
591
Jakob Stoklund Olesen0ab71032012-08-03 20:10:24 +0000592bool
593LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
594 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
595 I != E; ++I) {
596 const VNInfo *PHI = *I;
597 if (PHI->isUnused() || !PHI->isPHIDef())
598 continue;
599 const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
600 // Conservatively return true instead of scanning huge predecessor lists.
601 if (PHIMBB->pred_size() > 100)
602 return true;
603 for (MachineBasicBlock::const_pred_iterator
604 PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
605 if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
606 return true;
607 }
608 return false;
609}
610
Jakob Stoklund Olesene5d90412010-03-01 20:59:38 +0000611float
612LiveIntervals::getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
613 // Limit the loop depth ridiculousness.
614 if (loopDepth > 200)
615 loopDepth = 200;
616
617 // The loop depth is used to roughly estimate the number of times the
618 // instruction is executed. Something like 10^d is simple, but will quickly
619 // overflow a float. This expression behaves like 10^d for small d, but is
620 // more tempered for large d. At d=200 we get 6.7e33 which leaves a bit of
621 // headroom before overflow.
NAKAMURA Takumidc5198b2011-03-31 12:11:33 +0000622 // By the way, powf() might be unavailable here. For consistency,
623 // We may take pow(double,double).
624 float lc = std::pow(1 + (100.0 / (loopDepth + 10)), (double)loopDepth);
Jakob Stoklund Olesene5d90412010-03-01 20:59:38 +0000625
626 return (isDef + isUse) * lc;
627}
628
Owen Andersonc4dc1322008-06-05 17:15:43 +0000629LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
Lang Hamesffd13262009-07-09 03:57:02 +0000630 MachineInstr* startInst) {
Owen Andersonc4dc1322008-06-05 17:15:43 +0000631 LiveInterval& Interval = getOrCreateInterval(reg);
632 VNInfo* VN = Interval.getNextValue(
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000633 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000634 getVNInfoAllocator());
Lang Hames86511252009-09-04 20:41:11 +0000635 LiveRange LR(
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000636 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
Lang Hames74ab5ee2009-12-22 00:11:50 +0000637 getMBBEndIdx(startInst->getParent()), VN);
Owen Andersonc4dc1322008-06-05 17:15:43 +0000638 Interval.addRange(LR);
Jakob Stoklund Olesen1b293202010-08-12 20:01:23 +0000639
Owen Andersonc4dc1322008-06-05 17:15:43 +0000640 return LR;
641}
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000642
643
644//===----------------------------------------------------------------------===//
645// Register mask functions
646//===----------------------------------------------------------------------===//
647
648bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
649 BitVector &UsableRegs) {
650 if (LI.empty())
651 return false;
Jakob Stoklund Olesen9f10ac62012-02-10 01:31:31 +0000652 LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
653
654 // Use a smaller arrays for local live ranges.
655 ArrayRef<SlotIndex> Slots;
656 ArrayRef<const uint32_t*> Bits;
657 if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
658 Slots = getRegMaskSlotsInBlock(MBB->getNumber());
659 Bits = getRegMaskBitsInBlock(MBB->getNumber());
660 } else {
661 Slots = getRegMaskSlots();
662 Bits = getRegMaskBits();
663 }
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000664
665 // We are going to enumerate all the register mask slots contained in LI.
666 // Start with a binary search of RegMaskSlots to find a starting point.
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000667 ArrayRef<SlotIndex>::iterator SlotI =
668 std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
669 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
670
671 // No slots in range, LI begins after the last call.
672 if (SlotI == SlotE)
673 return false;
674
675 bool Found = false;
676 for (;;) {
677 assert(*SlotI >= LiveI->start);
678 // Loop over all slots overlapping this segment.
679 while (*SlotI < LiveI->end) {
680 // *SlotI overlaps LI. Collect mask bits.
681 if (!Found) {
682 // This is the first overlap. Initialize UsableRegs to all ones.
683 UsableRegs.clear();
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000684 UsableRegs.resize(TRI->getNumRegs(), true);
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000685 Found = true;
686 }
687 // Remove usable registers clobbered by this mask.
Jakob Stoklund Olesen9f10ac62012-02-10 01:31:31 +0000688 UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000689 if (++SlotI == SlotE)
690 return Found;
691 }
692 // *SlotI is beyond the current LI segment.
693 LiveI = LI.advanceTo(LiveI, *SlotI);
694 if (LiveI == LiveE)
695 return Found;
696 // Advance SlotI until it overlaps.
697 while (*SlotI < LiveI->start)
698 if (++SlotI == SlotE)
699 return Found;
700 }
701}
Lang Hames3dc7c512012-02-17 18:44:18 +0000702
703//===----------------------------------------------------------------------===//
704// IntervalUpdate class.
705//===----------------------------------------------------------------------===//
706
Lang Hamesfd6d3212012-02-21 00:00:36 +0000707// HMEditor is a toolkit used by handleMove to trim or extend live intervals.
Lang Hames3dc7c512012-02-17 18:44:18 +0000708class LiveIntervals::HMEditor {
709private:
Lang Hamesecb50622012-02-17 23:43:40 +0000710 LiveIntervals& LIS;
711 const MachineRegisterInfo& MRI;
712 const TargetRegisterInfo& TRI;
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000713 SlotIndex OldIdx;
Lang Hamesecb50622012-02-17 23:43:40 +0000714 SlotIndex NewIdx;
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000715 SmallPtrSet<LiveInterval*, 8> Updated;
Andrew Trick27c28ce2012-10-16 00:22:51 +0000716 bool UpdateFlags;
Lang Hames6aceab12012-02-19 07:13:05 +0000717
Lang Hames3dc7c512012-02-17 18:44:18 +0000718public:
Lang Hamesecb50622012-02-17 23:43:40 +0000719 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000720 const TargetRegisterInfo& TRI,
Andrew Trick27c28ce2012-10-16 00:22:51 +0000721 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
722 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
723 UpdateFlags(UpdateFlags) {}
724
725 // FIXME: UpdateFlags is a workaround that creates live intervals for all
726 // physregs, even those that aren't needed for regalloc, in order to update
727 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
728 // flags, and postRA passes will use a live register utility instead.
729 LiveInterval *getRegUnitLI(unsigned Unit) {
730 if (UpdateFlags)
731 return &LIS.getRegUnit(Unit);
732 return LIS.getCachedRegUnit(Unit);
733 }
Lang Hames3dc7c512012-02-17 18:44:18 +0000734
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000735 /// Update all live ranges touched by MI, assuming a move from OldIdx to
736 /// NewIdx.
737 void updateAllRanges(MachineInstr *MI) {
738 DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
739 bool hasRegMask = false;
740 for (MIOperands MO(MI); MO.isValid(); ++MO) {
741 if (MO->isRegMask())
742 hasRegMask = true;
743 if (!MO->isReg())
Lang Hames4586d252012-02-21 22:29:38 +0000744 continue;
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000745 // Aggressively clear all kill flags.
746 // They are reinserted by VirtRegRewriter.
747 if (MO->isUse())
748 MO->setIsKill(false);
749
750 unsigned Reg = MO->getReg();
751 if (!Reg)
752 continue;
753 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
754 updateRange(LIS.getInterval(Reg));
755 continue;
756 }
757
758 // For physregs, only update the regunits that actually have a
759 // precomputed live range.
760 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
Andrew Trick27c28ce2012-10-16 00:22:51 +0000761 if (LiveInterval *LI = getRegUnitLI(*Units))
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000762 updateRange(*LI);
Lang Hames4586d252012-02-21 22:29:38 +0000763 }
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000764 if (hasRegMask)
765 updateRegMaskSlots();
Lang Hames6aceab12012-02-19 07:13:05 +0000766 }
767
Lang Hames55fed622012-02-19 03:00:30 +0000768private:
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000769 /// Update a single live range, assuming an instruction has been moved from
770 /// OldIdx to NewIdx.
771 void updateRange(LiveInterval &LI) {
772 if (!Updated.insert(&LI))
773 return;
774 DEBUG({
775 dbgs() << " ";
776 if (TargetRegisterInfo::isVirtualRegister(LI.reg))
777 dbgs() << PrintReg(LI.reg);
Jakob Stoklund Olesenbf833f02012-06-19 23:50:18 +0000778 else
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000779 dbgs() << PrintRegUnit(LI.reg, &TRI);
780 dbgs() << ":\t" << LI << '\n';
781 });
782 if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
783 handleMoveDown(LI);
784 else
785 handleMoveUp(LI);
786 DEBUG(dbgs() << " -->\t" << LI << '\n');
787 LI.verify();
Lang Hames3dc7c512012-02-17 18:44:18 +0000788 }
789
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000790 /// Update LI to reflect an instruction has been moved downwards from OldIdx
791 /// to NewIdx.
792 ///
793 /// 1. Live def at OldIdx:
794 /// Move def to NewIdx, assert endpoint after NewIdx.
795 ///
796 /// 2. Live def at OldIdx, killed at NewIdx:
797 /// Change to dead def at NewIdx.
798 /// (Happens when bundling def+kill together).
799 ///
800 /// 3. Dead def at OldIdx:
801 /// Move def to NewIdx, possibly across another live value.
802 ///
803 /// 4. Def at OldIdx AND at NewIdx:
804 /// Remove live range [OldIdx;NewIdx) and value defined at OldIdx.
805 /// (Happens when bundling multiple defs together).
806 ///
807 /// 5. Value read at OldIdx, killed before NewIdx:
808 /// Extend kill to NewIdx.
809 ///
810 void handleMoveDown(LiveInterval &LI) {
811 // First look for a kill at OldIdx.
812 LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
813 LiveInterval::iterator E = LI.end();
814 // Is LI even live at OldIdx?
815 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
816 return;
Lang Hames6aceab12012-02-19 07:13:05 +0000817
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000818 // Handle a live-in value.
819 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
820 bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
821 // If the live-in value already extends to NewIdx, there is nothing to do.
822 if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
823 return;
824 // Aggressively remove all kill flags from the old kill point.
825 // Kill flags shouldn't be used while live intervals exist, they will be
826 // reinserted by VirtRegRewriter.
827 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
828 for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
829 if (MO->isReg() && MO->isUse())
830 MO->setIsKill(false);
831 // Adjust I->end to reach NewIdx. This may temporarily make LI invalid by
832 // overlapping ranges. Case 5 above.
833 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
834 // If this was a kill, there may also be a def. Otherwise we're done.
835 if (!isKill)
836 return;
837 ++I;
Lang Hames6aceab12012-02-19 07:13:05 +0000838 }
839
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000840 // Check for a def at OldIdx.
841 if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
842 return;
843 // We have a def at OldIdx.
844 VNInfo *DefVNI = I->valno;
845 assert(DefVNI->def == I->start && "Inconsistent def");
846 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
847 // If the defined value extends beyond NewIdx, just move the def down.
848 // This is case 1 above.
849 if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
850 I->start = DefVNI->def;
851 return;
852 }
853 // The remaining possibilities are now:
854 // 2. Live def at OldIdx, killed at NewIdx: isSameInstr(I->end, NewIdx).
855 // 3. Dead def at OldIdx: I->end = OldIdx.getDeadSlot().
856 // In either case, it is possible that there is an existing def at NewIdx.
857 assert((I->end == OldIdx.getDeadSlot() ||
858 SlotIndex::isSameInstr(I->end, NewIdx)) &&
859 "Cannot move def below kill");
860 LiveInterval::iterator NewI = LI.advanceTo(I, NewIdx.getRegSlot());
861 if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
862 // There is an existing def at NewIdx, case 4 above. The def at OldIdx is
863 // coalesced into that value.
864 assert(NewI->valno != DefVNI && "Multiple defs of value?");
865 LI.removeValNo(DefVNI);
866 return;
867 }
868 // There was no existing def at NewIdx. Turn *I into a dead def at NewIdx.
869 // If the def at OldIdx was dead, we allow it to be moved across other LI
870 // values. The new range should be placed immediately before NewI, move any
871 // intermediate ranges up.
872 assert(NewI != I && "Inconsistent iterators");
873 std::copy(llvm::next(I), NewI, I);
874 *llvm::prior(NewI) = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
875 }
876
877 /// Update LI to reflect an instruction has been moved upwards from OldIdx
878 /// to NewIdx.
879 ///
880 /// 1. Live def at OldIdx:
881 /// Hoist def to NewIdx.
882 ///
883 /// 2. Dead def at OldIdx:
884 /// Hoist def+end to NewIdx, possibly move across other values.
885 ///
886 /// 3. Dead def at OldIdx AND existing def at NewIdx:
887 /// Remove value defined at OldIdx, coalescing it with existing value.
888 ///
889 /// 4. Live def at OldIdx AND existing def at NewIdx:
890 /// Remove value defined at NewIdx, hoist OldIdx def to NewIdx.
891 /// (Happens when bundling multiple defs together).
892 ///
893 /// 5. Value killed at OldIdx:
894 /// Hoist kill to NewIdx, then scan for last kill between NewIdx and
895 /// OldIdx.
896 ///
897 void handleMoveUp(LiveInterval &LI) {
898 // First look for a kill at OldIdx.
899 LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
900 LiveInterval::iterator E = LI.end();
901 // Is LI even live at OldIdx?
902 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
903 return;
904
905 // Handle a live-in value.
906 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
907 // If the live-in value isn't killed here, there is nothing to do.
908 if (!SlotIndex::isSameInstr(OldIdx, I->end))
909 return;
910 // Adjust I->end to end at NewIdx. If we are hoisting a kill above
911 // another use, we need to search for that use. Case 5 above.
912 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
913 ++I;
914 // If OldIdx also defines a value, there couldn't have been another use.
915 if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
916 // No def, search for the new kill.
917 // This can never be an early clobber kill since there is no def.
918 llvm::prior(I)->end = findLastUseBefore(LI.reg).getRegSlot();
919 return;
Lang Hames6aceab12012-02-19 07:13:05 +0000920 }
921 }
922
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000923 // Now deal with the def at OldIdx.
924 assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
925 VNInfo *DefVNI = I->valno;
926 assert(DefVNI->def == I->start && "Inconsistent def");
927 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
928
929 // Check for an existing def at NewIdx.
930 LiveInterval::iterator NewI = LI.find(NewIdx.getRegSlot());
931 if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
932 assert(NewI->valno != DefVNI && "Same value defined more than once?");
933 // There is an existing def at NewIdx.
934 if (I->end.isDead()) {
935 // Case 3: Remove the dead def at OldIdx.
936 LI.removeValNo(DefVNI);
937 return;
938 }
939 // Case 4: Replace def at NewIdx with live def at OldIdx.
940 I->start = DefVNI->def;
941 LI.removeValNo(NewI->valno);
942 return;
Lang Hames6aceab12012-02-19 07:13:05 +0000943 }
944
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000945 // There is no existing def at NewIdx. Hoist DefVNI.
946 if (!I->end.isDead()) {
947 // Leave the end point of a live def.
948 I->start = DefVNI->def;
949 return;
950 }
951
952 // DefVNI is a dead def. It may have been moved across other values in LI,
953 // so move I up to NewI. Slide [NewI;I) down one position.
954 std::copy_backward(NewI, I, llvm::next(I));
955 *NewI = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
Lang Hames6aceab12012-02-19 07:13:05 +0000956 }
957
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000958 void updateRegMaskSlots() {
Lang Hamesecb50622012-02-17 23:43:40 +0000959 SmallVectorImpl<SlotIndex>::iterator RI =
960 std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
961 OldIdx);
Jakob Stoklund Olesen722c9a72012-11-09 19:18:49 +0000962 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
963 "No RegMask at OldIdx.");
964 *RI = NewIdx.getRegSlot();
965 assert((RI == LIS.RegMaskSlots.begin() ||
966 SlotIndex::isEarlierInstr(*llvm::prior(RI), *RI)) &&
967 "Cannot move regmask instruction above another call");
968 assert((llvm::next(RI) == LIS.RegMaskSlots.end() ||
969 SlotIndex::isEarlierInstr(*RI, *llvm::next(RI))) &&
970 "Cannot move regmask instruction below another call");
Lang Hamesfbc8dd32012-02-17 21:29:41 +0000971 }
Lang Hames55fed622012-02-19 03:00:30 +0000972
973 // Return the last use of reg between NewIdx and OldIdx.
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000974 SlotIndex findLastUseBefore(unsigned Reg) {
Lang Hames55fed622012-02-19 03:00:30 +0000975 SlotIndex LastUse = NewIdx;
Lang Hames6d742cc2012-09-12 06:56:16 +0000976
977 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
978 for (MachineRegisterInfo::use_nodbg_iterator
979 UI = MRI.use_nodbg_begin(Reg),
980 UE = MRI.use_nodbg_end();
981 UI != UE; UI.skipInstruction()) {
982 const MachineInstr* MI = &*UI;
983 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
984 if (InstSlot > LastUse && InstSlot < OldIdx)
985 LastUse = InstSlot;
986 }
987 } else {
988 MachineInstr* MI = LIS.getSlotIndexes()->getInstructionFromIndex(NewIdx);
989 MachineBasicBlock::iterator MII(MI);
990 ++MII;
991 MachineBasicBlock* MBB = MI->getParent();
Andrew Trick30fe61a2012-12-01 01:22:41 +0000992 for (; MII != MBB->end(); ++MII){
993 if (MII->isDebugValue())
994 continue;
995 if (LIS.getInstructionIndex(MII) < OldIdx)
996 break;
Lang Hames6d742cc2012-09-12 06:56:16 +0000997 for (MachineInstr::mop_iterator MOI = MII->operands_begin(),
998 MOE = MII->operands_end();
999 MOI != MOE; ++MOI) {
1000 const MachineOperand& mop = *MOI;
1001 if (!mop.isReg() || mop.getReg() == 0 ||
1002 TargetRegisterInfo::isVirtualRegister(mop.getReg()))
1003 continue;
1004
1005 if (TRI.hasRegUnit(mop.getReg(), Reg))
1006 LastUse = LIS.getInstructionIndex(MII);
1007 }
1008 }
Lang Hames55fed622012-02-19 03:00:30 +00001009 }
1010 return LastUse;
1011 }
Lang Hames3dc7c512012-02-17 18:44:18 +00001012};
1013
Andrew Trick27c28ce2012-10-16 00:22:51 +00001014void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001015 assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +00001016 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1017 Indexes->removeMachineInstrFromMaps(MI);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001018 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
Lang Hamesecb50622012-02-17 23:43:40 +00001019 assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1020 OldIndex < getMBBEndIdx(MI->getParent()) &&
Lang Hames3dc7c512012-02-17 18:44:18 +00001021 "Cannot handle moves across basic block boundaries.");
Lang Hames3dc7c512012-02-17 18:44:18 +00001022
Andrew Trick27c28ce2012-10-16 00:22:51 +00001023 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001024 HME.updateAllRanges(MI);
Lang Hames4586d252012-02-21 22:29:38 +00001025}
1026
Jakob Stoklund Olesenfa8becb2012-06-19 22:50:53 +00001027void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
Andrew Trick27c28ce2012-10-16 00:22:51 +00001028 MachineInstr* BundleStart,
1029 bool UpdateFlags) {
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001030 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +00001031 SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
Andrew Trick27c28ce2012-10-16 00:22:51 +00001032 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001033 HME.updateAllRanges(MI);
Lang Hames3dc7c512012-02-17 18:44:18 +00001034}