blob: ed7bef667e77e82a69910d6202f66decfbc40917 [file] [log] [blame]
Eugene Zelenko16ffaf82017-09-13 21:15:20 +00001//===- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map -----------------===//
Alkis Evlogimenos34d9bc92004-02-23 23:08:11 +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 Evlogimenos34d9bc92004-02-23 23:08:11 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner8c4d88d2004-09-30 01:54:45 +000010// This file implements the VirtRegMap class.
11//
Dan Gohmanf451cb82010-02-10 16:03:48 +000012// It also contains implementations of the Spiller interface, which, given a
Chris Lattner8c4d88d2004-09-30 01:54:45 +000013// virtual register map and a machine function, eliminates all virtual
14// references by replacing them with physical register references - adding spill
Alkis Evlogimenos0d6c5b62004-02-24 08:58:30 +000015// code as necessary.
Alkis Evlogimenos34d9bc92004-02-23 23:08:11 +000016//
17//===----------------------------------------------------------------------===//
18
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000019#include "llvm/CodeGen/VirtRegMap.h"
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +000020#include "LiveDebugVariables.h"
Eugene Zelenko16ffaf82017-09-13 21:15:20 +000021#include "llvm/ADT/SmallVector.h"
Chandler Carruth1decd562014-03-04 10:07:28 +000022#include "llvm/ADT/Statistic.h"
Eugene Zelenko16ffaf82017-09-13 21:15:20 +000023#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunfa621d22017-12-13 02:51:04 +000024#include "llvm/CodeGen/LiveIntervals.h"
Matthias Braun209f0482017-12-18 23:19:44 +000025#include "llvm/CodeGen/LiveStacks.h"
Eugene Zelenko16ffaf82017-09-13 21:15:20 +000026#include "llvm/CodeGen/MachineBasicBlock.h"
Alkis Evlogimenos34d9bc92004-02-23 23:08:11 +000027#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner8c4d88d2004-09-30 01:54:45 +000028#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko16ffaf82017-09-13 21:15:20 +000029#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
31#include "llvm/CodeGen/MachineOperand.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko16ffaf82017-09-13 21:15:20 +000033#include "llvm/CodeGen/SlotIndexes.h"
David Blaikie48319232017-11-08 01:01:31 +000034#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000035#include "llvm/CodeGen/TargetOpcodes.h"
36#include "llvm/CodeGen/TargetRegisterInfo.h"
37#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber0f38c602018-04-30 14:59:11 +000038#include "llvm/Config/llvm-config.h"
Eugene Zelenko16ffaf82017-09-13 21:15:20 +000039#include "llvm/MC/LaneBitmask.h"
40#include "llvm/Pass.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000041#include "llvm/Support/Compiler.h"
Evan Cheng752272a2009-02-11 08:24:21 +000042#include "llvm/Support/Debug.h"
Daniel Dunbar1cd1d982009-07-24 10:36:58 +000043#include "llvm/Support/raw_ostream.h"
Eugene Zelenko16ffaf82017-09-13 21:15:20 +000044#include <cassert>
45#include <iterator>
46#include <utility>
47
Alkis Evlogimenos34d9bc92004-02-23 23:08:11 +000048using namespace llvm;
49
Chandler Carruth8677f2f2014-04-22 02:02:50 +000050#define DEBUG_TYPE "regalloc"
51
Jakob Stoklund Olesen01afdb32011-09-15 18:31:13 +000052STATISTIC(NumSpillSlots, "Number of spill slots allocated");
53STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting");
Dan Gohman844731a2008-05-13 00:00:25 +000054
Chris Lattner8c4d88d2004-09-30 01:54:45 +000055//===----------------------------------------------------------------------===//
56// VirtRegMap implementation
57//===----------------------------------------------------------------------===//
58
Owen Anderson49c8aa02009-03-13 05:55:11 +000059char VirtRegMap::ID = 0;
60
Owen Andersonce665bd2010-10-07 22:25:06 +000061INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
Owen Anderson49c8aa02009-03-13 05:55:11 +000062
63bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
Evan Cheng90f95f82009-06-14 20:22:55 +000064 MRI = &mf.getRegInfo();
Eric Christopher60355182014-08-05 02:39:49 +000065 TII = mf.getSubtarget().getInstrInfo();
66 TRI = mf.getSubtarget().getRegisterInfo();
Owen Anderson49c8aa02009-03-13 05:55:11 +000067 MF = &mf;
Lang Hames233a60e2009-11-03 23:52:08 +000068
Owen Anderson49c8aa02009-03-13 05:55:11 +000069 Virt2PhysMap.clear();
70 Virt2StackSlotMap.clear();
Owen Anderson49c8aa02009-03-13 05:55:11 +000071 Virt2SplitMap.clear();
Mike Stumpfe095f32009-05-04 18:40:41 +000072
Chris Lattner29268692006-09-05 02:12:02 +000073 grow();
Owen Anderson49c8aa02009-03-13 05:55:11 +000074 return false;
Chris Lattner29268692006-09-05 02:12:02 +000075}
76
Chris Lattner8c4d88d2004-09-30 01:54:45 +000077void VirtRegMap::grow() {
Jakob Stoklund Olesen42e9c962011-01-09 21:58:20 +000078 unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
79 Virt2PhysMap.resize(NumRegs);
80 Virt2StackSlotMap.resize(NumRegs);
Jakob Stoklund Olesen42e9c962011-01-09 21:58:20 +000081 Virt2SplitMap.resize(NumRegs);
Alkis Evlogimenos34d9bc92004-02-23 23:08:11 +000082}
83
Matthias Braun9b4cf762017-06-08 21:30:54 +000084void VirtRegMap::assignVirt2Phys(unsigned virtReg, MCPhysReg physReg) {
85 assert(TargetRegisterInfo::isVirtualRegister(virtReg) &&
86 TargetRegisterInfo::isPhysicalRegister(physReg));
87 assert(Virt2PhysMap[virtReg] == NO_PHYS_REG &&
88 "attempt to assign physical register to already mapped "
89 "virtual register");
90 assert(!getRegInfo().isReserved(physReg) &&
91 "Attempt to map virtReg to a reserved physReg");
92 Virt2PhysMap[virtReg] = physReg;
93}
94
Jakob Stoklund Olesenb55e91e2010-11-16 00:41:01 +000095unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
Krzysztof Parzyszek36d7c2b2017-04-24 18:55:33 +000096 unsigned Size = TRI->getSpillSize(*RC);
97 unsigned Align = TRI->getSpillAlignment(*RC);
98 int SS = MF->getFrameInfo().CreateSpillStackObject(Size, Align);
Jakob Stoklund Olesen01afdb32011-09-15 18:31:13 +000099 ++NumSpillSlots;
Jakob Stoklund Olesenb55e91e2010-11-16 00:41:01 +0000100 return SS;
101}
102
Jakob Stoklund Olesen980bddf2012-12-04 00:30:22 +0000103bool VirtRegMap::hasPreferredPhys(unsigned VirtReg) {
104 unsigned Hint = MRI->getSimpleHint(VirtReg);
105 if (!Hint)
Matt Arsenault5fff0fe2016-06-02 18:37:21 +0000106 return false;
Jakob Stoklund Olesen980bddf2012-12-04 00:30:22 +0000107 if (TargetRegisterInfo::isVirtualRegister(Hint))
108 Hint = getPhys(Hint);
109 return getPhys(VirtReg) == Hint;
110}
111
Jakob Stoklund Olesenfc637442012-12-03 23:23:50 +0000112bool VirtRegMap::hasKnownPreference(unsigned VirtReg) {
113 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
114 if (TargetRegisterInfo::isPhysicalRegister(Hint.second))
115 return true;
116 if (TargetRegisterInfo::isVirtualRegister(Hint.second))
117 return hasPhys(Hint.second);
118 return false;
119}
120
Chris Lattner8c4d88d2004-09-30 01:54:45 +0000121int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000122 assert(TargetRegisterInfo::isVirtualRegister(virtReg));
Chris Lattner7f690e62004-09-30 02:15:18 +0000123 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
Chris Lattner8c4d88d2004-09-30 01:54:45 +0000124 "attempt to assign stack slot to already spilled register");
Owen Anderson49c8aa02009-03-13 05:55:11 +0000125 const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
Jakob Stoklund Olesenb55e91e2010-11-16 00:41:01 +0000126 return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
Chris Lattner8c4d88d2004-09-30 01:54:45 +0000127}
128
Evan Chengd3653122008-02-27 03:04:06 +0000129void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000130 assert(TargetRegisterInfo::isVirtualRegister(virtReg));
Chris Lattner7f690e62004-09-30 02:15:18 +0000131 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
Chris Lattner8c4d88d2004-09-30 01:54:45 +0000132 "attempt to assign stack slot to already spilled register");
Evan Chengd3653122008-02-27 03:04:06 +0000133 assert((SS >= 0 ||
Matthias Braunf79c57a2016-07-28 18:40:00 +0000134 (SS >= MF->getFrameInfo().getObjectIndexBegin())) &&
Evan Cheng91935142007-04-04 07:40:01 +0000135 "illegal fixed frame index");
Evan Chengd3653122008-02-27 03:04:06 +0000136 Virt2StackSlotMap[virtReg] = SS;
Alkis Evlogimenos38af59a2004-05-29 20:38:05 +0000137}
138
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000139void VirtRegMap::print(raw_ostream &OS, const Module*) const {
140 OS << "********** REGISTER MAP **********\n";
141 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
142 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
143 if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
Francis Visoiu Mistrihaccb3372017-11-28 12:42:37 +0000144 OS << '[' << printReg(Reg, TRI) << " -> "
145 << printReg(Virt2PhysMap[Reg], TRI) << "] "
Craig Toppera5babc82014-11-17 05:50:14 +0000146 << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000147 }
148 }
149
150 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
151 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
152 if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
Francis Visoiu Mistrihaccb3372017-11-28 12:42:37 +0000153 OS << '[' << printReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
Craig Toppera5babc82014-11-17 05:50:14 +0000154 << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000155 }
156 }
157 OS << '\n';
158}
159
Aaron Ballman1d03d382017-10-15 14:32:27 +0000160#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Keren55307982016-01-29 20:50:44 +0000161LLVM_DUMP_METHOD void VirtRegMap::dump() const {
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000162 print(dbgs());
163}
Manman Ren77e300e2012-09-06 19:06:06 +0000164#endif
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000165
166//===----------------------------------------------------------------------===//
167// VirtRegRewriter
168//===----------------------------------------------------------------------===//
169//
170// The VirtRegRewriter is the last of the register allocator passes.
171// It rewrites virtual registers to physical registers as specified in the
172// VirtRegMap analysis. It also updates live-in information on basic blocks
173// according to LiveIntervals.
174//
175namespace {
Eugene Zelenko16ffaf82017-09-13 21:15:20 +0000176
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000177class VirtRegRewriter : public MachineFunctionPass {
178 MachineFunction *MF;
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000179 const TargetRegisterInfo *TRI;
180 const TargetInstrInfo *TII;
181 MachineRegisterInfo *MRI;
182 SlotIndexes *Indexes;
183 LiveIntervals *LIS;
184 VirtRegMap *VRM;
185
186 void rewrite();
187 void addMBBLiveIns();
Matthias Braun944aaeb2015-06-16 18:22:28 +0000188 bool readsUndefSubreg(const MachineOperand &MO) const;
Matthias Braun6111cd82015-09-09 18:07:54 +0000189 void addLiveInsForSubRanges(const LiveInterval &LI, unsigned PhysReg) const;
Matthias Braun79519fe2016-07-09 00:19:07 +0000190 void handleIdentityCopy(MachineInstr &MI) const;
Matthias Braun94ebfcb2017-03-17 00:41:39 +0000191 void expandCopyBundle(MachineInstr &MI) const;
Quentin Colombet156a1032017-08-16 00:17:05 +0000192 bool subRegLiveThrough(const MachineInstr &MI, unsigned SuperPhysReg) const;
Matthias Braun6111cd82015-09-09 18:07:54 +0000193
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000194public:
195 static char ID;
Eugene Zelenko16ffaf82017-09-13 21:15:20 +0000196
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000197 VirtRegRewriter() : MachineFunctionPass(ID) {}
198
Craig Topper9f998de2014-03-07 09:26:03 +0000199 void getAnalysisUsage(AnalysisUsage &AU) const override;
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000200
Craig Topper9f998de2014-03-07 09:26:03 +0000201 bool runOnMachineFunction(MachineFunction&) override;
Eugene Zelenko16ffaf82017-09-13 21:15:20 +0000202
Derek Schuffb65f5502016-03-29 17:40:22 +0000203 MachineFunctionProperties getSetProperties() const override {
204 return MachineFunctionProperties().set(
Matthias Braun690a3cb2016-08-25 01:27:13 +0000205 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffb65f5502016-03-29 17:40:22 +0000206 }
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000207};
Eugene Zelenko16ffaf82017-09-13 21:15:20 +0000208
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000209} // end anonymous namespace
210
Eugene Zelenko16ffaf82017-09-13 21:15:20 +0000211char VirtRegRewriter::ID = 0;
212
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000213char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
214
215INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
216 "Virtual Register Rewriter", false, false)
217INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
218INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
219INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
Evan Chengbb36a432012-09-21 20:04:28 +0000220INITIALIZE_PASS_DEPENDENCY(LiveStacks)
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000221INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
222INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
223 "Virtual Register Rewriter", false, false)
224
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000225void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
226 AU.setPreservesCFG();
227 AU.addRequired<LiveIntervals>();
228 AU.addRequired<SlotIndexes>();
229 AU.addPreserved<SlotIndexes>();
230 AU.addRequired<LiveDebugVariables>();
Evan Chengbb36a432012-09-21 20:04:28 +0000231 AU.addRequired<LiveStacks>();
232 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000233 AU.addRequired<VirtRegMap>();
234 MachineFunctionPass::getAnalysisUsage(AU);
235}
236
237bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
238 MF = &fn;
Eric Christopher5db6cf42014-10-13 21:57:44 +0000239 TRI = MF->getSubtarget().getRegisterInfo();
240 TII = MF->getSubtarget().getInstrInfo();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000241 MRI = &MF->getRegInfo();
242 Indexes = &getAnalysis<SlotIndexes>();
243 LIS = &getAnalysis<LiveIntervals>();
244 VRM = &getAnalysis<VirtRegMap>();
Nicola Zaghen0818e782018-05-14 12:53:11 +0000245 LLVM_DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
246 << "********** Function: " << MF->getName() << '\n');
247 LLVM_DEBUG(VRM->dump());
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000248
249 // Add kill flags while we still have virtual registers.
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000250 LIS->addKillFlags(VRM);
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000251
Jakob Stoklund Olesenfe17bdb2012-06-09 00:14:47 +0000252 // Live-in lists on basic blocks are required for physregs.
253 addMBBLiveIns();
254
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000255 // Rewrite virtual registers.
256 rewrite();
257
258 // Write out new DBG_VALUE instructions.
259 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
260
261 // All machine operands and other references to virtual registers have been
262 // replaced. Remove the virtual registers and release all the transient data.
263 VRM->clearAllVirt();
264 MRI->clearVirtRegs();
265 return true;
266}
267
Matthias Braun6111cd82015-09-09 18:07:54 +0000268void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
269 unsigned PhysReg) const {
270 assert(!LI.empty());
271 assert(LI.hasSubRanges());
272
Eugene Zelenko16ffaf82017-09-13 21:15:20 +0000273 using SubRangeIteratorPair =
274 std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
275
Matthias Braun6111cd82015-09-09 18:07:54 +0000276 SmallVector<SubRangeIteratorPair, 4> SubRanges;
277 SlotIndex First;
278 SlotIndex Last;
279 for (const LiveInterval::SubRange &SR : LI.subranges()) {
280 SubRanges.push_back(std::make_pair(&SR, SR.begin()));
281 if (!First.isValid() || SR.segments.front().start < First)
282 First = SR.segments.front().start;
283 if (!Last.isValid() || SR.segments.back().end > Last)
284 Last = SR.segments.back().end;
285 }
286
287 // Check all mbb start positions between First and Last while
288 // simulatenously advancing an iterator for each subrange.
289 for (SlotIndexes::MBBIndexIterator MBBI = Indexes->findMBBIndex(First);
290 MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
291 SlotIndex MBBBegin = MBBI->first;
292 // Advance all subrange iterators so that their end position is just
293 // behind MBBBegin (or the iterator is at the end).
Krzysztof Parzyszekd6ca3f02016-12-15 14:36:06 +0000294 LaneBitmask LaneMask;
Matthias Braun6111cd82015-09-09 18:07:54 +0000295 for (auto &RangeIterPair : SubRanges) {
296 const LiveInterval::SubRange *SR = RangeIterPair.first;
297 LiveInterval::const_iterator &SRI = RangeIterPair.second;
298 while (SRI != SR->end() && SRI->end <= MBBBegin)
299 ++SRI;
300 if (SRI == SR->end())
301 continue;
302 if (SRI->start <= MBBBegin)
303 LaneMask |= SR->LaneMask;
304 }
Krzysztof Parzyszekd6ca3f02016-12-15 14:36:06 +0000305 if (LaneMask.none())
Matthias Braun6111cd82015-09-09 18:07:54 +0000306 continue;
307 MachineBasicBlock *MBB = MBBI->second;
Matthias Braunaf5ff602015-09-09 18:08:03 +0000308 MBB->addLiveIn(PhysReg, LaneMask);
Matthias Braun6111cd82015-09-09 18:07:54 +0000309 }
310}
311
Jakob Stoklund Olesenfe17bdb2012-06-09 00:14:47 +0000312// Compute MBB live-in lists from virtual register live ranges and their
313// assignments.
314void VirtRegRewriter::addMBBLiveIns() {
Jakob Stoklund Olesenfe17bdb2012-06-09 00:14:47 +0000315 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
316 unsigned VirtReg = TargetRegisterInfo::index2VirtReg(Idx);
317 if (MRI->reg_nodbg_empty(VirtReg))
318 continue;
319 LiveInterval &LI = LIS->getInterval(VirtReg);
320 if (LI.empty() || LIS->intervalIsInOneMBB(LI))
321 continue;
322 // This is a virtual register that is live across basic blocks. Its
323 // assigned PhysReg must be marked as live-in to those blocks.
324 unsigned PhysReg = VRM->getPhys(VirtReg);
325 assert(PhysReg != VirtRegMap::NO_PHYS_REG && "Unmapped virtual register.");
326
Matthias Braun8f080022014-12-10 01:13:08 +0000327 if (LI.hasSubRanges()) {
Matthias Braun6111cd82015-09-09 18:07:54 +0000328 addLiveInsForSubRanges(LI, PhysReg);
Matthias Braun8f080022014-12-10 01:13:08 +0000329 } else {
Matthias Braun6111cd82015-09-09 18:07:54 +0000330 // Go over MBB begin positions and see if we have segments covering them.
331 // The following works because segments and the MBBIndex list are both
332 // sorted by slot indexes.
333 SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin();
334 for (const auto &Seg : LI) {
335 I = Indexes->advanceMBBIndex(I, Seg.start);
336 for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) {
337 MachineBasicBlock *MBB = I->second;
338 MBB->addLiveIn(PhysReg);
339 }
Matthias Braun8f080022014-12-10 01:13:08 +0000340 }
Jakob Stoklund Olesenfe17bdb2012-06-09 00:14:47 +0000341 }
342 }
Puyan Lotfid9a08b02015-05-22 08:11:26 +0000343
344 // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
345 // each MBB's LiveIns set before calling addLiveIn on them.
346 for (MachineBasicBlock &MBB : *MF)
347 MBB.sortUniqueLiveIns();
Jakob Stoklund Olesenfe17bdb2012-06-09 00:14:47 +0000348}
349
Matthias Braun944aaeb2015-06-16 18:22:28 +0000350/// Returns true if the given machine operand \p MO only reads undefined lanes.
351/// The function only works for use operands with a subregister set.
352bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
353 // Shortcut if the operand is already marked undef.
354 if (MO.isUndef())
355 return true;
356
357 unsigned Reg = MO.getReg();
358 const LiveInterval &LI = LIS->getInterval(Reg);
359 const MachineInstr &MI = *MO.getParent();
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +0000360 SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
Matthias Braun944aaeb2015-06-16 18:22:28 +0000361 // This code is only meant to handle reading undefined subregisters which
362 // we couldn't properly detect before.
363 assert(LI.liveAt(BaseIndex) &&
364 "Reads of completely dead register should be marked undef already");
365 unsigned SubRegIdx = MO.getSubReg();
Krzysztof Parzyszek31a5f882016-08-24 13:37:55 +0000366 assert(SubRegIdx != 0 && LI.hasSubRanges());
Matthias Braundfc5b652015-09-25 21:51:14 +0000367 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
Matthias Braun944aaeb2015-06-16 18:22:28 +0000368 // See if any of the relevant subregister liveranges is defined at this point.
369 for (const LiveInterval::SubRange &SR : LI.subranges()) {
Krzysztof Parzyszek308c60d2016-12-16 19:11:56 +0000370 if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex))
Matthias Braun944aaeb2015-06-16 18:22:28 +0000371 return false;
372 }
373 return true;
374}
375
Matthias Braun79519fe2016-07-09 00:19:07 +0000376void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) const {
377 if (!MI.isIdentityCopy())
378 return;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000379 LLVM_DEBUG(dbgs() << "Identity copy: " << MI);
Matthias Braun79519fe2016-07-09 00:19:07 +0000380 ++NumIdCopies;
381
382 // Copies like:
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000383 // %r0 = COPY undef %r0
384 // %al = COPY %al, implicit-def %eax
Matthias Braun79519fe2016-07-09 00:19:07 +0000385 // give us additional liveness information: The target (super-)register
386 // must not be valid before this point. Replace the COPY with a KILL
387 // instruction to maintain this information.
388 if (MI.getOperand(0).isUndef() || MI.getNumOperands() > 2) {
389 MI.setDesc(TII->get(TargetOpcode::KILL));
Nicola Zaghen0818e782018-05-14 12:53:11 +0000390 LLVM_DEBUG(dbgs() << " replace by: " << MI);
Matthias Braun79519fe2016-07-09 00:19:07 +0000391 return;
392 }
393
394 if (Indexes)
Matthias Braun852989f2017-03-17 00:41:33 +0000395 Indexes->removeSingleMachineInstrFromMaps(MI);
396 MI.eraseFromBundle();
Nicola Zaghen0818e782018-05-14 12:53:11 +0000397 LLVM_DEBUG(dbgs() << " deleted.\n");
Matthias Braun79519fe2016-07-09 00:19:07 +0000398}
399
Matthias Braun94ebfcb2017-03-17 00:41:39 +0000400/// The liverange splitting logic sometimes produces bundles of copies when
401/// subregisters are involved. Expand these into a sequence of copy instructions
402/// after processing the last in the bundle. Does not update LiveIntervals
403/// which we shouldn't need for this instruction anymore.
404void VirtRegRewriter::expandCopyBundle(MachineInstr &MI) const {
405 if (!MI.isCopy())
406 return;
407
408 if (MI.isBundledWithPred() && !MI.isBundledWithSucc()) {
Justin Bogner3d294042018-06-14 19:24:03 +0000409 SmallVector<MachineInstr *, 2> MIs({&MI});
410
Matthias Braun94ebfcb2017-03-17 00:41:39 +0000411 // Only do this when the complete bundle is made out of COPYs.
Matthias Braun9c890fc2017-03-21 21:58:08 +0000412 MachineBasicBlock &MBB = *MI.getParent();
Matthias Braun94ebfcb2017-03-17 00:41:39 +0000413 for (MachineBasicBlock::reverse_instr_iterator I =
Matthias Braun9c890fc2017-03-21 21:58:08 +0000414 std::next(MI.getReverseIterator()), E = MBB.instr_rend();
415 I != E && I->isBundledWithSucc(); ++I) {
Matthias Braun94ebfcb2017-03-17 00:41:39 +0000416 if (!I->isCopy())
417 return;
Justin Bogner3d294042018-06-14 19:24:03 +0000418 MIs.push_back(&*I);
419 }
420 MachineInstr *FirstMI = MIs.back();
421
422 auto anyRegsAlias = [](const MachineInstr *Dst,
423 ArrayRef<MachineInstr *> Srcs,
424 const TargetRegisterInfo *TRI) {
425 for (const MachineInstr *Src : Srcs)
426 if (Src != Dst)
427 if (TRI->regsOverlap(Dst->getOperand(0).getReg(),
428 Src->getOperand(1).getReg()))
429 return true;
430 return false;
431 };
432
433 // If any of the destination registers in the bundle of copies alias any of
434 // the source registers, try to schedule the instructions to avoid any
435 // clobbering.
436 for (int E = MIs.size(), PrevE = E; E > 1; PrevE = E) {
437 for (int I = E; I--; )
438 if (!anyRegsAlias(MIs[I], makeArrayRef(MIs).take_front(E), TRI)) {
439 if (I + 1 != E)
440 std::swap(MIs[I], MIs[E - 1]);
441 --E;
442 }
443 if (PrevE == E) {
444 MF->getFunction().getContext().emitError(
445 "register rewriting failed: cycle in copy bundle");
446 break;
447 }
Matthias Braun94ebfcb2017-03-17 00:41:39 +0000448 }
449
Justin Bogner3d294042018-06-14 19:24:03 +0000450 MachineInstr *BundleStart = FirstMI;
451 for (MachineInstr *BundledMI : llvm::reverse(MIs)) {
452 // If instruction is in the middle of the bundle, move it before the
453 // bundle starts, otherwise, just unbundle it. When we get to the last
454 // instruction, the bundle will have been completely undone.
455 if (BundledMI != BundleStart) {
456 BundledMI->removeFromBundle();
457 MBB.insert(FirstMI, BundledMI);
458 } else if (BundledMI->isBundledWithSucc()) {
459 BundledMI->unbundleFromSucc();
460 BundleStart = &*std::next(BundledMI->getIterator());
461 }
Matthias Braun94ebfcb2017-03-17 00:41:39 +0000462
Justin Bogner3d294042018-06-14 19:24:03 +0000463 if (Indexes && BundledMI != FirstMI)
464 Indexes->insertMachineInstrInMaps(*BundledMI);
Matthias Braun94ebfcb2017-03-17 00:41:39 +0000465 }
466 }
467}
468
Quentin Colombet156a1032017-08-16 00:17:05 +0000469/// Check whether (part of) \p SuperPhysReg is live through \p MI.
470/// \pre \p MI defines a subregister of a virtual register that
471/// has been assigned to \p SuperPhysReg.
472bool VirtRegRewriter::subRegLiveThrough(const MachineInstr &MI,
473 unsigned SuperPhysReg) const {
474 SlotIndex MIIndex = LIS->getInstructionIndex(MI);
475 SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
476 SlotIndex AfterMIDefs = MIIndex.getBoundaryIndex();
477 for (MCRegUnitIterator Unit(SuperPhysReg, TRI); Unit.isValid(); ++Unit) {
478 const LiveRange &UnitRange = LIS->getRegUnit(*Unit);
479 // If the regunit is live both before and after MI,
480 // we assume it is live through.
481 // Generally speaking, this is not true, because something like
482 // "RU = op RU" would match that description.
483 // However, we know that we are trying to assess whether
484 // a def of a virtual reg, vreg, is live at the same time of RU.
485 // If we are in the "RU = op RU" situation, that means that vreg
486 // is defined at the same time as RU (i.e., "vreg, RU = op RU").
487 // Thus, vreg and RU interferes and vreg cannot be assigned to
488 // SuperPhysReg. Therefore, this situation cannot happen.
489 if (UnitRange.liveAt(AfterMIDefs) && UnitRange.liveAt(BeforeMIUses))
490 return true;
491 }
492 return false;
493}
494
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000495void VirtRegRewriter::rewrite() {
Matthias Braun5101c892015-03-19 00:21:58 +0000496 bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
Jakob Stoklund Olesen93e110b2011-04-27 17:42:31 +0000497 SmallVector<unsigned, 8> SuperDeads;
498 SmallVector<unsigned, 8> SuperDefs;
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000499 SmallVector<unsigned, 8> SuperKills;
Logan Chien28713bd2014-02-25 16:57:28 +0000500
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000501 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
502 MBBI != MBBE; ++MBBI) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000503 LLVM_DEBUG(MBBI->print(dbgs(), Indexes));
Evan Cheng3f9c2512012-01-19 07:46:36 +0000504 for (MachineBasicBlock::instr_iterator
505 MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
Duncan P. N. Exon Smithac4d7b62015-10-09 22:56:24 +0000506 MachineInstr *MI = &*MII;
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000507 ++MII;
508
509 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
510 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
511 MachineOperand &MO = *MOI;
Jakob Stoklund Olesend9f0ff52012-02-17 19:07:56 +0000512
513 // Make sure MRI knows about registers clobbered by regmasks.
514 if (MO.isRegMask())
515 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
516
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000517 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
518 continue;
519 unsigned VirtReg = MO.getReg();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000520 unsigned PhysReg = VRM->getPhys(VirtReg);
521 assert(PhysReg != VirtRegMap::NO_PHYS_REG &&
522 "Instruction uses unmapped VirtReg");
Jakob Stoklund Olesenfb9ebbf2012-10-15 21:57:41 +0000523 assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000524
525 // Preserve semantics of sub-register operands.
Matthias Braun944aaeb2015-06-16 18:22:28 +0000526 unsigned SubReg = MO.getSubReg();
527 if (SubReg != 0) {
Krzysztof Parzyszekd7a02362018-08-15 16:07:47 +0000528 if (NoSubRegLiveness || !MRI->shouldTrackSubRegLiveness(VirtReg)) {
Matthias Braun944aaeb2015-06-16 18:22:28 +0000529 // A virtual register kill refers to the whole register, so we may
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000530 // have to add implicit killed operands for the super-register. A
Matthias Braun944aaeb2015-06-16 18:22:28 +0000531 // partial redef always kills and redefines the super-register.
Quentin Colombet156a1032017-08-16 00:17:05 +0000532 if ((MO.readsReg() && (MO.isDef() || MO.isKill())) ||
533 (MO.isDef() && subRegLiveThrough(*MI, PhysReg)))
Matthias Braun944aaeb2015-06-16 18:22:28 +0000534 SuperKills.push_back(PhysReg);
Jakob Stoklund Olesen200a8ce2011-10-05 00:01:48 +0000535
Matthias Braun944aaeb2015-06-16 18:22:28 +0000536 if (MO.isDef()) {
537 // Also add implicit defs for the super-register.
Matthias Braun66813242014-12-10 01:13:04 +0000538 if (MO.isDead())
539 SuperDeads.push_back(PhysReg);
540 else
541 SuperDefs.push_back(PhysReg);
542 }
Matthias Braun944aaeb2015-06-16 18:22:28 +0000543 } else {
544 if (MO.isUse()) {
545 if (readsUndefSubreg(MO))
546 // We need to add an <undef> flag if the subregister is
547 // completely undefined (and we are not adding super-register
548 // defs).
549 MO.setIsUndef(true);
550 } else if (!MO.isDead()) {
551 assert(MO.isDef());
Matthias Braun944aaeb2015-06-16 18:22:28 +0000552 }
Jakob Stoklund Olesen200a8ce2011-10-05 00:01:48 +0000553 }
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000554
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000555 // The def undef and def internal flags only make sense for
Matthias Braun852989f2017-03-17 00:41:33 +0000556 // sub-register defs, and we are substituting a full physreg. An
Francis Visoiu Mistrihfd11bc02017-12-07 10:40:31 +0000557 // implicit killed operand from the SuperKills list will represent the
Matthias Braun852989f2017-03-17 00:41:33 +0000558 // partial read of the super-register.
559 if (MO.isDef()) {
Matthias Braun944aaeb2015-06-16 18:22:28 +0000560 MO.setIsUndef(false);
Matthias Braun852989f2017-03-17 00:41:33 +0000561 MO.setIsInternalRead(false);
562 }
Matthias Braun944aaeb2015-06-16 18:22:28 +0000563
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000564 // PhysReg operands cannot have subregister indexes.
Matthias Braun944aaeb2015-06-16 18:22:28 +0000565 PhysReg = TRI->getSubReg(PhysReg, SubReg);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000566 assert(PhysReg && "Invalid SubReg for physical register");
567 MO.setSubReg(0);
568 }
569 // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
570 // we need the inlining here.
571 MO.setReg(PhysReg);
Geoff Berry13357c92018-02-23 18:25:08 +0000572 MO.setIsRenamable(true);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000573 }
574
575 // Add any missing super-register kills after rewriting the whole
576 // instruction.
577 while (!SuperKills.empty())
578 MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
579
Jakob Stoklund Olesen93e110b2011-04-27 17:42:31 +0000580 while (!SuperDeads.empty())
581 MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
582
583 while (!SuperDefs.empty())
584 MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
585
Nicola Zaghen0818e782018-05-14 12:53:11 +0000586 LLVM_DEBUG(dbgs() << "> " << *MI);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000587
Matthias Braun94ebfcb2017-03-17 00:41:39 +0000588 expandCopyBundle(*MI);
589
Matthias Braun79519fe2016-07-09 00:19:07 +0000590 // We can remove identity copies right now.
591 handleIdentityCopy(*MI);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000592 }
593 }
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +0000594}