blob: fdc673f71e1974ec7e344fb92154ec35f59117b2 [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"
Stephen Hines36b56882014-04-23 16:57:46 -070025#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +000026#include "llvm/CodeGen/MachineDominators.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000027#include "llvm/CodeGen/MachineInstr.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000029#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000030#include "llvm/CodeGen/VirtRegMap.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000031#include "llvm/IR/Value.h"
Benjamin Kramer4eed7562013-06-17 19:00:36 +000032#include "llvm/Support/BlockFrequency.h"
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +000033#include "llvm/Support/CommandLine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000034#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000035#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000037#include "llvm/Target/TargetInstrInfo.h"
38#include "llvm/Target/TargetMachine.h"
39#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000040#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000041#include <cmath>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000042#include <limits>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000043using namespace llvm;
44
Devang Patel19974732007-05-03 01:11:54 +000045char LiveIntervals::ID = 0;
Jakob Stoklund Olesendcc44362012-08-03 22:12:54 +000046char &llvm::LiveIntervalsID = LiveIntervals::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +000047INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
48 "Live Interval Analysis", false, false)
Andrew Trick8dd26252012-02-10 04:10:36 +000049INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Owen Anderson2ab36d32010-10-12 19:48:12 +000050INITIALIZE_PASS_DEPENDENCY(LiveVariables)
Andrew Trick8dd26252012-02-10 04:10:36 +000051INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Owen Anderson2ab36d32010-10-12 19:48:12 +000052INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
Owen Anderson2ab36d32010-10-12 19:48:12 +000053INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
Owen Andersonce665bd2010-10-07 22:25:06 +000054 "Live Interval Analysis", false, false)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000055
Andrew Trickc6bae792013-06-21 18:33:23 +000056#ifndef NDEBUG
57static cl::opt<bool> EnablePrecomputePhysRegs(
58 "precompute-phys-liveness", cl::Hidden,
59 cl::desc("Eagerly compute live intervals for all physreg units."));
60#else
61static bool EnablePrecomputePhysRegs = false;
62#endif // NDEBUG
63
Chris Lattnerf7da2c72006-08-24 22:43:55 +000064void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000065 AU.setPreservesCFG();
Dan Gohman6d69ba82008-07-25 00:02:30 +000066 AU.addRequired<AliasAnalysis>();
67 AU.addPreserved<AliasAnalysis>();
Jakob Stoklund Olesenec7b25d2013-02-09 00:04:07 +000068 // LiveVariables isn't really required by this analysis, it is only required
69 // here to make sure it is live during TwoAddressInstructionPass and
70 // PHIElimination. This is temporary.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000071 AU.addRequired<LiveVariables>();
Evan Cheng148341c2010-08-17 21:00:37 +000072 AU.addPreserved<LiveVariables>();
Andrew Trickd35576b2012-02-13 20:44:42 +000073 AU.addPreservedID(MachineLoopInfoID);
Jakob Stoklund Olesenc4118452012-06-20 23:31:34 +000074 AU.addRequiredTransitiveID(MachineDominatorsID);
Bill Wendling67d65bb2008-01-04 20:54:55 +000075 AU.addPreservedID(MachineDominatorsID);
Lang Hames233a60e2009-11-03 23:52:08 +000076 AU.addPreserved<SlotIndexes>();
77 AU.addRequiredTransitive<SlotIndexes>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000078 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000079}
80
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +000081LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
82 DomTree(0), LRCalc(0) {
83 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
84}
85
86LiveIntervals::~LiveIntervals() {
87 delete LRCalc;
88}
89
Chris Lattnerf7da2c72006-08-24 22:43:55 +000090void LiveIntervals::releaseMemory() {
Owen Anderson03857b22008-08-13 21:49:13 +000091 // Free the live intervals themselves.
Jakob Stoklund Olesen7fa67842012-06-22 20:37:52 +000092 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
93 delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
94 VirtRegIntervals.clear();
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +000095 RegMaskSlots.clear();
96 RegMaskBits.clear();
Jakob Stoklund Olesen34e85d02012-02-10 01:26:29 +000097 RegMaskBlocks.clear();
Lang Hamesffd13262009-07-09 03:57:02 +000098
Matthias Braun4f3b5e82013-10-10 21:29:02 +000099 for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
100 delete RegUnitRanges[i];
101 RegUnitRanges.clear();
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000102
Benjamin Kramerce9a20b2010-06-26 11:30:59 +0000103 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
104 VNInfoAllocator.Reset();
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000105}
106
Jakob Stoklund Olesen2aeef002013-08-14 17:28:46 +0000107/// runOnMachineFunction - calculates LiveIntervals
Owen Anderson80b3ce62008-05-28 20:54:50 +0000108///
109bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000110 MF = &fn;
111 MRI = &MF->getRegInfo();
112 TM = &fn.getTarget();
113 TRI = TM->getRegisterInfo();
114 TII = TM->getInstrInfo();
115 AA = &getAnalysis<AliasAnalysis>();
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000116 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenc4118452012-06-20 23:31:34 +0000117 DomTree = &getAnalysis<MachineDominatorTree>();
118 if (!LRCalc)
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000119 LRCalc = new LiveRangeCalc();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000120
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000121 // Allocate space for all virtual registers.
122 VirtRegIntervals.resize(MRI->getNumVirtRegs());
123
Jakob Stoklund Olesenec7b25d2013-02-09 00:04:07 +0000124 computeVirtRegs();
125 computeRegMasks();
Jakob Stoklund Olesenc4118452012-06-20 23:31:34 +0000126 computeLiveInRegUnits();
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000127
Andrew Trickc6bae792013-06-21 18:33:23 +0000128 if (EnablePrecomputePhysRegs) {
129 // For stress testing, precompute live ranges of all physical register
130 // units, including reserved registers.
131 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
132 getRegUnit(i);
133 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000134 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000135 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000136}
137
Chris Lattner70ca3582004-09-30 15:59:17 +0000138/// print - Implement the dump method.
Chris Lattner45cfe542009-08-23 06:03:38 +0000139void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
Chris Lattner705e07f2009-08-23 03:41:05 +0000140 OS << "********** INTERVALS **********\n";
Jakob Stoklund Olesenf658af52012-02-14 23:46:21 +0000141
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000142 // Dump the regunits.
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000143 for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
144 if (LiveRange *LR = RegUnitRanges[i])
Matthias Braun03d96092013-10-10 21:29:05 +0000145 OS << PrintRegUnit(i, TRI) << ' ' << *LR << '\n';
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000146
Jakob Stoklund Olesenf658af52012-02-14 23:46:21 +0000147 // Dump the virtregs.
Jakob Stoklund Olesen7fa67842012-06-22 20:37:52 +0000148 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
149 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
150 if (hasInterval(Reg))
Matthias Braun03d96092013-10-10 21:29:05 +0000151 OS << getInterval(Reg) << '\n';
Jakob Stoklund Olesen7fa67842012-06-22 20:37:52 +0000152 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000153
Jakob Stoklund Olesen722c9a72012-11-09 19:18:49 +0000154 OS << "RegMasks:";
155 for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
156 OS << ' ' << RegMaskSlots[i];
157 OS << '\n';
158
Evan Cheng752195e2009-09-14 21:33:42 +0000159 printInstrs(OS);
160}
161
162void LiveIntervals::printInstrs(raw_ostream &OS) const {
Chris Lattner705e07f2009-08-23 03:41:05 +0000163 OS << "********** MACHINEINSTRS **********\n";
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000164 MF->print(OS, Indexes);
Chris Lattner70ca3582004-09-30 15:59:17 +0000165}
166
Manman Renb720be62012-09-11 22:23:19 +0000167#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Evan Cheng752195e2009-09-14 21:33:42 +0000168void LiveIntervals::dumpInstrs() const {
David Greene8a342292010-01-04 22:49:02 +0000169 printInstrs(dbgs());
Evan Cheng752195e2009-09-14 21:33:42 +0000170}
Manman Ren77e300e2012-09-06 19:06:06 +0000171#endif
Evan Cheng752195e2009-09-14 21:33:42 +0000172
Owen Anderson03857b22008-08-13 21:49:13 +0000173LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Aaron Ballmaneb360242013-11-13 00:15:44 +0000174 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
175 llvm::huge_valf : 0.0F;
Owen Anderson03857b22008-08-13 21:49:13 +0000176 return new LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000177}
Evan Chengf2fbca62007-11-12 06:35:08 +0000178
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000179
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000180/// computeVirtRegInterval - Compute the live interval of a virtual register,
181/// based on defs and uses.
Matthias Braune25dde52013-10-10 21:28:57 +0000182void LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000183 assert(LRCalc && "LRCalc not initialized.");
Matthias Braune25dde52013-10-10 21:28:57 +0000184 assert(LI.empty() && "Should only compute empty intervals.");
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000185 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
186 LRCalc->createDeadDefs(LI);
187 LRCalc->extendToUses(LI);
188}
189
Jakob Stoklund Olesenc16bf792012-07-27 21:56:39 +0000190void LiveIntervals::computeVirtRegs() {
191 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
192 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
193 if (MRI->reg_nodbg_empty(Reg))
194 continue;
Mark Laceye742d682013-08-14 23:50:16 +0000195 createAndComputeVirtRegInterval(Reg);
Jakob Stoklund Olesenc16bf792012-07-27 21:56:39 +0000196 }
197}
198
199void LiveIntervals::computeRegMasks() {
200 RegMaskBlocks.resize(MF->getNumBlockIDs());
201
202 // Find all instructions with regmask operands.
203 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
204 MBBI != E; ++MBBI) {
205 MachineBasicBlock *MBB = MBBI;
206 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
207 RMB.first = RegMaskSlots.size();
208 for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
209 MI != ME; ++MI)
210 for (MIOperands MO(MI); MO.isValid(); ++MO) {
211 if (!MO->isRegMask())
212 continue;
213 RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
214 RegMaskBits.push_back(MO->getRegMask());
215 }
216 // Compute the number of register mask instructions in this block.
Dmitri Gribenko2de05722012-09-10 21:26:47 +0000217 RMB.second = RegMaskSlots.size() - RMB.first;
Jakob Stoklund Olesenc16bf792012-07-27 21:56:39 +0000218 }
219}
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000220
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000221//===----------------------------------------------------------------------===//
222// Register Unit Liveness
223//===----------------------------------------------------------------------===//
224//
225// Fixed interference typically comes from ABI boundaries: Function arguments
226// and return values are passed in fixed registers, and so are exception
227// pointers entering landing pads. Certain instructions require values to be
228// present in specific registers. That is also represented through fixed
229// interference.
230//
231
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000232/// computeRegUnitInterval - Compute the live range of a register unit, based
233/// on the uses and defs of aliasing registers. The range should be empty,
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000234/// or contain only dead phi-defs from ABI blocks.
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000235void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000236 assert(LRCalc && "LRCalc not initialized.");
237 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
238
239 // The physregs aliasing Unit are the roots and their super-registers.
240 // Create all values as dead defs before extending to uses. Note that roots
241 // may share super-registers. That's OK because createDeadDefs() is
242 // idempotent. It is very rare for a register unit to have multiple roots, so
243 // uniquing super-registers is probably not worthwhile.
244 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
Chad Rosierb018bab2013-05-22 22:36:55 +0000245 for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
246 Supers.isValid(); ++Supers) {
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000247 if (!MRI->reg_empty(*Supers))
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000248 LRCalc->createDeadDefs(LR, *Supers);
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000249 }
250 }
251
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000252 // Now extend LR to reach all uses.
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000253 // Ignore uses of reserved registers. We only track defs of those.
254 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
Chad Rosierb018bab2013-05-22 22:36:55 +0000255 for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
256 Supers.isValid(); ++Supers) {
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000257 unsigned Reg = *Supers;
Jakob Stoklund Olesen79004762012-10-15 22:14:34 +0000258 if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000259 LRCalc->extendToUses(LR, Reg);
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000260 }
261 }
262}
263
264
265/// computeLiveInRegUnits - Precompute the live ranges of any register units
266/// that are live-in to an ABI block somewhere. Register values can appear
267/// without a corresponding def when entering the entry block or a landing pad.
268///
269void LiveIntervals::computeLiveInRegUnits() {
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000270 RegUnitRanges.resize(TRI->getNumRegUnits());
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000271 DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
272
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000273 // Keep track of the live range sets allocated.
274 SmallVector<unsigned, 8> NewRanges;
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000275
276 // Check all basic blocks for live-ins.
277 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
278 MFI != MFE; ++MFI) {
279 const MachineBasicBlock *MBB = MFI;
280
281 // We only care about ABI blocks: Entry + landing pads.
282 if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
283 continue;
284
285 // Create phi-defs at Begin for all live-in registers.
286 SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
287 DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
288 for (MachineBasicBlock::livein_iterator LII = MBB->livein_begin(),
289 LIE = MBB->livein_end(); LII != LIE; ++LII) {
290 for (MCRegUnitIterator Units(*LII, TRI); Units.isValid(); ++Units) {
291 unsigned Unit = *Units;
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000292 LiveRange *LR = RegUnitRanges[Unit];
293 if (!LR) {
294 LR = RegUnitRanges[Unit] = new LiveRange();
295 NewRanges.push_back(Unit);
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000296 }
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000297 VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
Matt Beaumont-Gay05b46f02012-06-05 23:00:03 +0000298 (void)VNI;
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000299 DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
300 }
301 }
302 DEBUG(dbgs() << '\n');
303 }
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000304 DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000305
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000306 // Compute the 'normal' part of the ranges.
307 for (unsigned i = 0, e = NewRanges.size(); i != e; ++i) {
308 unsigned Unit = NewRanges[i];
309 computeRegUnitRange(*RegUnitRanges[Unit], Unit);
310 }
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000311}
312
313
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000314/// shrinkToUses - After removing some uses of a register, shrink its live
315/// range to just the remaining uses. This method does not compute reaching
316/// defs for new uses, and it doesn't remove dead defs.
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000317bool LiveIntervals::shrinkToUses(LiveInterval *li,
Jakob Stoklund Olesen0d8ccaa2011-03-07 23:29:10 +0000318 SmallVectorImpl<MachineInstr*> *dead) {
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000319 DEBUG(dbgs() << "Shrink: " << *li << '\n');
320 assert(TargetRegisterInfo::isVirtualRegister(li->reg)
Lang Hames567cdba2012-01-03 20:05:57 +0000321 && "Can only shrink virtual registers");
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000322 // Find all the values used, including PHI kills.
323 SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
324
Jakob Stoklund Olesen031432f2011-09-15 15:24:16 +0000325 // Blocks that have already been added to WorkList as live-out.
326 SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
327
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000328 // Visit all instructions reading li->reg.
Stephen Hines36b56882014-04-23 16:57:46 -0700329 for (MachineRegisterInfo::reg_instr_iterator
330 I = MRI->reg_instr_begin(li->reg), E = MRI->reg_instr_end();
331 I != E; ) {
332 MachineInstr *UseMI = &*(I++);
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000333 if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
334 continue;
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000335 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
Matthias Braun5649e252013-10-10 21:28:52 +0000336 LiveQueryResult LRQ = li->Query(Idx);
Jakob Stoklund Olesen97769fc2012-05-20 02:54:52 +0000337 VNInfo *VNI = LRQ.valueIn();
Jakob Stoklund Olesen9ef931e2011-03-18 03:06:04 +0000338 if (!VNI) {
339 // This shouldn't happen: readsVirtualRegister returns true, but there is
340 // no live value. It is likely caused by a target getting <undef> flags
341 // wrong.
342 DEBUG(dbgs() << Idx << '\t' << *UseMI
343 << "Warning: Instr claims to read non-existent value in "
344 << *li << '\n');
345 continue;
346 }
Jakob Stoklund Olesenf054e192011-11-14 18:45:38 +0000347 // Special case: An early-clobber tied operand reads and writes the
Jakob Stoklund Olesen97769fc2012-05-20 02:54:52 +0000348 // register one slot early.
349 if (VNInfo *DefVNI = LRQ.valueDefined())
350 Idx = DefVNI->def;
351
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000352 WorkList.push_back(std::make_pair(Idx, VNI));
353 }
354
Matthias Braun87a86052013-10-10 21:28:47 +0000355 // Create new live ranges with only minimal live segments per def.
356 LiveRange NewLR;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000357 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
358 I != E; ++I) {
359 VNInfo *VNI = *I;
360 if (VNI->isUnused())
361 continue;
Matthias Braun87a86052013-10-10 21:28:47 +0000362 NewLR.addSegment(LiveRange::Segment(VNI->def, VNI->def.getDeadSlot(), VNI));
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000363 }
364
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000365 // Keep track of the PHIs that are in use.
366 SmallPtrSet<VNInfo*, 8> UsedPHIs;
367
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000368 // Extend intervals to reach all uses in WorkList.
369 while (!WorkList.empty()) {
370 SlotIndex Idx = WorkList.back().first;
371 VNInfo *VNI = WorkList.back().second;
372 WorkList.pop_back();
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000373 const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000374 SlotIndex BlockStart = getMBBStartIdx(MBB);
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000375
376 // Extend the live range for VNI to be live at Idx.
Matthias Braun87a86052013-10-10 21:28:47 +0000377 if (VNInfo *ExtVNI = NewLR.extendInBlock(BlockStart, Idx)) {
Nick Lewycky4b11a702011-03-02 01:43:30 +0000378 (void)ExtVNI;
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000379 assert(ExtVNI == VNI && "Unexpected existing value number");
380 // Is this a PHIDef we haven't seen before?
Jakob Stoklund Olesenc29d9b32011-03-03 00:20:51 +0000381 if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000382 continue;
383 // The PHI is live, make sure the predecessors are live-out.
384 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
385 PE = MBB->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen031432f2011-09-15 15:24:16 +0000386 if (!LiveOut.insert(*PI))
387 continue;
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000388 SlotIndex Stop = getMBBEndIdx(*PI);
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000389 // A predecessor is not required to have a live-out value for a PHI.
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000390 if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000391 WorkList.push_back(std::make_pair(Stop, PVNI));
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000392 }
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000393 continue;
394 }
395
396 // VNI is live-in to MBB.
397 DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
Matthias Braun87a86052013-10-10 21:28:47 +0000398 NewLR.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000399
400 // Make sure VNI is live-out from the predecessors.
401 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
402 PE = MBB->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen031432f2011-09-15 15:24:16 +0000403 if (!LiveOut.insert(*PI))
404 continue;
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000405 SlotIndex Stop = getMBBEndIdx(*PI);
406 assert(li->getVNInfoBefore(Stop) == VNI &&
407 "Wrong value out of predecessor");
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000408 WorkList.push_back(std::make_pair(Stop, VNI));
409 }
410 }
411
412 // Handle dead values.
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000413 bool CanSeparate = false;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000414 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
415 I != E; ++I) {
416 VNInfo *VNI = *I;
417 if (VNI->isUnused())
418 continue;
Matthias Braun87a86052013-10-10 21:28:47 +0000419 LiveRange::iterator LRI = NewLR.FindSegmentContaining(VNI->def);
420 assert(LRI != NewLR.end() && "Missing segment for PHI");
421 if (LRI->end != VNI->def.getDeadSlot())
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000422 continue;
Jakob Stoklund Olesena4d34732011-03-02 00:33:01 +0000423 if (VNI->isPHIDef()) {
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000424 // This is a dead PHI. Remove it.
Jakob Stoklund Olesenb2beac22012-08-03 20:59:32 +0000425 VNI->markUnused();
Matthias Braun87a86052013-10-10 21:28:47 +0000426 NewLR.removeSegment(LRI->start, LRI->end);
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000427 DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
428 CanSeparate = true;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000429 } else {
430 // This is a dead def. Make sure the instruction knows.
431 MachineInstr *MI = getInstructionFromIndex(VNI->def);
432 assert(MI && "No instruction defining live value");
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000433 MI->addRegisterDead(li->reg, TRI);
Jakob Stoklund Olesen0d8ccaa2011-03-07 23:29:10 +0000434 if (dead && MI->allDefsAreDead()) {
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000435 DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
Jakob Stoklund Olesen0d8ccaa2011-03-07 23:29:10 +0000436 dead->push_back(MI);
437 }
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000438 }
439 }
440
Matthias Braun331de112013-10-10 21:28:43 +0000441 // Move the trimmed segments back.
Matthias Braun87a86052013-10-10 21:28:47 +0000442 li->segments.swap(NewLR.segments);
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000443 DEBUG(dbgs() << "Shrunk: " << *li << '\n');
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000444 return CanSeparate;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000445}
446
Matthias Braune25dde52013-10-10 21:28:57 +0000447void LiveIntervals::extendToIndices(LiveRange &LR,
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000448 ArrayRef<SlotIndex> Indices) {
449 assert(LRCalc && "LRCalc not initialized.");
450 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
451 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
Matthias Braune25dde52013-10-10 21:28:57 +0000452 LRCalc->extend(LR, Indices[i]);
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000453}
454
455void LiveIntervals::pruneValue(LiveInterval *LI, SlotIndex Kill,
456 SmallVectorImpl<SlotIndex> *EndPoints) {
Matthias Braun5649e252013-10-10 21:28:52 +0000457 LiveQueryResult LRQ = LI->Query(Kill);
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000458 VNInfo *VNI = LRQ.valueOut();
459 if (!VNI)
460 return;
461
462 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
463 SlotIndex MBBStart, MBBEnd;
Stephen Hines36b56882014-04-23 16:57:46 -0700464 std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(KillMBB);
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000465
466 // If VNI isn't live out from KillMBB, the value is trivially pruned.
467 if (LRQ.endPoint() < MBBEnd) {
Matthias Braun331de112013-10-10 21:28:43 +0000468 LI->removeSegment(Kill, LRQ.endPoint());
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000469 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
470 return;
471 }
472
473 // VNI is live out of KillMBB.
Matthias Braun331de112013-10-10 21:28:43 +0000474 LI->removeSegment(Kill, MBBEnd);
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000475 if (EndPoints) EndPoints->push_back(MBBEnd);
476
Jakob Stoklund Olesenaf896902012-10-13 16:15:31 +0000477 // Find all blocks that are reachable from KillMBB without leaving VNI's live
478 // range. It is possible that KillMBB itself is reachable, so start a DFS
479 // from each successor.
480 typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
481 VisitedTy Visited;
482 for (MachineBasicBlock::succ_iterator
483 SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
484 SuccI != SuccE; ++SuccI) {
485 for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
486 I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
487 I != E;) {
488 MachineBasicBlock *MBB = *I;
489
490 // Check if VNI is live in to MBB.
Stephen Hines36b56882014-04-23 16:57:46 -0700491 std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
Matthias Braun5649e252013-10-10 21:28:52 +0000492 LiveQueryResult LRQ = LI->Query(MBBStart);
Jakob Stoklund Olesenaf896902012-10-13 16:15:31 +0000493 if (LRQ.valueIn() != VNI) {
Matthias Braun331de112013-10-10 21:28:43 +0000494 // This block isn't part of the VNI segment. Prune the search.
Jakob Stoklund Olesenaf896902012-10-13 16:15:31 +0000495 I.skipChildren();
496 continue;
497 }
498
499 // Prune the search if VNI is killed in MBB.
500 if (LRQ.endPoint() < MBBEnd) {
Matthias Braun331de112013-10-10 21:28:43 +0000501 LI->removeSegment(MBBStart, LRQ.endPoint());
Jakob Stoklund Olesenaf896902012-10-13 16:15:31 +0000502 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
503 I.skipChildren();
504 continue;
505 }
506
507 // VNI is live through MBB.
Matthias Braun331de112013-10-10 21:28:43 +0000508 LI->removeSegment(MBBStart, MBBEnd);
Jakob Stoklund Olesenaf896902012-10-13 16:15:31 +0000509 if (EndPoints) EndPoints->push_back(MBBEnd);
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000510 ++I;
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000511 }
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000512 }
513}
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000514
Evan Chengf2fbca62007-11-12 06:35:08 +0000515//===----------------------------------------------------------------------===//
516// Register allocator hooks.
517//
518
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000519void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
520 // Keep track of regunit ranges.
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000521 SmallVector<std::pair<LiveRange*, LiveRange::iterator>, 8> RU;
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000522
Jakob Stoklund Olesen12a7be92012-06-20 23:23:59 +0000523 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
524 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000525 if (MRI->reg_nodbg_empty(Reg))
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000526 continue;
Jakob Stoklund Olesen12a7be92012-06-20 23:23:59 +0000527 LiveInterval *LI = &getInterval(Reg);
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000528 if (LI->empty())
529 continue;
530
531 // Find the regunit intervals for the assigned register. They may overlap
532 // the virtual register live range, cancelling any kills.
533 RU.clear();
534 for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
535 ++Units) {
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000536 LiveRange &RURanges = getRegUnit(*Units);
537 if (RURanges.empty())
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000538 continue;
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000539 RU.push_back(std::make_pair(&RURanges, RURanges.find(LI->begin()->end)));
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000540 }
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000541
Matthias Braun331de112013-10-10 21:28:43 +0000542 // Every instruction that kills Reg corresponds to a segment range end
543 // point.
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000544 for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
545 ++RI) {
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000546 // A block index indicates an MBB edge.
547 if (RI->end.isBlock())
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000548 continue;
549 MachineInstr *MI = getInstructionFromIndex(RI->end);
550 if (!MI)
551 continue;
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000552
Matthias Braunb1aa5e42013-10-04 16:52:58 +0000553 // Check if any of the regunits are live beyond the end of RI. That could
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000554 // happen when a physreg is defined as a copy of a virtreg:
555 //
556 // %EAX = COPY %vreg5
557 // FOO %vreg5 <--- MI, cancel kill because %EAX is live.
558 // BAR %EAX<kill>
559 //
560 // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
561 bool CancelKill = false;
562 for (unsigned u = 0, e = RU.size(); u != e; ++u) {
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000563 LiveRange &RRanges = *RU[u].first;
564 LiveRange::iterator &I = RU[u].second;
565 if (I == RRanges.end())
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000566 continue;
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000567 I = RRanges.advanceTo(I, RI->end);
568 if (I == RRanges.end() || I->start >= RI->end)
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000569 continue;
570 // I is overlapping RI.
571 CancelKill = true;
572 break;
573 }
574 if (CancelKill)
575 MI->clearRegisterKills(Reg, NULL);
576 else
577 MI->addRegisterKilled(Reg, NULL);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000578 }
579 }
580}
581
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000582MachineBasicBlock*
583LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
584 // A local live range must be fully contained inside the block, meaning it is
585 // defined and killed at instructions, not at block boundaries. It is not
586 // live in or or out of any block.
587 //
588 // It is technically possible to have a PHI-defined live range identical to a
589 // single block, but we are going to return false in that case.
Lang Hames233a60e2009-11-03 23:52:08 +0000590
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000591 SlotIndex Start = LI.beginIndex();
592 if (Start.isBlock())
593 return NULL;
Lang Hames233a60e2009-11-03 23:52:08 +0000594
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000595 SlotIndex Stop = LI.endIndex();
596 if (Stop.isBlock())
597 return NULL;
Lang Hames233a60e2009-11-03 23:52:08 +0000598
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000599 // getMBBFromIndex doesn't need to search the MBB table when both indexes
600 // belong to proper instructions.
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000601 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
602 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000603 return MBB1 == MBB2 ? MBB1 : NULL;
Evan Cheng81a03822007-11-17 00:40:40 +0000604}
605
Jakob Stoklund Olesen0ab71032012-08-03 20:10:24 +0000606bool
607LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
608 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
609 I != E; ++I) {
610 const VNInfo *PHI = *I;
611 if (PHI->isUnused() || !PHI->isPHIDef())
612 continue;
613 const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
614 // Conservatively return true instead of scanning huge predecessor lists.
615 if (PHIMBB->pred_size() > 100)
616 return true;
617 for (MachineBasicBlock::const_pred_iterator
618 PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
619 if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
620 return true;
621 }
622 return false;
623}
624
Jakob Stoklund Olesene5d90412010-03-01 20:59:38 +0000625float
Stephen Hines36b56882014-04-23 16:57:46 -0700626LiveIntervals::getSpillWeight(bool isDef, bool isUse,
627 const MachineBlockFrequencyInfo *MBFI,
628 const MachineInstr *MI) {
629 BlockFrequency Freq = MBFI->getBlockFreq(MI->getParent());
630 const float Scale = 1.0f / MBFI->getEntryFreq();
631 return (isDef + isUse) * (Freq.getFrequency() * Scale);
Jakob Stoklund Olesene5d90412010-03-01 20:59:38 +0000632}
633
Matthias Braun87a86052013-10-10 21:28:47 +0000634LiveRange::Segment
Matthias Braun331de112013-10-10 21:28:43 +0000635LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr* startInst) {
Mark Laceye742d682013-08-14 23:50:16 +0000636 LiveInterval& Interval = createEmptyInterval(reg);
Owen Andersonc4dc1322008-06-05 17:15:43 +0000637 VNInfo* VN = Interval.getNextValue(
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000638 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000639 getVNInfoAllocator());
Matthias Braun87a86052013-10-10 21:28:47 +0000640 LiveRange::Segment S(
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000641 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
Lang Hames74ab5ee2009-12-22 00:11:50 +0000642 getMBBEndIdx(startInst->getParent()), VN);
Matthias Braun331de112013-10-10 21:28:43 +0000643 Interval.addSegment(S);
Jakob Stoklund Olesen1b293202010-08-12 20:01:23 +0000644
Matthias Braun331de112013-10-10 21:28:43 +0000645 return S;
Owen Andersonc4dc1322008-06-05 17:15:43 +0000646}
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000647
648
649//===----------------------------------------------------------------------===//
650// Register mask functions
651//===----------------------------------------------------------------------===//
652
653bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
654 BitVector &UsableRegs) {
655 if (LI.empty())
656 return false;
Jakob Stoklund Olesen9f10ac62012-02-10 01:31:31 +0000657 LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
658
659 // Use a smaller arrays for local live ranges.
660 ArrayRef<SlotIndex> Slots;
661 ArrayRef<const uint32_t*> Bits;
662 if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
663 Slots = getRegMaskSlotsInBlock(MBB->getNumber());
664 Bits = getRegMaskBitsInBlock(MBB->getNumber());
665 } else {
666 Slots = getRegMaskSlots();
667 Bits = getRegMaskBits();
668 }
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000669
670 // We are going to enumerate all the register mask slots contained in LI.
671 // Start with a binary search of RegMaskSlots to find a starting point.
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000672 ArrayRef<SlotIndex>::iterator SlotI =
673 std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
674 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
675
676 // No slots in range, LI begins after the last call.
677 if (SlotI == SlotE)
678 return false;
679
680 bool Found = false;
681 for (;;) {
682 assert(*SlotI >= LiveI->start);
683 // Loop over all slots overlapping this segment.
684 while (*SlotI < LiveI->end) {
685 // *SlotI overlaps LI. Collect mask bits.
686 if (!Found) {
687 // This is the first overlap. Initialize UsableRegs to all ones.
688 UsableRegs.clear();
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000689 UsableRegs.resize(TRI->getNumRegs(), true);
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000690 Found = true;
691 }
692 // Remove usable registers clobbered by this mask.
Jakob Stoklund Olesen9f10ac62012-02-10 01:31:31 +0000693 UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000694 if (++SlotI == SlotE)
695 return Found;
696 }
697 // *SlotI is beyond the current LI segment.
698 LiveI = LI.advanceTo(LiveI, *SlotI);
699 if (LiveI == LiveE)
700 return Found;
701 // Advance SlotI until it overlaps.
702 while (*SlotI < LiveI->start)
703 if (++SlotI == SlotE)
704 return Found;
705 }
706}
Lang Hames3dc7c512012-02-17 18:44:18 +0000707
708//===----------------------------------------------------------------------===//
709// IntervalUpdate class.
710//===----------------------------------------------------------------------===//
711
Lang Hamesfd6d3212012-02-21 00:00:36 +0000712// HMEditor is a toolkit used by handleMove to trim or extend live intervals.
Lang Hames3dc7c512012-02-17 18:44:18 +0000713class LiveIntervals::HMEditor {
714private:
Lang Hamesecb50622012-02-17 23:43:40 +0000715 LiveIntervals& LIS;
716 const MachineRegisterInfo& MRI;
717 const TargetRegisterInfo& TRI;
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000718 SlotIndex OldIdx;
Lang Hamesecb50622012-02-17 23:43:40 +0000719 SlotIndex NewIdx;
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000720 SmallPtrSet<LiveRange*, 8> Updated;
Andrew Trick27c28ce2012-10-16 00:22:51 +0000721 bool UpdateFlags;
Lang Hames6aceab12012-02-19 07:13:05 +0000722
Lang Hames3dc7c512012-02-17 18:44:18 +0000723public:
Lang Hamesecb50622012-02-17 23:43:40 +0000724 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000725 const TargetRegisterInfo& TRI,
Andrew Trick27c28ce2012-10-16 00:22:51 +0000726 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
727 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
728 UpdateFlags(UpdateFlags) {}
729
730 // FIXME: UpdateFlags is a workaround that creates live intervals for all
731 // physregs, even those that aren't needed for regalloc, in order to update
732 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
733 // flags, and postRA passes will use a live register utility instead.
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000734 LiveRange *getRegUnitLI(unsigned Unit) {
Andrew Trick27c28ce2012-10-16 00:22:51 +0000735 if (UpdateFlags)
736 return &LIS.getRegUnit(Unit);
737 return LIS.getCachedRegUnit(Unit);
738 }
Lang Hames3dc7c512012-02-17 18:44:18 +0000739
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000740 /// Update all live ranges touched by MI, assuming a move from OldIdx to
741 /// NewIdx.
742 void updateAllRanges(MachineInstr *MI) {
743 DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
744 bool hasRegMask = false;
745 for (MIOperands MO(MI); MO.isValid(); ++MO) {
746 if (MO->isRegMask())
747 hasRegMask = true;
748 if (!MO->isReg())
Lang Hames4586d252012-02-21 22:29:38 +0000749 continue;
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000750 // Aggressively clear all kill flags.
751 // They are reinserted by VirtRegRewriter.
752 if (MO->isUse())
753 MO->setIsKill(false);
754
755 unsigned Reg = MO->getReg();
756 if (!Reg)
757 continue;
758 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000759 LiveInterval &LI = LIS.getInterval(Reg);
760 updateRange(LI, Reg);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000761 continue;
762 }
763
764 // For physregs, only update the regunits that actually have a
765 // precomputed live range.
766 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000767 if (LiveRange *LR = getRegUnitLI(*Units))
768 updateRange(*LR, *Units);
Lang Hames4586d252012-02-21 22:29:38 +0000769 }
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000770 if (hasRegMask)
771 updateRegMaskSlots();
Lang Hames6aceab12012-02-19 07:13:05 +0000772 }
773
Lang Hames55fed622012-02-19 03:00:30 +0000774private:
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000775 /// Update a single live range, assuming an instruction has been moved from
776 /// OldIdx to NewIdx.
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000777 void updateRange(LiveRange &LR, unsigned Reg) {
778 if (!Updated.insert(&LR))
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000779 return;
780 DEBUG({
781 dbgs() << " ";
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000782 if (TargetRegisterInfo::isVirtualRegister(Reg))
783 dbgs() << PrintReg(Reg);
Jakob Stoklund Olesenbf833f02012-06-19 23:50:18 +0000784 else
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000785 dbgs() << PrintRegUnit(Reg, &TRI);
786 dbgs() << ":\t" << LR << '\n';
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000787 });
788 if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000789 handleMoveDown(LR);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000790 else
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000791 handleMoveUp(LR, Reg);
792 DEBUG(dbgs() << " -->\t" << LR << '\n');
793 LR.verify();
Lang Hames3dc7c512012-02-17 18:44:18 +0000794 }
795
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000796 /// Update LR to reflect an instruction has been moved downwards from OldIdx
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000797 /// to NewIdx.
798 ///
799 /// 1. Live def at OldIdx:
800 /// Move def to NewIdx, assert endpoint after NewIdx.
801 ///
802 /// 2. Live def at OldIdx, killed at NewIdx:
803 /// Change to dead def at NewIdx.
804 /// (Happens when bundling def+kill together).
805 ///
806 /// 3. Dead def at OldIdx:
807 /// Move def to NewIdx, possibly across another live value.
808 ///
809 /// 4. Def at OldIdx AND at NewIdx:
Matthias Braun331de112013-10-10 21:28:43 +0000810 /// Remove segment [OldIdx;NewIdx) and value defined at OldIdx.
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000811 /// (Happens when bundling multiple defs together).
812 ///
813 /// 5. Value read at OldIdx, killed before NewIdx:
814 /// Extend kill to NewIdx.
815 ///
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000816 void handleMoveDown(LiveRange &LR) {
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000817 // First look for a kill at OldIdx.
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000818 LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
819 LiveRange::iterator E = LR.end();
820 // Is LR even live at OldIdx?
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000821 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
822 return;
Lang Hames6aceab12012-02-19 07:13:05 +0000823
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000824 // Handle a live-in value.
825 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
826 bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
827 // If the live-in value already extends to NewIdx, there is nothing to do.
828 if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
829 return;
830 // Aggressively remove all kill flags from the old kill point.
831 // Kill flags shouldn't be used while live intervals exist, they will be
832 // reinserted by VirtRegRewriter.
833 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
834 for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
835 if (MO->isReg() && MO->isUse())
836 MO->setIsKill(false);
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000837 // Adjust I->end to reach NewIdx. This may temporarily make LR invalid by
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000838 // overlapping ranges. Case 5 above.
839 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
840 // If this was a kill, there may also be a def. Otherwise we're done.
841 if (!isKill)
842 return;
843 ++I;
Lang Hames6aceab12012-02-19 07:13:05 +0000844 }
845
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000846 // Check for a def at OldIdx.
847 if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
848 return;
849 // We have a def at OldIdx.
850 VNInfo *DefVNI = I->valno;
851 assert(DefVNI->def == I->start && "Inconsistent def");
852 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
853 // If the defined value extends beyond NewIdx, just move the def down.
854 // This is case 1 above.
855 if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
856 I->start = DefVNI->def;
857 return;
858 }
859 // The remaining possibilities are now:
860 // 2. Live def at OldIdx, killed at NewIdx: isSameInstr(I->end, NewIdx).
861 // 3. Dead def at OldIdx: I->end = OldIdx.getDeadSlot().
862 // In either case, it is possible that there is an existing def at NewIdx.
863 assert((I->end == OldIdx.getDeadSlot() ||
864 SlotIndex::isSameInstr(I->end, NewIdx)) &&
865 "Cannot move def below kill");
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000866 LiveRange::iterator NewI = LR.advanceTo(I, NewIdx.getRegSlot());
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000867 if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
868 // There is an existing def at NewIdx, case 4 above. The def at OldIdx is
869 // coalesced into that value.
870 assert(NewI->valno != DefVNI && "Multiple defs of value?");
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000871 LR.removeValNo(DefVNI);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000872 return;
873 }
874 // There was no existing def at NewIdx. Turn *I into a dead def at NewIdx.
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000875 // If the def at OldIdx was dead, we allow it to be moved across other LR
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000876 // values. The new range should be placed immediately before NewI, move any
877 // intermediate ranges up.
878 assert(NewI != I && "Inconsistent iterators");
Stephen Hines36b56882014-04-23 16:57:46 -0700879 std::copy(std::next(I), NewI, I);
880 *std::prev(NewI)
Matthias Braun87a86052013-10-10 21:28:47 +0000881 = LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000882 }
883
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000884 /// Update LR to reflect an instruction has been moved upwards from OldIdx
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000885 /// to NewIdx.
886 ///
887 /// 1. Live def at OldIdx:
888 /// Hoist def to NewIdx.
889 ///
890 /// 2. Dead def at OldIdx:
891 /// Hoist def+end to NewIdx, possibly move across other values.
892 ///
893 /// 3. Dead def at OldIdx AND existing def at NewIdx:
894 /// Remove value defined at OldIdx, coalescing it with existing value.
895 ///
896 /// 4. Live def at OldIdx AND existing def at NewIdx:
897 /// Remove value defined at NewIdx, hoist OldIdx def to NewIdx.
898 /// (Happens when bundling multiple defs together).
899 ///
900 /// 5. Value killed at OldIdx:
901 /// Hoist kill to NewIdx, then scan for last kill between NewIdx and
902 /// OldIdx.
903 ///
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000904 void handleMoveUp(LiveRange &LR, unsigned Reg) {
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000905 // First look for a kill at OldIdx.
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000906 LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
907 LiveRange::iterator E = LR.end();
908 // Is LR even live at OldIdx?
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000909 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
910 return;
911
912 // Handle a live-in value.
913 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
914 // If the live-in value isn't killed here, there is nothing to do.
915 if (!SlotIndex::isSameInstr(OldIdx, I->end))
916 return;
917 // Adjust I->end to end at NewIdx. If we are hoisting a kill above
918 // another use, we need to search for that use. Case 5 above.
919 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
920 ++I;
921 // If OldIdx also defines a value, there couldn't have been another use.
922 if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
923 // No def, search for the new kill.
924 // This can never be an early clobber kill since there is no def.
Stephen Hines36b56882014-04-23 16:57:46 -0700925 std::prev(I)->end = findLastUseBefore(Reg).getRegSlot();
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000926 return;
Lang Hames6aceab12012-02-19 07:13:05 +0000927 }
928 }
929
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000930 // Now deal with the def at OldIdx.
931 assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
932 VNInfo *DefVNI = I->valno;
933 assert(DefVNI->def == I->start && "Inconsistent def");
934 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
935
936 // Check for an existing def at NewIdx.
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000937 LiveRange::iterator NewI = LR.find(NewIdx.getRegSlot());
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000938 if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
939 assert(NewI->valno != DefVNI && "Same value defined more than once?");
940 // There is an existing def at NewIdx.
941 if (I->end.isDead()) {
942 // Case 3: Remove the dead def at OldIdx.
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000943 LR.removeValNo(DefVNI);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000944 return;
945 }
946 // Case 4: Replace def at NewIdx with live def at OldIdx.
947 I->start = DefVNI->def;
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000948 LR.removeValNo(NewI->valno);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000949 return;
Lang Hames6aceab12012-02-19 07:13:05 +0000950 }
951
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000952 // There is no existing def at NewIdx. Hoist DefVNI.
953 if (!I->end.isDead()) {
954 // Leave the end point of a live def.
955 I->start = DefVNI->def;
956 return;
957 }
958
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000959 // DefVNI is a dead def. It may have been moved across other values in LR,
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000960 // so move I up to NewI. Slide [NewI;I) down one position.
Stephen Hines36b56882014-04-23 16:57:46 -0700961 std::copy_backward(NewI, I, std::next(I));
Matthias Braun87a86052013-10-10 21:28:47 +0000962 *NewI = LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
Lang Hames6aceab12012-02-19 07:13:05 +0000963 }
964
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000965 void updateRegMaskSlots() {
Lang Hamesecb50622012-02-17 23:43:40 +0000966 SmallVectorImpl<SlotIndex>::iterator RI =
967 std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
968 OldIdx);
Jakob Stoklund Olesen722c9a72012-11-09 19:18:49 +0000969 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
970 "No RegMask at OldIdx.");
971 *RI = NewIdx.getRegSlot();
972 assert((RI == LIS.RegMaskSlots.begin() ||
Stephen Hines36b56882014-04-23 16:57:46 -0700973 SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
974 "Cannot move regmask instruction above another call");
975 assert((std::next(RI) == LIS.RegMaskSlots.end() ||
976 SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
977 "Cannot move regmask instruction below another call");
Lang Hamesfbc8dd32012-02-17 21:29:41 +0000978 }
Lang Hames55fed622012-02-19 03:00:30 +0000979
980 // Return the last use of reg between NewIdx and OldIdx.
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000981 SlotIndex findLastUseBefore(unsigned Reg) {
Lang Hames6d742cc2012-09-12 06:56:16 +0000982
983 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Jakob Stoklund Olesen778ef972013-03-08 18:08:57 +0000984 SlotIndex LastUse = NewIdx;
Stephen Hines36b56882014-04-23 16:57:46 -0700985 for (MachineRegisterInfo::use_instr_nodbg_iterator
986 UI = MRI.use_instr_nodbg_begin(Reg),
987 UE = MRI.use_instr_nodbg_end();
988 UI != UE; ++UI) {
Lang Hames6d742cc2012-09-12 06:56:16 +0000989 const MachineInstr* MI = &*UI;
990 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
991 if (InstSlot > LastUse && InstSlot < OldIdx)
992 LastUse = InstSlot;
993 }
Jakob Stoklund Olesen778ef972013-03-08 18:08:57 +0000994 return LastUse;
Lang Hames55fed622012-02-19 03:00:30 +0000995 }
Jakob Stoklund Olesen778ef972013-03-08 18:08:57 +0000996
997 // This is a regunit interval, so scanning the use list could be very
998 // expensive. Scan upwards from OldIdx instead.
999 assert(NewIdx < OldIdx && "Expected upwards move");
1000 SlotIndexes *Indexes = LIS.getSlotIndexes();
1001 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(NewIdx);
1002
1003 // OldIdx may not correspond to an instruction any longer, so set MII to
1004 // point to the next instruction after OldIdx, or MBB->end().
1005 MachineBasicBlock::iterator MII = MBB->end();
1006 if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1007 Indexes->getNextNonNullIndex(OldIdx)))
1008 if (MI->getParent() == MBB)
1009 MII = MI;
1010
1011 MachineBasicBlock::iterator Begin = MBB->begin();
1012 while (MII != Begin) {
1013 if ((--MII)->isDebugValue())
1014 continue;
1015 SlotIndex Idx = Indexes->getInstructionIndex(MII);
1016
1017 // Stop searching when NewIdx is reached.
1018 if (!SlotIndex::isEarlierInstr(NewIdx, Idx))
1019 return NewIdx;
1020
1021 // Check if MII uses Reg.
1022 for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
1023 if (MO->isReg() &&
1024 TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
1025 TRI.hasRegUnit(MO->getReg(), Reg))
1026 return Idx;
1027 }
1028 // Didn't reach NewIdx. It must be the first instruction in the block.
1029 return NewIdx;
Lang Hames55fed622012-02-19 03:00:30 +00001030 }
Lang Hames3dc7c512012-02-17 18:44:18 +00001031};
1032
Andrew Trick27c28ce2012-10-16 00:22:51 +00001033void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001034 assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +00001035 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1036 Indexes->removeMachineInstrFromMaps(MI);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001037 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
Lang Hamesecb50622012-02-17 23:43:40 +00001038 assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1039 OldIndex < getMBBEndIdx(MI->getParent()) &&
Lang Hames3dc7c512012-02-17 18:44:18 +00001040 "Cannot handle moves across basic block boundaries.");
Lang Hames3dc7c512012-02-17 18:44:18 +00001041
Andrew Trick27c28ce2012-10-16 00:22:51 +00001042 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001043 HME.updateAllRanges(MI);
Lang Hames4586d252012-02-21 22:29:38 +00001044}
1045
Jakob Stoklund Olesenfa8becb2012-06-19 22:50:53 +00001046void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
Andrew Trick27c28ce2012-10-16 00:22:51 +00001047 MachineInstr* BundleStart,
1048 bool UpdateFlags) {
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001049 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +00001050 SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
Andrew Trick27c28ce2012-10-16 00:22:51 +00001051 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001052 HME.updateAllRanges(MI);
Lang Hames3dc7c512012-02-17 18:44:18 +00001053}
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001054
1055void
1056LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
Cameron Zwarich680c98f2013-02-17 11:09:00 +00001057 MachineBasicBlock::iterator Begin,
1058 MachineBasicBlock::iterator End,
Cameron Zwarich7324d4e2013-02-17 03:48:23 +00001059 ArrayRef<unsigned> OrigRegs) {
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001060 // Find anchor points, which are at the beginning/end of blocks or at
1061 // instructions that already have indexes.
1062 while (Begin != MBB->begin() && !Indexes->hasIndex(Begin))
1063 --Begin;
1064 while (End != MBB->end() && !Indexes->hasIndex(End))
1065 ++End;
1066
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001067 SlotIndex endIdx;
1068 if (End == MBB->end())
1069 endIdx = getMBBEndIdx(MBB).getPrevSlot();
Cameron Zwarich680c98f2013-02-17 11:09:00 +00001070 else
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001071 endIdx = getInstructionIndex(End);
Cameron Zwarich680c98f2013-02-17 11:09:00 +00001072
Cameron Zwarich349cf342013-02-20 06:46:41 +00001073 Indexes->repairIndexesInRange(MBB, Begin, End);
1074
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001075 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1076 --I;
1077 MachineInstr *MI = I;
Cameron Zwarich79f5ab12013-02-23 10:25:25 +00001078 if (MI->isDebugValue())
1079 continue;
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001080 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1081 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1082 if (MOI->isReg() &&
1083 TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
1084 !hasInterval(MOI->getReg())) {
Mark Laceye742d682013-08-14 23:50:16 +00001085 createAndComputeVirtRegInterval(MOI->getReg());
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001086 }
1087 }
1088 }
1089
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001090 for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
1091 unsigned Reg = OrigRegs[i];
1092 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1093 continue;
1094
1095 LiveInterval &LI = getInterval(Reg);
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001096 // FIXME: Should we support undefs that gain defs?
1097 if (!LI.hasAtLeastOneValue())
1098 continue;
1099
1100 LiveInterval::iterator LII = LI.find(endIdx);
1101 SlotIndex lastUseIdx;
1102 if (LII != LI.end() && LII->start < endIdx)
1103 lastUseIdx = LII->end;
1104 else
1105 --LII;
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001106
Cameron Zwarich680c98f2013-02-17 11:09:00 +00001107 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1108 --I;
1109 MachineInstr *MI = I;
Cameron Zwarich79f5ab12013-02-23 10:25:25 +00001110 if (MI->isDebugValue())
1111 continue;
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001112
Cameron Zwarich79f5ab12013-02-23 10:25:25 +00001113 SlotIndex instrIdx = getInstructionIndex(MI);
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001114 bool isStartValid = getInstructionFromIndex(LII->start);
1115 bool isEndValid = getInstructionFromIndex(LII->end);
1116
1117 // FIXME: This doesn't currently handle early-clobber or multiple removed
1118 // defs inside of the region to repair.
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001119 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
1120 OE = MI->operands_end(); OI != OE; ++OI) {
1121 const MachineOperand &MO = *OI;
1122 if (!MO.isReg() || MO.getReg() != Reg)
1123 continue;
1124
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001125 if (MO.isDef()) {
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001126 if (!isStartValid) {
1127 if (LII->end.isDead()) {
1128 SlotIndex prevStart;
1129 if (LII != LI.begin())
Stephen Hines36b56882014-04-23 16:57:46 -07001130 prevStart = std::prev(LII)->start;
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001131
Matthias Braun331de112013-10-10 21:28:43 +00001132 // FIXME: This could be more efficient if there was a
1133 // removeSegment method that returned an iterator.
1134 LI.removeSegment(*LII, true);
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001135 if (prevStart.isValid())
1136 LII = LI.find(prevStart);
1137 else
1138 LII = LI.begin();
1139 } else {
1140 LII->start = instrIdx.getRegSlot();
1141 LII->valno->def = instrIdx.getRegSlot();
1142 if (MO.getSubReg() && !MO.isUndef())
1143 lastUseIdx = instrIdx.getRegSlot();
1144 else
1145 lastUseIdx = SlotIndex();
1146 continue;
1147 }
1148 }
1149
1150 if (!lastUseIdx.isValid()) {
1151 VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
1152 VNInfoAllocator);
Matthias Braun87a86052013-10-10 21:28:47 +00001153 LiveRange::Segment S(instrIdx.getRegSlot(),
1154 instrIdx.getDeadSlot(), VNI);
Matthias Braun331de112013-10-10 21:28:43 +00001155 LII = LI.addSegment(S);
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001156 } else if (LII->start != instrIdx.getRegSlot()) {
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001157 VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
1158 VNInfoAllocator);
Matthias Braun87a86052013-10-10 21:28:47 +00001159 LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
Matthias Braun331de112013-10-10 21:28:43 +00001160 LII = LI.addSegment(S);
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001161 }
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001162
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001163 if (MO.getSubReg() && !MO.isUndef())
1164 lastUseIdx = instrIdx.getRegSlot();
1165 else
1166 lastUseIdx = SlotIndex();
1167 } else if (MO.isUse()) {
1168 // FIXME: This should probably be handled outside of this branch,
1169 // either as part of the def case (for defs inside of the region) or
1170 // after the loop over the region.
1171 if (!isEndValid && !LII->end.isBlock())
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001172 LII->end = instrIdx.getRegSlot();
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001173 if (!lastUseIdx.isValid())
1174 lastUseIdx = instrIdx.getRegSlot();
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001175 }
1176 }
1177 }
1178 }
1179}