blob: 9b99de75560c560f3326e5690d45e0dfed037eb8 [file] [log] [blame]
Chris Lattner85638332004-07-23 17:56:30 +00001//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Evlogimenos0e9ded72003-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
Matthias Braunac697c52016-02-18 05:21:43 +000012// basic blocks of the function in DFS order and uses the
13// LiveVariables pass to conservatively compute live intervals for
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000014// each virtual and physical register.
15//
16//===----------------------------------------------------------------------===//
17
Chris Lattnerb1f89822005-09-21 04:19:09 +000018#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "LiveRangeCalc.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/STLExtras.h"
Dan Gohman09b04482008-07-25 00:02:30 +000022#include "llvm/Analysis/AliasAnalysis.h"
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000023#include "llvm/CodeGen/LiveVariables.h"
Michael Gottesman9f49d742013-12-14 00:53:32 +000024#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +000025#include "llvm/CodeGen/MachineDominators.h"
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000026#include "llvm/CodeGen/MachineInstr.h"
Chris Lattnera10fff52007-12-31 04:13:23 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000028#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000029#include "llvm/CodeGen/VirtRegMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Value.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000031#include "llvm/Support/BlockFrequency.h"
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +000032#include "llvm/Support/CommandLine.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000034#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000038#include "llvm/Target/TargetSubtargetInfo.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000039#include <algorithm>
Jeff Cohencc08c832006-12-02 02:22:01 +000040#include <cmath>
Chandler Carruthed0881b2012-12-03 16:50:05 +000041#include <limits>
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000042using namespace llvm;
43
Chandler Carruth1b9dde02014-04-22 02:02:50 +000044#define DEBUG_TYPE "regalloc"
45
Devang Patel8c78a0b2007-05-03 01:11:54 +000046char LiveIntervals::ID = 0;
Jakob Stoklund Olesen1c465892012-08-03 22:12:54 +000047char &llvm::LiveIntervalsID = LiveIntervals::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +000048INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
49 "Live Interval Analysis", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +000050INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Matthias Braunac697c52016-02-18 05:21:43 +000051INITIALIZE_PASS_DEPENDENCY(LiveVariables)
Andrew Trickd3f8fe82012-02-10 04:10:36 +000052INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Owen Anderson8ac477f2010-10-12 19:48:12 +000053INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
Owen Anderson8ac477f2010-10-12 19:48:12 +000054INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
Owen Andersondf7a4f22010-10-07 22:25:06 +000055 "Live Interval Analysis", false, false)
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000056
Andrew Trick8d02e912013-06-21 18:33:23 +000057#ifndef NDEBUG
58static cl::opt<bool> EnablePrecomputePhysRegs(
59 "precompute-phys-liveness", cl::Hidden,
60 cl::desc("Eagerly compute live intervals for all physreg units."));
61#else
62static bool EnablePrecomputePhysRegs = false;
63#endif // NDEBUG
64
Matthias Braune3d3b882014-12-10 01:12:30 +000065static cl::opt<bool> EnableSubRegLiveness(
66 "enable-subreg-liveness", cl::Hidden, cl::init(true),
67 cl::desc("Enable subregister liveness tracking."));
68
Quentin Colombeta8cb36e2015-02-06 18:42:41 +000069namespace llvm {
70cl::opt<bool> UseSegmentSetForPhysRegs(
71 "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
72 cl::desc(
73 "Use segment set for the computation of the live ranges of physregs."));
74}
75
Chris Lattnerbdf12102006-08-24 22:43:55 +000076void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman04023152009-07-31 23:37:33 +000077 AU.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +000078 AU.addRequired<AAResultsWrapperPass>();
79 AU.addPreserved<AAResultsWrapperPass>();
Matthias Braunac697c52016-02-18 05:21:43 +000080 // LiveVariables isn't really required by this analysis, it is only required
81 // here to make sure it is live during TwoAddressInstructionPass and
82 // PHIElimination. This is temporary.
83 AU.addRequired<LiveVariables>();
Evan Cheng16bfe5b2010-08-17 21:00:37 +000084 AU.addPreserved<LiveVariables>();
Andrew Trick5188c002012-02-13 20:44:42 +000085 AU.addPreservedID(MachineLoopInfoID);
Jakob Stoklund Olesen51c63e62012-06-20 23:31:34 +000086 AU.addRequiredTransitiveID(MachineDominatorsID);
Bill Wendling0c209432008-01-04 20:54:55 +000087 AU.addPreservedID(MachineDominatorsID);
Lang Hames05fb9632009-11-03 23:52:08 +000088 AU.addPreserved<SlotIndexes>();
89 AU.addRequiredTransitive<SlotIndexes>();
Alkis Evlogimenosa6983082004-08-04 09:46:26 +000090 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000091}
92
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +000093LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
Craig Topperc0196b12014-04-14 00:51:57 +000094 DomTree(nullptr), LRCalc(nullptr) {
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +000095 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
96}
97
98LiveIntervals::~LiveIntervals() {
99 delete LRCalc;
100}
101
Chris Lattnerbdf12102006-08-24 22:43:55 +0000102void LiveIntervals::releaseMemory() {
Owen Anderson51f689a2008-08-13 21:49:13 +0000103 // Free the live intervals themselves.
Jakob Stoklund Olesenc61edda2012-06-22 20:37:52 +0000104 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
105 delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
106 VirtRegIntervals.clear();
Jakob Stoklund Olesen3ff74d82012-02-08 17:33:45 +0000107 RegMaskSlots.clear();
108 RegMaskBits.clear();
Jakob Stoklund Olesen25c41952012-02-10 01:26:29 +0000109 RegMaskBlocks.clear();
Lang Hamesdab7b062009-07-09 03:57:02 +0000110
Matthias Braun34e1be92013-10-10 21:29:02 +0000111 for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
112 delete RegUnitRanges[i];
113 RegUnitRanges.clear();
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000114
Benjamin Kramera0000022010-06-26 11:30:59 +0000115 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
116 VNInfoAllocator.Reset();
Alkis Evlogimenos50d97e32004-01-31 19:59:32 +0000117}
118
Jakob Stoklund Olesen6d13b8f2013-08-14 17:28:46 +0000119/// runOnMachineFunction - calculates LiveIntervals
Owen Anderson4f8e1ad2008-05-28 20:54:50 +0000120///
121bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +0000122 MF = &fn;
123 MRI = &MF->getRegInfo();
Eric Christopherd3fa4402014-10-14 06:26:53 +0000124 TRI = MF->getSubtarget().getRegisterInfo();
125 TII = MF->getSubtarget().getInstrInfo();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000126 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +0000127 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesen51c63e62012-06-20 23:31:34 +0000128 DomTree = &getAnalysis<MachineDominatorTree>();
Matthias Braune3d3b882014-12-10 01:12:30 +0000129
130 if (EnableSubRegLiveness && MF->getSubtarget().enableSubRegLiveness())
131 MRI->enableSubRegLiveness(true);
132
Jakob Stoklund Olesen51c63e62012-06-20 23:31:34 +0000133 if (!LRCalc)
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000134 LRCalc = new LiveRangeCalc();
Owen Anderson4f8e1ad2008-05-28 20:54:50 +0000135
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +0000136 // Allocate space for all virtual registers.
137 VirtRegIntervals.resize(MRI->getNumVirtRegs());
138
Jakob Stoklund Olesenfac770b2013-02-09 00:04:07 +0000139 computeVirtRegs();
140 computeRegMasks();
Jakob Stoklund Olesen51c63e62012-06-20 23:31:34 +0000141 computeLiveInRegUnits();
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000142
Andrew Trick8d02e912013-06-21 18:33:23 +0000143 if (EnablePrecomputePhysRegs) {
144 // For stress testing, precompute live ranges of all physical register
145 // units, including reserved registers.
146 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
147 getRegUnit(i);
148 }
Chris Lattnerb0b707f2004-09-30 15:59:17 +0000149 DEBUG(dump());
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000150 return true;
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000151}
152
Chris Lattnerb0b707f2004-09-30 15:59:17 +0000153/// print - Implement the dump method.
Chris Lattner13626022009-08-23 06:03:38 +0000154void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
Chris Lattnera6f074f2009-08-23 03:41:05 +0000155 OS << "********** INTERVALS **********\n";
Jakob Stoklund Olesen20d25a72012-02-14 23:46:21 +0000156
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000157 // Dump the regunits.
Matthias Braun34e1be92013-10-10 21:29:02 +0000158 for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
159 if (LiveRange *LR = RegUnitRanges[i])
Matthias Braunf6fe6bf2013-10-10 21:29:05 +0000160 OS << PrintRegUnit(i, TRI) << ' ' << *LR << '\n';
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000161
Jakob Stoklund Olesen20d25a72012-02-14 23:46:21 +0000162 // Dump the virtregs.
Jakob Stoklund Olesenc61edda2012-06-22 20:37:52 +0000163 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
164 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
165 if (hasInterval(Reg))
Matthias Braunf6fe6bf2013-10-10 21:29:05 +0000166 OS << getInterval(Reg) << '\n';
Jakob Stoklund Olesenc61edda2012-06-22 20:37:52 +0000167 }
Chris Lattnerb0b707f2004-09-30 15:59:17 +0000168
Jakob Stoklund Olesen13d55622012-11-09 19:18:49 +0000169 OS << "RegMasks:";
170 for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
171 OS << ' ' << RegMaskSlots[i];
172 OS << '\n';
173
Evan Cheng7f789592009-09-14 21:33:42 +0000174 printInstrs(OS);
175}
176
177void LiveIntervals::printInstrs(raw_ostream &OS) const {
Chris Lattnera6f074f2009-08-23 03:41:05 +0000178 OS << "********** MACHINEINSTRS **********\n";
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +0000179 MF->print(OS, Indexes);
Chris Lattnerb0b707f2004-09-30 15:59:17 +0000180}
181
Manman Ren19f49ac2012-09-11 22:23:19 +0000182#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Evan Cheng7f789592009-09-14 21:33:42 +0000183void LiveIntervals::dumpInstrs() const {
David Greene1a51a212010-01-04 22:49:02 +0000184 printInstrs(dbgs());
Evan Cheng7f789592009-09-14 21:33:42 +0000185}
Manman Ren742534c2012-09-06 19:06:06 +0000186#endif
Evan Cheng7f789592009-09-14 21:33:42 +0000187
Owen Anderson51f689a2008-08-13 21:49:13 +0000188LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Aaron Ballman04999042013-11-13 00:15:44 +0000189 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
190 llvm::huge_valf : 0.0F;
Owen Anderson51f689a2008-08-13 21:49:13 +0000191 return new LiveInterval(reg, Weight);
Alkis Evlogimenos237f2032004-04-09 18:07:57 +0000192}
Evan Chengbe51f282007-11-12 06:35:08 +0000193
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000194
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +0000195/// computeVirtRegInterval - Compute the live interval of a virtual register,
196/// based on defs and uses.
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000197void LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +0000198 assert(LRCalc && "LRCalc not initialized.");
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000199 assert(LI.empty() && "Should only compute empty intervals.");
Matthias Braun73e42212015-09-22 22:37:44 +0000200 bool ShouldTrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(LI.reg);
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +0000201 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
Matthias Braun73e42212015-09-22 22:37:44 +0000202 LRCalc->calculate(LI, ShouldTrackSubRegLiveness);
203 bool SeparatedComponents = computeDeadValues(LI, nullptr);
204 if (SeparatedComponents) {
205 assert(ShouldTrackSubRegLiveness
206 && "Separated components should only occur for unused subreg defs");
207 SmallVector<LiveInterval*, 8> SplitLIs;
208 splitSeparateComponents(LI, SplitLIs);
209 }
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +0000210}
211
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000212void LiveIntervals::computeVirtRegs() {
213 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
214 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
215 if (MRI->reg_nodbg_empty(Reg))
216 continue;
Mark Lacey9d8103d2013-08-14 23:50:16 +0000217 createAndComputeVirtRegInterval(Reg);
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000218 }
219}
220
221void LiveIntervals::computeRegMasks() {
222 RegMaskBlocks.resize(MF->getNumBlockIDs());
223
224 // Find all instructions with regmask operands.
Reid Klecknere535c1f2015-11-06 02:01:02 +0000225 for (MachineBasicBlock &MBB : *MF) {
226 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()];
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000227 RMB.first = RegMaskSlots.size();
Reid Klecknerb8fd1622015-11-06 17:06:38 +0000228
229 // Some block starts, such as EH funclets, create masks.
230 if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) {
231 RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
232 RegMaskBits.push_back(Mask);
233 }
234
Reid Klecknere535c1f2015-11-06 02:01:02 +0000235 for (MachineInstr &MI : MBB) {
236 for (const MachineOperand &MO : MI.operands()) {
Matthias Braune41e1462015-05-29 02:56:46 +0000237 if (!MO.isRegMask())
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000238 continue;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000239 RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
Reid Klecknere535c1f2015-11-06 02:01:02 +0000240 RegMaskBits.push_back(MO.getRegMask());
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000241 }
Reid Klecknere535c1f2015-11-06 02:01:02 +0000242 }
Reid Klecknerb8fd1622015-11-06 17:06:38 +0000243
Reid Kleckner70c9bc72016-02-26 16:53:19 +0000244 // Some block ends, such as funclet returns, create masks. Put the mask on
245 // the last instruction of the block, because MBB slot index intervals are
246 // half-open.
Reid Klecknerb8fd1622015-11-06 17:06:38 +0000247 if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) {
Reid Kleckner70c9bc72016-02-26 16:53:19 +0000248 assert(!MBB.empty() && "empty return block?");
249 RegMaskSlots.push_back(
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000250 Indexes->getInstructionIndex(MBB.back()).getRegSlot());
Reid Klecknerb8fd1622015-11-06 17:06:38 +0000251 RegMaskBits.push_back(Mask);
252 }
253
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000254 // Compute the number of register mask instructions in this block.
Dmitri Gribenkoca1e27b2012-09-10 21:26:47 +0000255 RMB.second = RegMaskSlots.size() - RMB.first;
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000256 }
257}
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +0000258
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000259//===----------------------------------------------------------------------===//
260// Register Unit Liveness
261//===----------------------------------------------------------------------===//
262//
263// Fixed interference typically comes from ABI boundaries: Function arguments
264// and return values are passed in fixed registers, and so are exception
265// pointers entering landing pads. Certain instructions require values to be
266// present in specific registers. That is also represented through fixed
267// interference.
268//
269
Matthias Braun34e1be92013-10-10 21:29:02 +0000270/// computeRegUnitInterval - Compute the live range of a register unit, based
271/// on the uses and defs of aliasing registers. The range should be empty,
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000272/// or contain only dead phi-defs from ABI blocks.
Matthias Braun34e1be92013-10-10 21:29:02 +0000273void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000274 assert(LRCalc && "LRCalc not initialized.");
275 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
276
277 // The physregs aliasing Unit are the roots and their super-registers.
278 // Create all values as dead defs before extending to uses. Note that roots
279 // may share super-registers. That's OK because createDeadDefs() is
280 // idempotent. It is very rare for a register unit to have multiple roots, so
281 // uniquing super-registers is probably not worthwhile.
282 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
Chad Rosier682ae152013-05-22 22:36:55 +0000283 for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
284 Supers.isValid(); ++Supers) {
Matthias Braunc3a72c22014-12-15 21:36:35 +0000285 if (!MRI->reg_empty(*Supers))
286 LRCalc->createDeadDefs(LR, *Supers);
287 }
288 }
289
290 // Now extend LR to reach all uses.
291 // Ignore uses of reserved registers. We only track defs of those.
292 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
293 for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
294 Supers.isValid(); ++Supers) {
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000295 unsigned Reg = *Supers;
Matthias Braunc3a72c22014-12-15 21:36:35 +0000296 if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
297 LRCalc->extendToUses(LR, Reg);
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000298 }
299 }
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000300
301 // Flush the segment set to the segment vector.
302 if (UseSegmentSetForPhysRegs)
303 LR.flushSegmentSet();
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000304}
305
306
307/// computeLiveInRegUnits - Precompute the live ranges of any register units
308/// that are live-in to an ABI block somewhere. Register values can appear
309/// without a corresponding def when entering the entry block or a landing pad.
310///
311void LiveIntervals::computeLiveInRegUnits() {
Matthias Braun34e1be92013-10-10 21:29:02 +0000312 RegUnitRanges.resize(TRI->getNumRegUnits());
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000313 DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
314
Matthias Braun34e1be92013-10-10 21:29:02 +0000315 // Keep track of the live range sets allocated.
316 SmallVector<unsigned, 8> NewRanges;
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000317
318 // Check all basic blocks for live-ins.
319 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
320 MFI != MFE; ++MFI) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000321 const MachineBasicBlock *MBB = &*MFI;
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000322
323 // We only care about ABI blocks: Entry + landing pads.
Reid Kleckner0e288232015-08-27 23:27:47 +0000324 if ((MFI != MF->begin() && !MBB->isEHPad()) || MBB->livein_empty())
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000325 continue;
326
327 // Create phi-defs at Begin for all live-in registers.
328 SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
329 DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
Matthias Braund9da1622015-09-09 18:08:03 +0000330 for (const auto &LI : MBB->liveins()) {
331 for (MCRegUnitIterator Units(LI.PhysReg, TRI); Units.isValid(); ++Units) {
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000332 unsigned Unit = *Units;
Matthias Braun34e1be92013-10-10 21:29:02 +0000333 LiveRange *LR = RegUnitRanges[Unit];
334 if (!LR) {
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000335 // Use segment set to speed-up initial computation of the live range.
336 LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
Matthias Braun34e1be92013-10-10 21:29:02 +0000337 NewRanges.push_back(Unit);
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000338 }
Matthias Braun34e1be92013-10-10 21:29:02 +0000339 VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
Matt Beaumont-Gay7ba769b2012-06-05 23:00:03 +0000340 (void)VNI;
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000341 DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
342 }
343 }
344 DEBUG(dbgs() << '\n');
345 }
Matthias Braun34e1be92013-10-10 21:29:02 +0000346 DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000347
Matthias Braun34e1be92013-10-10 21:29:02 +0000348 // Compute the 'normal' part of the ranges.
349 for (unsigned i = 0, e = NewRanges.size(); i != e; ++i) {
350 unsigned Unit = NewRanges[i];
351 computeRegUnitRange(*RegUnitRanges[Unit], Unit);
352 }
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000353}
354
355
Matthias Braun20e1f382014-12-10 01:12:18 +0000356static void createSegmentsForValues(LiveRange &LR,
357 iterator_range<LiveInterval::vni_iterator> VNIs) {
358 for (auto VNI : VNIs) {
359 if (VNI->isUnused())
360 continue;
361 SlotIndex Def = VNI->def;
362 LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
363 }
364}
365
366typedef SmallVector<std::pair<SlotIndex, VNInfo*>, 16> ShrinkToUsesWorkList;
367
368static void extendSegmentsToUses(LiveRange &LR, const SlotIndexes &Indexes,
369 ShrinkToUsesWorkList &WorkList,
370 const LiveRange &OldRange) {
371 // Keep track of the PHIs that are in use.
372 SmallPtrSet<VNInfo*, 8> UsedPHIs;
373 // Blocks that have already been added to WorkList as live-out.
374 SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
375
376 // Extend intervals to reach all uses in WorkList.
377 while (!WorkList.empty()) {
378 SlotIndex Idx = WorkList.back().first;
379 VNInfo *VNI = WorkList.back().second;
380 WorkList.pop_back();
381 const MachineBasicBlock *MBB = Indexes.getMBBFromIndex(Idx.getPrevSlot());
382 SlotIndex BlockStart = Indexes.getMBBStartIdx(MBB);
383
384 // Extend the live range for VNI to be live at Idx.
385 if (VNInfo *ExtVNI = LR.extendInBlock(BlockStart, Idx)) {
386 assert(ExtVNI == VNI && "Unexpected existing value number");
387 (void)ExtVNI;
388 // Is this a PHIDef we haven't seen before?
389 if (!VNI->isPHIDef() || VNI->def != BlockStart ||
390 !UsedPHIs.insert(VNI).second)
391 continue;
392 // The PHI is live, make sure the predecessors are live-out.
393 for (auto &Pred : MBB->predecessors()) {
394 if (!LiveOut.insert(Pred).second)
395 continue;
396 SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
397 // A predecessor is not required to have a live-out value for a PHI.
398 if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
399 WorkList.push_back(std::make_pair(Stop, PVNI));
400 }
401 continue;
402 }
403
404 // VNI is live-in to MBB.
405 DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
406 LR.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
407
408 // Make sure VNI is live-out from the predecessors.
409 for (auto &Pred : MBB->predecessors()) {
410 if (!LiveOut.insert(Pred).second)
411 continue;
412 SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
413 assert(OldRange.getVNInfoBefore(Stop) == VNI &&
414 "Wrong value out of predecessor");
415 WorkList.push_back(std::make_pair(Stop, VNI));
416 }
417 }
418}
419
Jakob Stoklund Olesen86308402011-03-17 20:37:07 +0000420bool LiveIntervals::shrinkToUses(LiveInterval *li,
Jakob Stoklund Olesen71c380f2011-03-07 23:29:10 +0000421 SmallVectorImpl<MachineInstr*> *dead) {
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000422 DEBUG(dbgs() << "Shrink: " << *li << '\n');
423 assert(TargetRegisterInfo::isVirtualRegister(li->reg)
Lang Hamesc405ac42012-01-03 20:05:57 +0000424 && "Can only shrink virtual registers");
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000425
Matthias Braun20e1f382014-12-10 01:12:18 +0000426 // Shrink subregister live ranges.
Matthias Braun0d4cebd2015-07-16 18:55:35 +0000427 bool NeedsCleanup = false;
Matthias Braun09afa1e2014-12-11 00:59:06 +0000428 for (LiveInterval::SubRange &S : li->subranges()) {
429 shrinkToUses(S, li->reg);
Matthias Braun0d4cebd2015-07-16 18:55:35 +0000430 if (S.empty())
431 NeedsCleanup = true;
Matthias Braun20e1f382014-12-10 01:12:18 +0000432 }
Matthias Braun0d4cebd2015-07-16 18:55:35 +0000433 if (NeedsCleanup)
434 li->removeEmptySubRanges();
Matthias Braun20e1f382014-12-10 01:12:18 +0000435
436 // Find all the values used, including PHI kills.
437 ShrinkToUsesWorkList WorkList;
Jakob Stoklund Olesenb8b1d4c2011-09-15 15:24:16 +0000438
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000439 // Visit all instructions reading li->reg.
Owen Andersonabb90c92014-03-13 06:02:25 +0000440 for (MachineRegisterInfo::reg_instr_iterator
441 I = MRI->reg_instr_begin(li->reg), E = MRI->reg_instr_end();
442 I != E; ) {
443 MachineInstr *UseMI = &*(I++);
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000444 if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
445 continue;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000446 SlotIndex Idx = getInstructionIndex(*UseMI).getRegSlot();
Matthias Braun88dd0ab2013-10-10 21:28:52 +0000447 LiveQueryResult LRQ = li->Query(Idx);
Jakob Stoklund Olesen02d83e32012-05-20 02:54:52 +0000448 VNInfo *VNI = LRQ.valueIn();
Jakob Stoklund Olesenfdc09942011-03-18 03:06:04 +0000449 if (!VNI) {
450 // This shouldn't happen: readsVirtualRegister returns true, but there is
451 // no live value. It is likely caused by a target getting <undef> flags
452 // wrong.
453 DEBUG(dbgs() << Idx << '\t' << *UseMI
454 << "Warning: Instr claims to read non-existent value in "
455 << *li << '\n');
456 continue;
457 }
Jakob Stoklund Olesen7e6004a2011-11-14 18:45:38 +0000458 // Special case: An early-clobber tied operand reads and writes the
Jakob Stoklund Olesen02d83e32012-05-20 02:54:52 +0000459 // register one slot early.
460 if (VNInfo *DefVNI = LRQ.valueDefined())
461 Idx = DefVNI->def;
462
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000463 WorkList.push_back(std::make_pair(Idx, VNI));
464 }
465
Matthias Braund7df9352013-10-10 21:28:47 +0000466 // Create new live ranges with only minimal live segments per def.
467 LiveRange NewLR;
Matthias Braun20e1f382014-12-10 01:12:18 +0000468 createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end()));
469 extendSegmentsToUses(NewLR, *Indexes, WorkList, *li);
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000470
Pete Cooper72235572014-06-03 22:42:10 +0000471 // Move the trimmed segments back.
472 li->segments.swap(NewLR.segments);
Matthias Braun15abf372014-12-18 19:58:52 +0000473
474 // Handle dead values.
475 bool CanSeparate = computeDeadValues(*li, dead);
Pete Cooper72235572014-06-03 22:42:10 +0000476 DEBUG(dbgs() << "Shrunk: " << *li << '\n');
477 return CanSeparate;
478}
479
Matthias Braun15abf372014-12-18 19:58:52 +0000480bool LiveIntervals::computeDeadValues(LiveInterval &LI,
Pete Cooper72235572014-06-03 22:42:10 +0000481 SmallVectorImpl<MachineInstr*> *dead) {
Matthias Braun73e42212015-09-22 22:37:44 +0000482 bool MayHaveSplitComponents = false;
Matthias Braun15abf372014-12-18 19:58:52 +0000483 for (auto VNI : LI.valnos) {
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000484 if (VNI->isUnused())
485 continue;
Matthias Braunc1988f32015-01-21 22:55:13 +0000486 SlotIndex Def = VNI->def;
487 LiveRange::iterator I = LI.FindSegmentContaining(Def);
Matthias Braun15abf372014-12-18 19:58:52 +0000488 assert(I != LI.end() && "Missing segment for VNI");
Matthias Braunc1988f32015-01-21 22:55:13 +0000489
490 // Is the register live before? Otherwise we may have to add a read-undef
491 // flag for subregister defs.
Matthias Braun73e42212015-09-22 22:37:44 +0000492 bool DeadBeforeDef = false;
493 unsigned VReg = LI.reg;
494 if (MRI->shouldTrackSubRegLiveness(VReg)) {
Matthias Braunc1988f32015-01-21 22:55:13 +0000495 if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
496 MachineInstr *MI = getInstructionFromIndex(Def);
Matthias Braun2c98d0f2015-11-11 00:41:58 +0000497 MI->setRegisterDefReadUndef(VReg);
Matthias Braun73e42212015-09-22 22:37:44 +0000498 DeadBeforeDef = true;
Matthias Braunc1988f32015-01-21 22:55:13 +0000499 }
500 }
501
502 if (I->end != Def.getDeadSlot())
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000503 continue;
Jakob Stoklund Olesen81eb18d2011-03-02 00:33:01 +0000504 if (VNI->isPHIDef()) {
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000505 // This is a dead PHI. Remove it.
Jakob Stoklund Olesendaae19f2012-08-03 20:59:32 +0000506 VNI->markUnused();
Matthias Braun15abf372014-12-18 19:58:52 +0000507 LI.removeSegment(I);
Matthias Braunc1988f32015-01-21 22:55:13 +0000508 DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
Matthias Braun73e42212015-09-22 22:37:44 +0000509 MayHaveSplitComponents = true;
Matthias Braun15abf372014-12-18 19:58:52 +0000510 } else {
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000511 // This is a dead def. Make sure the instruction knows.
Matthias Braunc1988f32015-01-21 22:55:13 +0000512 MachineInstr *MI = getInstructionFromIndex(Def);
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000513 assert(MI && "No instruction defining live value");
Matthias Braun73e42212015-09-22 22:37:44 +0000514 MI->addRegisterDead(VReg, TRI);
515
516 // If we have a dead def that is completely separate from the rest of
517 // the liverange then we rewrite it to use a different VReg to not violate
518 // the rule that the liveness of a virtual register forms a connected
519 // component. This should only happen if subregister liveness is tracked.
520 if (DeadBeforeDef)
521 MayHaveSplitComponents = true;
522
Jakob Stoklund Olesen71c380f2011-03-07 23:29:10 +0000523 if (dead && MI->allDefsAreDead()) {
Matthias Braunc1988f32015-01-21 22:55:13 +0000524 DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
Jakob Stoklund Olesen71c380f2011-03-07 23:29:10 +0000525 dead->push_back(MI);
526 }
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000527 }
528 }
Matthias Braun73e42212015-09-22 22:37:44 +0000529 return MayHaveSplitComponents;
Matthias Braun20e1f382014-12-10 01:12:18 +0000530}
531
Matthias Braun15abf372014-12-18 19:58:52 +0000532void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg)
Matthias Braun20e1f382014-12-10 01:12:18 +0000533{
534 DEBUG(dbgs() << "Shrink: " << SR << '\n');
535 assert(TargetRegisterInfo::isVirtualRegister(Reg)
536 && "Can only shrink virtual registers");
537 // Find all the values used, including PHI kills.
538 ShrinkToUsesWorkList WorkList;
539
540 // Visit all instructions reading Reg.
541 SlotIndex LastIdx;
542 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
543 MachineInstr *UseMI = MO.getParent();
544 if (UseMI->isDebugValue())
545 continue;
546 // Maybe the operand is for a subregister we don't care about.
547 unsigned SubReg = MO.getSubReg();
548 if (SubReg != 0) {
Matthias Braune6a24852015-09-25 21:51:14 +0000549 LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
550 if ((LaneMask & SR.LaneMask) == 0)
Matthias Braun20e1f382014-12-10 01:12:18 +0000551 continue;
552 }
553 // We only need to visit each instruction once.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000554 SlotIndex Idx = getInstructionIndex(*UseMI).getRegSlot();
Matthias Braun20e1f382014-12-10 01:12:18 +0000555 if (Idx == LastIdx)
556 continue;
557 LastIdx = Idx;
558
559 LiveQueryResult LRQ = SR.Query(Idx);
560 VNInfo *VNI = LRQ.valueIn();
561 // For Subranges it is possible that only undef values are left in that
562 // part of the subregister, so there is no real liverange at the use
563 if (!VNI)
564 continue;
565
566 // Special case: An early-clobber tied operand reads and writes the
567 // register one slot early.
568 if (VNInfo *DefVNI = LRQ.valueDefined())
569 Idx = DefVNI->def;
570
571 WorkList.push_back(std::make_pair(Idx, VNI));
572 }
573
574 // Create a new live ranges with only minimal live segments per def.
575 LiveRange NewLR;
576 createSegmentsForValues(NewLR, make_range(SR.vni_begin(), SR.vni_end()));
577 extendSegmentsToUses(NewLR, *Indexes, WorkList, SR);
578
Matthias Braun20e1f382014-12-10 01:12:18 +0000579 // Move the trimmed ranges back.
580 SR.segments.swap(NewLR.segments);
Matthias Braun15abf372014-12-18 19:58:52 +0000581
582 // Remove dead PHI value numbers
583 for (auto VNI : SR.valnos) {
584 if (VNI->isUnused())
585 continue;
586 const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
587 assert(Segment != nullptr && "Missing segment for VNI");
588 if (Segment->end != VNI->def.getDeadSlot())
589 continue;
590 if (VNI->isPHIDef()) {
591 // This is a dead PHI. Remove it.
592 VNI->markUnused();
593 SR.removeSegment(*Segment);
594 DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
595 }
596 }
597
Matthias Braun20e1f382014-12-10 01:12:18 +0000598 DEBUG(dbgs() << "Shrunk: " << SR << '\n');
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000599}
600
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000601void LiveIntervals::extendToIndices(LiveRange &LR,
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000602 ArrayRef<SlotIndex> Indices) {
603 assert(LRCalc && "LRCalc not initialized.");
604 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
605 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000606 LRCalc->extend(LR, Indices[i]);
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000607}
608
Matthias Braun8970d842014-12-10 01:12:36 +0000609void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000610 SmallVectorImpl<SlotIndex> *EndPoints) {
Matthias Braun8970d842014-12-10 01:12:36 +0000611 LiveQueryResult LRQ = LR.Query(Kill);
612 VNInfo *VNI = LRQ.valueOutOrDead();
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000613 if (!VNI)
614 return;
615
616 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
Matthias Braun8970d842014-12-10 01:12:36 +0000617 SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000618
619 // If VNI isn't live out from KillMBB, the value is trivially pruned.
620 if (LRQ.endPoint() < MBBEnd) {
Matthias Braun8970d842014-12-10 01:12:36 +0000621 LR.removeSegment(Kill, LRQ.endPoint());
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000622 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
623 return;
624 }
625
626 // VNI is live out of KillMBB.
Matthias Braun8970d842014-12-10 01:12:36 +0000627 LR.removeSegment(Kill, MBBEnd);
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000628 if (EndPoints) EndPoints->push_back(MBBEnd);
629
Jakob Stoklund Olesen2f6dfc72012-10-13 16:15:31 +0000630 // Find all blocks that are reachable from KillMBB without leaving VNI's live
631 // range. It is possible that KillMBB itself is reachable, so start a DFS
632 // from each successor.
633 typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
634 VisitedTy Visited;
635 for (MachineBasicBlock::succ_iterator
636 SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
637 SuccI != SuccE; ++SuccI) {
638 for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
639 I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
640 I != E;) {
641 MachineBasicBlock *MBB = *I;
642
643 // Check if VNI is live in to MBB.
Matthias Braun8970d842014-12-10 01:12:36 +0000644 SlotIndex MBBStart, MBBEnd;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000645 std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
Matthias Braun8970d842014-12-10 01:12:36 +0000646 LiveQueryResult LRQ = LR.Query(MBBStart);
Jakob Stoklund Olesen2f6dfc72012-10-13 16:15:31 +0000647 if (LRQ.valueIn() != VNI) {
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000648 // This block isn't part of the VNI segment. Prune the search.
Jakob Stoklund Olesen2f6dfc72012-10-13 16:15:31 +0000649 I.skipChildren();
650 continue;
651 }
652
653 // Prune the search if VNI is killed in MBB.
654 if (LRQ.endPoint() < MBBEnd) {
Matthias Braun8970d842014-12-10 01:12:36 +0000655 LR.removeSegment(MBBStart, LRQ.endPoint());
Jakob Stoklund Olesen2f6dfc72012-10-13 16:15:31 +0000656 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
657 I.skipChildren();
658 continue;
659 }
660
661 // VNI is live through MBB.
Matthias Braun8970d842014-12-10 01:12:36 +0000662 LR.removeSegment(MBBStart, MBBEnd);
Jakob Stoklund Olesen2f6dfc72012-10-13 16:15:31 +0000663 if (EndPoints) EndPoints->push_back(MBBEnd);
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000664 ++I;
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000665 }
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000666 }
667}
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000668
Evan Chengbe51f282007-11-12 06:35:08 +0000669//===----------------------------------------------------------------------===//
670// Register allocator hooks.
671//
672
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000673void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
674 // Keep track of regunit ranges.
Matthias Braun7f8dece2014-12-20 01:54:48 +0000675 SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
Matthias Braun714c4942014-12-20 01:54:50 +0000676 // Keep track of subregister ranges.
677 SmallVector<std::pair<const LiveInterval::SubRange*,
678 LiveRange::const_iterator>, 4> SRs;
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000679
Jakob Stoklund Olesen781e0b92012-06-20 23:23:59 +0000680 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
681 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +0000682 if (MRI->reg_nodbg_empty(Reg))
Jakob Stoklund Olesenf2b16dc2011-02-08 21:13:03 +0000683 continue;
Matthias Braun7f8dece2014-12-20 01:54:48 +0000684 const LiveInterval &LI = getInterval(Reg);
685 if (LI.empty())
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000686 continue;
687
688 // Find the regunit intervals for the assigned register. They may overlap
689 // the virtual register live range, cancelling any kills.
690 RU.clear();
691 for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
692 ++Units) {
Matthias Braun7f8dece2014-12-20 01:54:48 +0000693 const LiveRange &RURange = getRegUnit(*Units);
694 if (RURange.empty())
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000695 continue;
Matthias Braun7f8dece2014-12-20 01:54:48 +0000696 RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000697 }
Jakob Stoklund Olesenf2b16dc2011-02-08 21:13:03 +0000698
Matthias Brauna25e13a2015-03-19 00:21:58 +0000699 if (MRI->subRegLivenessEnabled()) {
Matthias Braun714c4942014-12-20 01:54:50 +0000700 SRs.clear();
701 for (const LiveInterval::SubRange &SR : LI.subranges()) {
702 SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end)));
703 }
704 }
705
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000706 // Every instruction that kills Reg corresponds to a segment range end
707 // point.
Matthias Braun7f8dece2014-12-20 01:54:48 +0000708 for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
Jakob Stoklund Olesenf2b16dc2011-02-08 21:13:03 +0000709 ++RI) {
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000710 // A block index indicates an MBB edge.
711 if (RI->end.isBlock())
Jakob Stoklund Olesenf2b16dc2011-02-08 21:13:03 +0000712 continue;
713 MachineInstr *MI = getInstructionFromIndex(RI->end);
714 if (!MI)
715 continue;
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000716
Matthias Braunc9d5c0f2013-10-04 16:52:58 +0000717 // Check if any of the regunits are live beyond the end of RI. That could
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000718 // happen when a physreg is defined as a copy of a virtreg:
719 //
720 // %EAX = COPY %vreg5
721 // FOO %vreg5 <--- MI, cancel kill because %EAX is live.
722 // BAR %EAX<kill>
723 //
724 // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
Matthias Braun7f8dece2014-12-20 01:54:48 +0000725 for (auto &RUP : RU) {
726 const LiveRange &RURange = *RUP.first;
Matthias Braunf603c882014-12-24 02:11:43 +0000727 LiveRange::const_iterator &I = RUP.second;
Matthias Braun7f8dece2014-12-20 01:54:48 +0000728 if (I == RURange.end())
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000729 continue;
Matthias Braun7f8dece2014-12-20 01:54:48 +0000730 I = RURange.advanceTo(I, RI->end);
731 if (I == RURange.end() || I->start >= RI->end)
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000732 continue;
733 // I is overlapping RI.
Matthias Braun714c4942014-12-20 01:54:50 +0000734 goto CancelKill;
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000735 }
Matthias Braund70caaf2014-12-10 01:13:04 +0000736
Matthias Brauna25e13a2015-03-19 00:21:58 +0000737 if (MRI->subRegLivenessEnabled()) {
Matthias Braun714c4942014-12-20 01:54:50 +0000738 // When reading a partial undefined value we must not add a kill flag.
739 // The regalloc might have used the undef lane for something else.
740 // Example:
741 // %vreg1 = ... ; R32: %vreg1
742 // %vreg2:high16 = ... ; R64: %vreg2
743 // = read %vreg2<kill> ; R64: %vreg2
744 // = read %vreg1 ; R32: %vreg1
745 // The <kill> flag is correct for %vreg2, but the register allocator may
746 // assign R0L to %vreg1, and R0 to %vreg2 because the low 32bits of R0
747 // are actually never written by %vreg2. After assignment the <kill>
748 // flag at the read instruction is invalid.
Matthias Braune6a24852015-09-25 21:51:14 +0000749 LaneBitmask DefinedLanesMask;
Matthias Braun714c4942014-12-20 01:54:50 +0000750 if (!SRs.empty()) {
751 // Compute a mask of lanes that are defined.
752 DefinedLanesMask = 0;
753 for (auto &SRP : SRs) {
754 const LiveInterval::SubRange &SR = *SRP.first;
Matthias Braunf603c882014-12-24 02:11:43 +0000755 LiveRange::const_iterator &I = SRP.second;
Matthias Braun714c4942014-12-20 01:54:50 +0000756 if (I == SR.end())
757 continue;
758 I = SR.advanceTo(I, RI->end);
759 if (I == SR.end() || I->start >= RI->end)
760 continue;
761 // I is overlapping RI
762 DefinedLanesMask |= SR.LaneMask;
Matthias Braund70caaf2014-12-10 01:13:04 +0000763 }
Matthias Braun714c4942014-12-20 01:54:50 +0000764 } else
765 DefinedLanesMask = ~0u;
766
767 bool IsFullWrite = false;
768 for (const MachineOperand &MO : MI->operands()) {
769 if (!MO.isReg() || MO.getReg() != Reg)
770 continue;
771 if (MO.isUse()) {
772 // Reading any undefined lanes?
Matthias Braune6a24852015-09-25 21:51:14 +0000773 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
Matthias Braun714c4942014-12-20 01:54:50 +0000774 if ((UseMask & ~DefinedLanesMask) != 0)
775 goto CancelKill;
776 } else if (MO.getSubReg() == 0) {
777 // Writing to the full register?
778 assert(MO.isDef());
779 IsFullWrite = true;
780 }
781 }
782
783 // If an instruction writes to a subregister, a new segment starts in
784 // the LiveInterval. But as this is only overriding part of the register
785 // adding kill-flags is not correct here after registers have been
786 // assigned.
787 if (!IsFullWrite) {
788 // Next segment has to be adjacent in the subregister write case.
789 LiveRange::const_iterator N = std::next(RI);
790 if (N != LI.end() && N->start == RI->end)
791 goto CancelKill;
Matthias Braund70caaf2014-12-10 01:13:04 +0000792 }
793 }
794
Matthias Braun714c4942014-12-20 01:54:50 +0000795 MI->addRegisterKilled(Reg, nullptr);
796 continue;
797CancelKill:
798 MI->clearRegisterKills(Reg, nullptr);
Jakob Stoklund Olesenf2b16dc2011-02-08 21:13:03 +0000799 }
800 }
801}
802
Jakob Stoklund Olesenaa06de22012-02-10 01:23:55 +0000803MachineBasicBlock*
804LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
805 // A local live range must be fully contained inside the block, meaning it is
806 // defined and killed at instructions, not at block boundaries. It is not
807 // live in or or out of any block.
808 //
809 // It is technically possible to have a PHI-defined live range identical to a
810 // single block, but we are going to return false in that case.
Lang Hames05fb9632009-11-03 23:52:08 +0000811
Jakob Stoklund Olesenaa06de22012-02-10 01:23:55 +0000812 SlotIndex Start = LI.beginIndex();
813 if (Start.isBlock())
Craig Topperc0196b12014-04-14 00:51:57 +0000814 return nullptr;
Lang Hames05fb9632009-11-03 23:52:08 +0000815
Jakob Stoklund Olesenaa06de22012-02-10 01:23:55 +0000816 SlotIndex Stop = LI.endIndex();
817 if (Stop.isBlock())
Craig Topperc0196b12014-04-14 00:51:57 +0000818 return nullptr;
Lang Hames05fb9632009-11-03 23:52:08 +0000819
Jakob Stoklund Olesenaa06de22012-02-10 01:23:55 +0000820 // getMBBFromIndex doesn't need to search the MBB table when both indexes
821 // belong to proper instructions.
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +0000822 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
823 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
Craig Topperc0196b12014-04-14 00:51:57 +0000824 return MBB1 == MBB2 ? MBB1 : nullptr;
Evan Cheng8e223792007-11-17 00:40:40 +0000825}
826
Jakob Stoklund Olesen06d6a532012-08-03 20:10:24 +0000827bool
828LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
Matthias Braun96761952014-12-10 23:07:54 +0000829 for (const VNInfo *PHI : LI.valnos) {
Jakob Stoklund Olesen06d6a532012-08-03 20:10:24 +0000830 if (PHI->isUnused() || !PHI->isPHIDef())
831 continue;
832 const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
833 // Conservatively return true instead of scanning huge predecessor lists.
834 if (PHIMBB->pred_size() > 100)
835 return true;
836 for (MachineBasicBlock::const_pred_iterator
837 PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
838 if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
839 return true;
840 }
841 return false;
842}
843
Jakob Stoklund Olesen115da882010-03-01 20:59:38 +0000844float
Michael Gottesman9f49d742013-12-14 00:53:32 +0000845LiveIntervals::getSpillWeight(bool isDef, bool isUse,
846 const MachineBlockFrequencyInfo *MBFI,
847 const MachineInstr *MI) {
848 BlockFrequency Freq = MBFI->getBlockFreq(MI->getParent());
Michael Gottesman5e985ee2013-12-14 02:37:38 +0000849 const float Scale = 1.0f / MBFI->getEntryFreq();
Michael Gottesman9f49d742013-12-14 00:53:32 +0000850 return (isDef + isUse) * (Freq.getFrequency() * Scale);
Jakob Stoklund Olesen115da882010-03-01 20:59:38 +0000851}
852
Matthias Braund7df9352013-10-10 21:28:47 +0000853LiveRange::Segment
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000854LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr &startInst) {
Mark Lacey9d8103d2013-08-14 23:50:16 +0000855 LiveInterval& Interval = createEmptyInterval(reg);
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000856 VNInfo *VN = Interval.getNextValue(
857 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
858 getVNInfoAllocator());
859 LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()),
860 getMBBEndIdx(startInst.getParent()), VN);
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000861 Interval.addSegment(S);
Jakob Stoklund Olesen073cd802010-08-12 20:01:23 +0000862
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000863 return S;
Owen Anderson35e2dfe2008-06-05 17:15:43 +0000864}
Jakob Stoklund Olesen3ff74d82012-02-08 17:33:45 +0000865
866
867//===----------------------------------------------------------------------===//
868// Register mask functions
869//===----------------------------------------------------------------------===//
870
871bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
872 BitVector &UsableRegs) {
873 if (LI.empty())
874 return false;
Jakob Stoklund Olesen9ef50bd2012-02-10 01:31:31 +0000875 LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
876
877 // Use a smaller arrays for local live ranges.
878 ArrayRef<SlotIndex> Slots;
879 ArrayRef<const uint32_t*> Bits;
880 if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
881 Slots = getRegMaskSlotsInBlock(MBB->getNumber());
882 Bits = getRegMaskBitsInBlock(MBB->getNumber());
883 } else {
884 Slots = getRegMaskSlots();
885 Bits = getRegMaskBits();
886 }
Jakob Stoklund Olesen3ff74d82012-02-08 17:33:45 +0000887
888 // We are going to enumerate all the register mask slots contained in LI.
889 // Start with a binary search of RegMaskSlots to find a starting point.
Jakob Stoklund Olesen3ff74d82012-02-08 17:33:45 +0000890 ArrayRef<SlotIndex>::iterator SlotI =
891 std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
892 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
893
894 // No slots in range, LI begins after the last call.
895 if (SlotI == SlotE)
896 return false;
897
898 bool Found = false;
899 for (;;) {
900 assert(*SlotI >= LiveI->start);
901 // Loop over all slots overlapping this segment.
902 while (*SlotI < LiveI->end) {
903 // *SlotI overlaps LI. Collect mask bits.
904 if (!Found) {
905 // This is the first overlap. Initialize UsableRegs to all ones.
906 UsableRegs.clear();
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +0000907 UsableRegs.resize(TRI->getNumRegs(), true);
Jakob Stoklund Olesen3ff74d82012-02-08 17:33:45 +0000908 Found = true;
909 }
910 // Remove usable registers clobbered by this mask.
Jakob Stoklund Olesen9ef50bd2012-02-10 01:31:31 +0000911 UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
Jakob Stoklund Olesen3ff74d82012-02-08 17:33:45 +0000912 if (++SlotI == SlotE)
913 return Found;
914 }
915 // *SlotI is beyond the current LI segment.
916 LiveI = LI.advanceTo(LiveI, *SlotI);
917 if (LiveI == LiveE)
918 return Found;
919 // Advance SlotI until it overlaps.
920 while (*SlotI < LiveI->start)
921 if (++SlotI == SlotE)
922 return Found;
923 }
924}
Lang Hamesb9057d52012-02-17 18:44:18 +0000925
926//===----------------------------------------------------------------------===//
927// IntervalUpdate class.
928//===----------------------------------------------------------------------===//
929
Lang Hames7e2ce882012-02-21 00:00:36 +0000930// HMEditor is a toolkit used by handleMove to trim or extend live intervals.
Lang Hamesb9057d52012-02-17 18:44:18 +0000931class LiveIntervals::HMEditor {
932private:
Lang Hames59761982012-02-17 23:43:40 +0000933 LiveIntervals& LIS;
934 const MachineRegisterInfo& MRI;
935 const TargetRegisterInfo& TRI;
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000936 SlotIndex OldIdx;
Lang Hames59761982012-02-17 23:43:40 +0000937 SlotIndex NewIdx;
Matthias Braun34e1be92013-10-10 21:29:02 +0000938 SmallPtrSet<LiveRange*, 8> Updated;
Andrew Trickd9d4be02012-10-16 00:22:51 +0000939 bool UpdateFlags;
Lang Hames13b11522012-02-19 07:13:05 +0000940
Lang Hamesb9057d52012-02-17 18:44:18 +0000941public:
Lang Hames59761982012-02-17 23:43:40 +0000942 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000943 const TargetRegisterInfo& TRI,
Andrew Trickd9d4be02012-10-16 00:22:51 +0000944 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
945 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
946 UpdateFlags(UpdateFlags) {}
947
948 // FIXME: UpdateFlags is a workaround that creates live intervals for all
949 // physregs, even those that aren't needed for regalloc, in order to update
950 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
951 // flags, and postRA passes will use a live register utility instead.
Matthias Braun34e1be92013-10-10 21:29:02 +0000952 LiveRange *getRegUnitLI(unsigned Unit) {
Andrew Trickd9d4be02012-10-16 00:22:51 +0000953 if (UpdateFlags)
954 return &LIS.getRegUnit(Unit);
955 return LIS.getCachedRegUnit(Unit);
956 }
Lang Hamesb9057d52012-02-17 18:44:18 +0000957
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000958 /// Update all live ranges touched by MI, assuming a move from OldIdx to
959 /// NewIdx.
960 void updateAllRanges(MachineInstr *MI) {
961 DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
962 bool hasRegMask = false;
Matthias Braune41e1462015-05-29 02:56:46 +0000963 for (MachineOperand &MO : MI->operands()) {
964 if (MO.isRegMask())
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000965 hasRegMask = true;
Matthias Braune41e1462015-05-29 02:56:46 +0000966 if (!MO.isReg())
Lang Hamesd6e765c2012-02-21 22:29:38 +0000967 continue;
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000968 // Aggressively clear all kill flags.
969 // They are reinserted by VirtRegRewriter.
Matthias Braune41e1462015-05-29 02:56:46 +0000970 if (MO.isUse())
971 MO.setIsKill(false);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000972
Matthias Braune41e1462015-05-29 02:56:46 +0000973 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000974 if (!Reg)
975 continue;
976 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Matthias Braun34e1be92013-10-10 21:29:02 +0000977 LiveInterval &LI = LIS.getInterval(Reg);
Matthias Braun7044d692014-12-10 01:12:20 +0000978 if (LI.hasSubRanges()) {
Matthias Braune41e1462015-05-29 02:56:46 +0000979 unsigned SubReg = MO.getSubReg();
Matthias Braune6a24852015-09-25 21:51:14 +0000980 LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
Matthias Braun09afa1e2014-12-11 00:59:06 +0000981 for (LiveInterval::SubRange &S : LI.subranges()) {
982 if ((S.LaneMask & LaneMask) == 0)
Matthias Braun7044d692014-12-10 01:12:20 +0000983 continue;
Matthias Braun09afa1e2014-12-11 00:59:06 +0000984 updateRange(S, Reg, S.LaneMask);
Matthias Braun7044d692014-12-10 01:12:20 +0000985 }
986 }
987 updateRange(LI, Reg, 0);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000988 continue;
989 }
990
991 // For physregs, only update the regunits that actually have a
992 // precomputed live range.
993 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
Matthias Braun34e1be92013-10-10 21:29:02 +0000994 if (LiveRange *LR = getRegUnitLI(*Units))
Matthias Braun7044d692014-12-10 01:12:20 +0000995 updateRange(*LR, *Units, 0);
Lang Hamesd6e765c2012-02-21 22:29:38 +0000996 }
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000997 if (hasRegMask)
998 updateRegMaskSlots();
Lang Hames13b11522012-02-19 07:13:05 +0000999 }
1000
Lang Hames4645a722012-02-19 03:00:30 +00001001private:
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001002 /// Update a single live range, assuming an instruction has been moved from
1003 /// OldIdx to NewIdx.
Matthias Braune6a24852015-09-25 21:51:14 +00001004 void updateRange(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
David Blaikie70573dc2014-11-19 07:49:26 +00001005 if (!Updated.insert(&LR).second)
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001006 return;
1007 DEBUG({
1008 dbgs() << " ";
Matthias Braun7044d692014-12-10 01:12:20 +00001009 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001010 dbgs() << PrintReg(Reg);
Matthias Braun7044d692014-12-10 01:12:20 +00001011 if (LaneMask != 0)
Matthias Braunc804cdb2015-09-25 21:51:24 +00001012 dbgs() << " L" << PrintLaneMask(LaneMask);
Matthias Braun7044d692014-12-10 01:12:20 +00001013 } else {
Matthias Braun34e1be92013-10-10 21:29:02 +00001014 dbgs() << PrintRegUnit(Reg, &TRI);
Matthias Braun7044d692014-12-10 01:12:20 +00001015 }
Matthias Braun34e1be92013-10-10 21:29:02 +00001016 dbgs() << ":\t" << LR << '\n';
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001017 });
1018 if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
Matthias Braun34e1be92013-10-10 21:29:02 +00001019 handleMoveDown(LR);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001020 else
Matthias Braun7044d692014-12-10 01:12:20 +00001021 handleMoveUp(LR, Reg, LaneMask);
Matthias Braun34e1be92013-10-10 21:29:02 +00001022 DEBUG(dbgs() << " -->\t" << LR << '\n');
1023 LR.verify();
Lang Hamesb9057d52012-02-17 18:44:18 +00001024 }
1025
Matthias Braun34e1be92013-10-10 21:29:02 +00001026 /// Update LR to reflect an instruction has been moved downwards from OldIdx
Matthias Braun242b8bb2016-01-26 00:43:50 +00001027 /// to NewIdx (OldIdx < NewIdx).
Matthias Braun34e1be92013-10-10 21:29:02 +00001028 void handleMoveDown(LiveRange &LR) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001029 LiveRange::iterator E = LR.end();
Matthias Braun242b8bb2016-01-26 00:43:50 +00001030 // Segment going into OldIdx.
1031 LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1032
1033 // No value live before or after OldIdx? Nothing to do.
1034 if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001035 return;
Lang Hames13b11522012-02-19 07:13:05 +00001036
Matthias Braun242b8bb2016-01-26 00:43:50 +00001037 LiveRange::iterator OldIdxOut;
1038 // Do we have a value live-in to OldIdx?
1039 if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001040 // If the live-in value already extends to NewIdx, there is nothing to do.
Matthias Braun242b8bb2016-01-26 00:43:50 +00001041 if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end))
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001042 return;
1043 // Aggressively remove all kill flags from the old kill point.
1044 // Kill flags shouldn't be used while live intervals exist, they will be
1045 // reinserted by VirtRegRewriter.
Matthias Braun242b8bb2016-01-26 00:43:50 +00001046 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end))
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001047 for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
1048 if (MO->isReg() && MO->isUse())
1049 MO->setIsKill(false);
Matthias Braun4a6c7282016-02-15 19:25:36 +00001050
1051 // Is there a def before NewIdx which is not OldIdx?
1052 LiveRange::iterator Next = std::next(OldIdxIn);
1053 if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) &&
1054 SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1055 // If we are here then OldIdx was just a use but not a def. We only have
1056 // to ensure liveness extends to NewIdx.
1057 LiveRange::iterator NewIdxIn =
1058 LR.advanceTo(Next, NewIdx.getBaseIndex());
1059 // Extend the segment before NewIdx if necessary.
1060 if (NewIdxIn == E ||
1061 !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) {
1062 LiveRange::iterator Prev = std::prev(NewIdxIn);
1063 Prev->end = NewIdx.getRegSlot();
1064 }
1065 return;
1066 }
1067
Matthias Braun242b8bb2016-01-26 00:43:50 +00001068 // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
Matthias Braundb320772016-01-26 01:40:48 +00001069 // invalid by overlapping ranges.
Matthias Braun242b8bb2016-01-26 00:43:50 +00001070 bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1071 OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber());
1072 // If this was not a kill, then there was no def and we're done.
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001073 if (!isKill)
1074 return;
Matthias Braun242b8bb2016-01-26 00:43:50 +00001075
1076 // Did we have a Def at OldIdx?
Matthias Braun4a6c7282016-02-15 19:25:36 +00001077 OldIdxOut = Next;
Matthias Braun242b8bb2016-01-26 00:43:50 +00001078 if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1079 return;
1080 } else {
1081 OldIdxOut = OldIdxIn;
Lang Hames13b11522012-02-19 07:13:05 +00001082 }
1083
Matthias Braun242b8bb2016-01-26 00:43:50 +00001084 // If we are here then there is a Definition at OldIdx. OldIdxOut points
1085 // to the segment starting there.
1086 assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1087 "No def?");
1088 VNInfo *OldIdxVNI = OldIdxOut->valno;
1089 assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1090
1091 // If the defined value extends beyond NewIdx, just move the beginning
1092 // of the segment to NewIdx.
1093 SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1094 if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) {
1095 OldIdxVNI->def = NewIdxDef;
1096 OldIdxOut->start = OldIdxVNI->def;
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001097 return;
1098 }
Matthias Braun242b8bb2016-01-26 00:43:50 +00001099
1100 // If we are here then we have a Definition at OldIdx which ends before
Matthias Braun4a6c7282016-02-15 19:25:36 +00001101 // NewIdx.
1102
Matthias Braun242b8bb2016-01-26 00:43:50 +00001103 // Is there an existing Def at NewIdx?
1104 LiveRange::iterator AfterNewIdx
1105 = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot());
Matthias Braun4a6c7282016-02-15 19:25:36 +00001106 bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1107 if (!OldIdxDefIsDead &&
1108 SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) {
1109 // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
1110 VNInfo *DefVNI;
1111 if (OldIdxOut != LR.begin() &&
1112 !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end,
1113 OldIdxOut->start)) {
1114 // There is no gap between OldIdxOut and its predecessor anymore,
1115 // merge them.
1116 LiveRange::iterator IPrev = std::prev(OldIdxOut);
1117 DefVNI = OldIdxVNI;
1118 IPrev->end = OldIdxOut->end;
1119 } else {
1120 // The value is live in to OldIdx
1121 LiveRange::iterator INext = std::next(OldIdxOut);
1122 assert(INext != E && "Must have following segment");
1123 // We merge OldIdxOut and its successor. As we're dealing with subreg
1124 // reordering, there is always a successor to OldIdxOut in the same BB
1125 // We don't need INext->valno anymore and will reuse for the new segment
1126 // we create later.
1127 DefVNI = INext->valno;
1128 INext->start = OldIdxOut->end;
1129 INext->valno = OldIdxVNI;
1130 INext->valno->def = INext->start;
1131 }
1132 // If NewIdx is behind the last segment, extend that and append a new one.
1133 if (AfterNewIdx == E) {
1134 // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1135 // one position.
1136 // |- ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
1137 // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
1138 std::copy(std::next(OldIdxOut), E, OldIdxOut);
1139 // The last segment is undefined now, reuse it for a dead def.
1140 LiveRange::iterator NewSegment = std::prev(E);
1141 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1142 DefVNI);
1143 DefVNI->def = NewIdxDef;
1144
1145 LiveRange::iterator Prev = std::prev(NewSegment);
1146 Prev->end = NewIdxDef;
1147 } else {
1148 // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1149 // one position.
1150 // |- ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
1151 // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
1152 std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut);
1153 LiveRange::iterator Prev = std::prev(AfterNewIdx);
1154 // We have two cases:
1155 if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) {
1156 // Case 1: NewIdx is inside a liverange. Split this liverange at
1157 // NewIdxDef into the segment "Prev" followed by "NewSegment".
1158 LiveRange::iterator NewSegment = AfterNewIdx;
1159 *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
1160 Prev->valno->def = NewIdxDef;
1161
1162 *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
1163 DefVNI->def = Prev->start;
1164 } else {
1165 // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
1166 // turn Prev into a segment from NewIdx to AfterNewIdx->start.
1167 *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
1168 DefVNI->def = NewIdxDef;
1169 assert(DefVNI != AfterNewIdx->valno);
1170 }
1171 }
1172 return;
1173 }
1174
Matthias Braun242b8bb2016-01-26 00:43:50 +00001175 if (AfterNewIdx != E &&
1176 SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) {
1177 // There is an existing def at NewIdx. The def at OldIdx is coalesced into
1178 // that value.
1179 assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
1180 LR.removeValNo(OldIdxVNI);
1181 } else {
1182 // There was no existing def at NewIdx. We need to create a dead def
1183 // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
1184 // a new segment at the place where we want to construct the dead def.
1185 // |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
1186 // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
1187 assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
1188 std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut);
1189 // We can reuse OldIdxVNI now.
1190 LiveRange::iterator NewSegment = std::prev(AfterNewIdx);
1191 VNInfo *NewSegmentVNI = OldIdxVNI;
1192 NewSegmentVNI->def = NewIdxDef;
1193 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1194 NewSegmentVNI);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001195 }
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001196 }
1197
Matthias Braun34e1be92013-10-10 21:29:02 +00001198 /// Update LR to reflect an instruction has been moved upwards from OldIdx
Matthias Braun242b8bb2016-01-26 00:43:50 +00001199 /// to NewIdx (NewIdx < OldIdx).
Matthias Braune6a24852015-09-25 21:51:14 +00001200 void handleMoveUp(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001201 LiveRange::iterator E = LR.end();
Matthias Braun242b8bb2016-01-26 00:43:50 +00001202 // Segment going into OldIdx.
1203 LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1204
1205 // No value live before or after OldIdx? Nothing to do.
1206 if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001207 return;
1208
Matthias Braun242b8bb2016-01-26 00:43:50 +00001209 LiveRange::iterator OldIdxOut;
1210 // Do we have a value live-in to OldIdx?
1211 if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1212 // If the live-in value isn't killed here, then we have no Def at
1213 // OldIdx, moreover the value must be live at NewIdx so there is nothing
1214 // to do.
1215 bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1216 if (!isKill)
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001217 return;
Matthias Braun242b8bb2016-01-26 00:43:50 +00001218
1219 // At this point we have to move OldIdxIn->end back to the nearest
Matthias Braun4a6c7282016-02-15 19:25:36 +00001220 // previous use or (dead-)def but no further than NewIdx.
1221 SlotIndex DefBeforeOldIdx
1222 = std::max(OldIdxIn->start.getDeadSlot(),
1223 NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()));
1224 OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask);
Matthias Braun242b8bb2016-01-26 00:43:50 +00001225
Matthias Braun4a6c7282016-02-15 19:25:36 +00001226 // Did we have a Def at OldIdx? If not we are done now.
Matthias Braun242b8bb2016-01-26 00:43:50 +00001227 OldIdxOut = std::next(OldIdxIn);
Matthias Braun4a6c7282016-02-15 19:25:36 +00001228 if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001229 return;
Matthias Braun242b8bb2016-01-26 00:43:50 +00001230 } else {
1231 OldIdxOut = OldIdxIn;
Matthias Braun4a6c7282016-02-15 19:25:36 +00001232 OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E;
Matthias Braun242b8bb2016-01-26 00:43:50 +00001233 }
1234
1235 // If we are here then there is a Definition at OldIdx. OldIdxOut points
1236 // to the segment starting there.
1237 assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1238 "No def?");
1239 VNInfo *OldIdxVNI = OldIdxOut->valno;
1240 assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1241 bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1242
1243 // Is there an existing def at NewIdx?
1244 SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1245 LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot());
1246 if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) {
1247 assert(NewIdxOut->valno != OldIdxVNI &&
1248 "Same value defined more than once?");
1249 // If OldIdx was a dead def remove it.
1250 if (!OldIdxDefIsDead) {
Matthias Braundb320772016-01-26 01:40:48 +00001251 // Remove segment starting at NewIdx and move begin of OldIdxOut to
1252 // NewIdx so it can take its place.
Matthias Braun242b8bb2016-01-26 00:43:50 +00001253 OldIdxVNI->def = NewIdxDef;
1254 OldIdxOut->start = NewIdxDef;
1255 LR.removeValNo(NewIdxOut->valno);
1256 } else {
Matthias Braundb320772016-01-26 01:40:48 +00001257 // Simply remove the dead def at OldIdx.
Matthias Braun242b8bb2016-01-26 00:43:50 +00001258 LR.removeValNo(OldIdxVNI);
1259 }
1260 } else {
1261 // Previously nothing was live after NewIdx, so all we have to do now is
1262 // move the begin of OldIdxOut to NewIdx.
1263 if (!OldIdxDefIsDead) {
Matthias Braun4a6c7282016-02-15 19:25:36 +00001264 // Do we have any intermediate Defs between OldIdx and NewIdx?
1265 if (OldIdxIn != E &&
1266 SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) {
1267 // OldIdx is not a dead def and NewIdx is before predecessor start.
1268 LiveRange::iterator NewIdxIn = NewIdxOut;
1269 assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
1270 const SlotIndex SplitPos = NewIdxDef;
1271
1272 // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
1273 *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
1274 OldIdxIn->valno);
1275 // OldIdxIn and OldIdxVNI are now undef and can be overridden.
1276 // We Slide [NewIdxIn, OldIdxIn) down one position.
1277 // |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
1278 // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
1279 std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut);
1280 // NewIdxIn is now considered undef so we can reuse it for the moved
1281 // value.
1282 LiveRange::iterator NewSegment = NewIdxIn;
1283 LiveRange::iterator Next = std::next(NewSegment);
1284 NewSegment->valno = OldIdxVNI;
1285 if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1286 // There is no gap between NewSegment and its predecessor.
1287 *NewSegment = LiveRange::Segment(Next->start, SplitPos,
1288 NewSegment->valno);
1289 NewSegment->valno->def = Next->start;
1290
1291 *Next = LiveRange::Segment(SplitPos, Next->end, Next->valno);
1292 Next->valno->def = SplitPos;
1293 } else {
1294 // There is a gap between NewSegment and its predecessor
1295 // Value becomes live in.
1296 *NewSegment = LiveRange::Segment(SplitPos, Next->start,
1297 NewSegment->valno);
1298 NewSegment->valno->def = SplitPos;
1299 }
1300 } else {
1301 // Leave the end point of a live def.
1302 OldIdxOut->start = NewIdxDef;
1303 OldIdxVNI->def = NewIdxDef;
1304 if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end))
1305 OldIdxIn->end = NewIdx.getRegSlot();
1306 }
Matthias Braun242b8bb2016-01-26 00:43:50 +00001307 } else {
1308 // OldIdxVNI is a dead def. It may have been moved across other values
1309 // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1310 // down one position.
1311 // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1312 // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1313 std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1314 // OldIdxVNI can be reused now to build a new dead def segment.
1315 LiveRange::iterator NewSegment = NewIdxOut;
1316 VNInfo *NewSegmentVNI = OldIdxVNI;
1317 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1318 NewSegmentVNI);
1319 NewSegmentVNI->def = NewIdxDef;
Lang Hames13b11522012-02-19 07:13:05 +00001320 }
1321 }
Lang Hames13b11522012-02-19 07:13:05 +00001322 }
1323
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001324 void updateRegMaskSlots() {
Lang Hames59761982012-02-17 23:43:40 +00001325 SmallVectorImpl<SlotIndex>::iterator RI =
1326 std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
1327 OldIdx);
Jakob Stoklund Olesen13d55622012-11-09 19:18:49 +00001328 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1329 "No RegMask at OldIdx.");
1330 *RI = NewIdx.getRegSlot();
1331 assert((RI == LIS.RegMaskSlots.begin() ||
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001332 SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1333 "Cannot move regmask instruction above another call");
1334 assert((std::next(RI) == LIS.RegMaskSlots.end() ||
1335 SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1336 "Cannot move regmask instruction below another call");
Lang Hamesa9afc6a2012-02-17 21:29:41 +00001337 }
Lang Hames4645a722012-02-19 03:00:30 +00001338
1339 // Return the last use of reg between NewIdx and OldIdx.
Matthias Braun4a6c7282016-02-15 19:25:36 +00001340 SlotIndex findLastUseBefore(SlotIndex Before, unsigned Reg,
1341 LaneBitmask LaneMask) {
Lang Hamesc3d9a3d2012-09-12 06:56:16 +00001342 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Matthias Braun4a6c7282016-02-15 19:25:36 +00001343 SlotIndex LastUse = Before;
Matthias Braun7044d692014-12-10 01:12:20 +00001344 for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
1345 unsigned SubReg = MO.getSubReg();
1346 if (SubReg != 0 && LaneMask != 0
1347 && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask) == 0)
1348 continue;
1349
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001350 const MachineInstr &MI = *MO.getParent();
Lang Hamesc3d9a3d2012-09-12 06:56:16 +00001351 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1352 if (InstSlot > LastUse && InstSlot < OldIdx)
Matthias Braun4a6c7282016-02-15 19:25:36 +00001353 LastUse = InstSlot.getRegSlot();
Lang Hamesc3d9a3d2012-09-12 06:56:16 +00001354 }
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001355 return LastUse;
Lang Hames4645a722012-02-19 03:00:30 +00001356 }
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001357
1358 // This is a regunit interval, so scanning the use list could be very
1359 // expensive. Scan upwards from OldIdx instead.
Matthias Braun4a6c7282016-02-15 19:25:36 +00001360 assert(Before < OldIdx && "Expected upwards move");
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001361 SlotIndexes *Indexes = LIS.getSlotIndexes();
Matthias Braun4a6c7282016-02-15 19:25:36 +00001362 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before);
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001363
1364 // OldIdx may not correspond to an instruction any longer, so set MII to
1365 // point to the next instruction after OldIdx, or MBB->end().
1366 MachineBasicBlock::iterator MII = MBB->end();
1367 if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1368 Indexes->getNextNonNullIndex(OldIdx)))
1369 if (MI->getParent() == MBB)
1370 MII = MI;
1371
1372 MachineBasicBlock::iterator Begin = MBB->begin();
1373 while (MII != Begin) {
1374 if ((--MII)->isDebugValue())
1375 continue;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001376 SlotIndex Idx = Indexes->getInstructionIndex(*MII);
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001377
Matthias Braun4a6c7282016-02-15 19:25:36 +00001378 // Stop searching when Before is reached.
1379 if (!SlotIndex::isEarlierInstr(Before, Idx))
1380 return Before;
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001381
1382 // Check if MII uses Reg.
1383 for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
1384 if (MO->isReg() &&
1385 TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
1386 TRI.hasRegUnit(MO->getReg(), Reg))
Matthias Braun4a6c7282016-02-15 19:25:36 +00001387 return Idx.getRegSlot();
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001388 }
Matthias Braun4a6c7282016-02-15 19:25:36 +00001389 // Didn't reach Before. It must be the first instruction in the block.
1390 return Before;
Lang Hames4645a722012-02-19 03:00:30 +00001391 }
Lang Hamesb9057d52012-02-17 18:44:18 +00001392};
1393
Andrew Trickd9d4be02012-10-16 00:22:51 +00001394void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001395 assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001396 SlotIndex OldIndex = Indexes->getInstructionIndex(*MI);
1397 Indexes->removeMachineInstrFromMaps(*MI);
1398 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(*MI);
Lang Hames59761982012-02-17 23:43:40 +00001399 assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1400 OldIndex < getMBBEndIdx(MI->getParent()) &&
Lang Hamesb9057d52012-02-17 18:44:18 +00001401 "Cannot handle moves across basic block boundaries.");
Lang Hamesb9057d52012-02-17 18:44:18 +00001402
Andrew Trickd9d4be02012-10-16 00:22:51 +00001403 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001404 HME.updateAllRanges(MI);
Lang Hamesd6e765c2012-02-21 22:29:38 +00001405}
1406
Jakob Stoklund Olesen2db11252012-06-19 22:50:53 +00001407void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
Andrew Trickd9d4be02012-10-16 00:22:51 +00001408 MachineInstr* BundleStart,
1409 bool UpdateFlags) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001410 SlotIndex OldIndex = Indexes->getInstructionIndex(*MI);
1411 SlotIndex NewIndex = Indexes->getInstructionIndex(*BundleStart);
Andrew Trickd9d4be02012-10-16 00:22:51 +00001412 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001413 HME.updateAllRanges(MI);
Lang Hamesb9057d52012-02-17 18:44:18 +00001414}
Cameron Zwarichbfebb412013-02-17 00:10:44 +00001415
Matthias Braune5f861b2014-12-10 01:12:26 +00001416void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
1417 const MachineBasicBlock::iterator End,
1418 const SlotIndex endIdx,
1419 LiveRange &LR, const unsigned Reg,
Matthias Braune6a24852015-09-25 21:51:14 +00001420 LaneBitmask LaneMask) {
Matthias Braune5f861b2014-12-10 01:12:26 +00001421 LiveInterval::iterator LII = LR.find(endIdx);
1422 SlotIndex lastUseIdx;
1423 if (LII != LR.end() && LII->start < endIdx)
1424 lastUseIdx = LII->end;
1425 else
1426 --LII;
1427
1428 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1429 --I;
1430 MachineInstr *MI = I;
1431 if (MI->isDebugValue())
1432 continue;
1433
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001434 SlotIndex instrIdx = getInstructionIndex(*MI);
Matthias Braune5f861b2014-12-10 01:12:26 +00001435 bool isStartValid = getInstructionFromIndex(LII->start);
1436 bool isEndValid = getInstructionFromIndex(LII->end);
1437
1438 // FIXME: This doesn't currently handle early-clobber or multiple removed
1439 // defs inside of the region to repair.
1440 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
1441 OE = MI->operands_end(); OI != OE; ++OI) {
1442 const MachineOperand &MO = *OI;
1443 if (!MO.isReg() || MO.getReg() != Reg)
1444 continue;
1445
1446 unsigned SubReg = MO.getSubReg();
Matthias Braune6a24852015-09-25 21:51:14 +00001447 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
Matthias Braune5f861b2014-12-10 01:12:26 +00001448 if ((Mask & LaneMask) == 0)
1449 continue;
1450
1451 if (MO.isDef()) {
1452 if (!isStartValid) {
1453 if (LII->end.isDead()) {
1454 SlotIndex prevStart;
1455 if (LII != LR.begin())
1456 prevStart = std::prev(LII)->start;
1457
1458 // FIXME: This could be more efficient if there was a
1459 // removeSegment method that returned an iterator.
1460 LR.removeSegment(*LII, true);
1461 if (prevStart.isValid())
1462 LII = LR.find(prevStart);
1463 else
1464 LII = LR.begin();
1465 } else {
1466 LII->start = instrIdx.getRegSlot();
1467 LII->valno->def = instrIdx.getRegSlot();
1468 if (MO.getSubReg() && !MO.isUndef())
1469 lastUseIdx = instrIdx.getRegSlot();
1470 else
1471 lastUseIdx = SlotIndex();
1472 continue;
1473 }
1474 }
1475
1476 if (!lastUseIdx.isValid()) {
1477 VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1478 LiveRange::Segment S(instrIdx.getRegSlot(),
1479 instrIdx.getDeadSlot(), VNI);
1480 LII = LR.addSegment(S);
1481 } else if (LII->start != instrIdx.getRegSlot()) {
1482 VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1483 LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
1484 LII = LR.addSegment(S);
1485 }
1486
1487 if (MO.getSubReg() && !MO.isUndef())
1488 lastUseIdx = instrIdx.getRegSlot();
1489 else
1490 lastUseIdx = SlotIndex();
1491 } else if (MO.isUse()) {
1492 // FIXME: This should probably be handled outside of this branch,
1493 // either as part of the def case (for defs inside of the region) or
1494 // after the loop over the region.
1495 if (!isEndValid && !LII->end.isBlock())
1496 LII->end = instrIdx.getRegSlot();
1497 if (!lastUseIdx.isValid())
1498 lastUseIdx = instrIdx.getRegSlot();
1499 }
1500 }
1501 }
1502}
1503
Cameron Zwarichbfebb412013-02-17 00:10:44 +00001504void
1505LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
Cameron Zwarich24955962013-02-17 11:09:00 +00001506 MachineBasicBlock::iterator Begin,
1507 MachineBasicBlock::iterator End,
Cameron Zwarich1286ef92013-02-17 03:48:23 +00001508 ArrayRef<unsigned> OrigRegs) {
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001509 // Find anchor points, which are at the beginning/end of blocks or at
1510 // instructions that already have indexes.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001511 while (Begin != MBB->begin() && !Indexes->hasIndex(*Begin))
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001512 --Begin;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001513 while (End != MBB->end() && !Indexes->hasIndex(*End))
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001514 ++End;
1515
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001516 SlotIndex endIdx;
1517 if (End == MBB->end())
1518 endIdx = getMBBEndIdx(MBB).getPrevSlot();
Cameron Zwarich24955962013-02-17 11:09:00 +00001519 else
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001520 endIdx = getInstructionIndex(*End);
Cameron Zwarich24955962013-02-17 11:09:00 +00001521
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001522 Indexes->repairIndexesInRange(MBB, *Begin, *End);
Cameron Zwarich29414822013-02-20 06:46:41 +00001523
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001524 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1525 --I;
1526 MachineInstr *MI = I;
Cameron Zwarich63acc732013-02-23 10:25:25 +00001527 if (MI->isDebugValue())
1528 continue;
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001529 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1530 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1531 if (MOI->isReg() &&
1532 TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
1533 !hasInterval(MOI->getReg())) {
Mark Lacey9d8103d2013-08-14 23:50:16 +00001534 createAndComputeVirtRegInterval(MOI->getReg());
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001535 }
1536 }
1537 }
1538
Cameron Zwarichbfebb412013-02-17 00:10:44 +00001539 for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
1540 unsigned Reg = OrigRegs[i];
1541 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1542 continue;
1543
1544 LiveInterval &LI = getInterval(Reg);
Cameron Zwarich8e7dc062013-02-20 22:09:57 +00001545 // FIXME: Should we support undefs that gain defs?
1546 if (!LI.hasAtLeastOneValue())
1547 continue;
1548
Matthias Braun09afa1e2014-12-11 00:59:06 +00001549 for (LiveInterval::SubRange &S : LI.subranges()) {
1550 repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask);
Cameron Zwarichbfebb412013-02-17 00:10:44 +00001551 }
Matthias Braune5f861b2014-12-10 01:12:26 +00001552 repairOldRegInRange(Begin, End, endIdx, LI, Reg);
Cameron Zwarichbfebb412013-02-17 00:10:44 +00001553 }
1554}
Matthias Brauncfb8ad22015-01-21 18:50:21 +00001555
1556void LiveIntervals::removePhysRegDefAt(unsigned Reg, SlotIndex Pos) {
1557 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1558 if (LiveRange *LR = getCachedRegUnit(*Units))
1559 if (VNInfo *VNI = LR->getVNInfoAt(Pos))
1560 LR->removeValNo(VNI);
1561 }
1562}
Matthias Braun311730a2015-01-21 19:02:30 +00001563
1564void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
1565 VNInfo *VNI = LI.getVNInfoAt(Pos);
1566 if (VNI == nullptr)
1567 return;
1568 LI.removeValNo(VNI);
1569
1570 // Also remove the value in subranges.
1571 for (LiveInterval::SubRange &S : LI.subranges()) {
1572 if (VNInfo *SVNI = S.getVNInfoAt(Pos))
1573 S.removeValNo(SVNI);
1574 }
1575 LI.removeEmptySubRanges();
1576}
Matthias Braund3dd1352015-09-22 03:44:41 +00001577
1578void LiveIntervals::splitSeparateComponents(LiveInterval &LI,
1579 SmallVectorImpl<LiveInterval*> &SplitLIs) {
1580 ConnectedVNInfoEqClasses ConEQ(*this);
Matthias Braunbf47f632016-01-08 01:16:35 +00001581 unsigned NumComp = ConEQ.Classify(LI);
Matthias Braund3dd1352015-09-22 03:44:41 +00001582 if (NumComp <= 1)
1583 return;
1584 DEBUG(dbgs() << " Split " << NumComp << " components: " << LI << '\n');
1585 unsigned Reg = LI.reg;
1586 const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
1587 for (unsigned I = 1; I < NumComp; ++I) {
1588 unsigned NewVReg = MRI->createVirtualRegister(RegClass);
1589 LiveInterval &NewLI = createEmptyInterval(NewVReg);
1590 SplitLIs.push_back(&NewLI);
1591 }
1592 ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
1593}
Matthias Braun3907fde2016-01-20 00:23:21 +00001594
1595void LiveIntervals::renameDisconnectedComponents() {
1596 ConnectedSubRegClasses SubRegClasses(*this, *MRI);
1597
1598 // Iterate over all vregs. Note that we query getNumVirtRegs() the newly
1599 // created vregs end up with higher numbers but do not need to be visited as
1600 // there can't be any further splitting.
1601 for (size_t I = 0, E = MRI->getNumVirtRegs(); I < E; ++I) {
1602 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
1603 LiveInterval *LI = VirtRegIntervals[Reg];
1604 if (LI == nullptr || !LI->hasSubRanges())
1605 continue;
1606
1607 SubRegClasses.renameComponents(*LI);
1608 }
1609}