blob: 0020221f4d6b7010a6fa1b800009d930ffa39a62 [file] [log] [blame]
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001//===- LiveRangeCalc.cpp - Calculate live ranges --------------------------===//
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Implementation of the LiveRangeCalc class.
10//
11//===----------------------------------------------------------------------===//
12
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +000013#include "LiveRangeCalc.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000014#include "llvm/ADT/BitVector.h"
15#include "llvm/ADT/STLExtras.h"
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +000016#include "llvm/ADT/SetVector.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/CodeGen/LiveInterval.h"
19#include "llvm/CodeGen/MachineBasicBlock.h"
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +000020#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000021#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstr.h"
23#include "llvm/CodeGen/MachineOperand.h"
Jakob Stoklund Olesen989b3b12012-06-05 21:54:09 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000025#include "llvm/CodeGen/SlotIndexes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000026#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000027#include "llvm/MC/LaneBitmask.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000030#include <algorithm>
31#include <cassert>
32#include <iterator>
33#include <tuple>
34#include <utility>
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +000035
36using namespace llvm;
37
Chandler Carruth1b9dde02014-04-22 02:02:50 +000038#define DEBUG_TYPE "regalloc"
39
Krzysztof Parzyszek0b7688e2017-06-27 21:30:46 +000040// Reserve an address that indicates a value that is known to be "undef".
41static VNInfo UndefVNI(0xbad, SlotIndex());
42
Matthias Braun1aed6ff2014-12-16 04:03:38 +000043void LiveRangeCalc::resetLiveOutMap() {
44 unsigned NumBlocks = MF->getNumBlockIDs();
45 Seen.clear();
46 Seen.resize(NumBlocks);
Matthias Brauna6e77402017-06-27 18:05:26 +000047 EntryInfos.clear();
Matthias Braun1aed6ff2014-12-16 04:03:38 +000048 Map.resize(NumBlocks);
49}
50
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +000051void LiveRangeCalc::reset(const MachineFunction *mf,
Jakob Stoklund Olesen5ef0e0b2012-06-04 18:21:16 +000052 SlotIndexes *SI,
53 MachineDominatorTree *MDT,
54 VNInfo::Allocator *VNIA) {
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +000055 MF = mf;
Jakob Stoklund Olesen5ef0e0b2012-06-04 18:21:16 +000056 MRI = &MF->getRegInfo();
57 Indexes = SI;
58 DomTree = MDT;
59 Alloc = VNIA;
Matthias Braun1aed6ff2014-12-16 04:03:38 +000060 resetLiveOutMap();
Matthias Braunc3a72c22014-12-15 21:36:35 +000061 LiveIn.clear();
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +000062}
63
Matthias Braun1aed6ff2014-12-16 04:03:38 +000064static void createDeadDef(SlotIndexes &Indexes, VNInfo::Allocator &Alloc,
65 LiveRange &LR, const MachineOperand &MO) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +000066 const MachineInstr &MI = *MO.getParent();
67 SlotIndex DefIdx =
68 Indexes.getInstructionIndex(MI).getRegSlot(MO.isEarlyClobber());
Matthias Braunc3a72c22014-12-15 21:36:35 +000069
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +000070 // Create the def in LR. This may find an existing def.
71 LR.createDeadDef(DefIdx, Alloc);
Matthias Braun2f662322014-12-10 01:12:12 +000072}
73
Matthias Brauna25e13a2015-03-19 00:21:58 +000074void LiveRangeCalc::calculate(LiveInterval &LI, bool TrackSubRegs) {
Matthias Braun2f662322014-12-10 01:12:12 +000075 assert(MRI && Indexes && "call reset() first");
76
Matthias Braun1aed6ff2014-12-16 04:03:38 +000077 // Step 1: Create minimal live segments for every definition of Reg.
Matthias Braun2f662322014-12-10 01:12:12 +000078 // Visit all def operands. If the same instruction has multiple defs of Reg,
Matthias Braun1aed6ff2014-12-16 04:03:38 +000079 // createDeadDef() will deduplicate.
Matthias Braun2f662322014-12-10 01:12:12 +000080 const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
81 unsigned Reg = LI.reg;
Matthias Braun1aed6ff2014-12-16 04:03:38 +000082 for (const MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
83 if (!MO.isDef() && !MO.readsReg())
84 continue;
85
Matthias Braun2f662322014-12-10 01:12:12 +000086 unsigned SubReg = MO.getSubReg();
Matthias Brauna25e13a2015-03-19 00:21:58 +000087 if (LI.hasSubRanges() || (SubReg != 0 && TrackSubRegs)) {
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +000088 LaneBitmask SubMask = SubReg != 0 ? TRI.getSubRegIndexLaneMask(SubReg)
Krzysztof Parzyszek0a955d62016-08-29 13:15:35 +000089 : MRI->getMaxLaneMaskForVReg(Reg);
Matthias Braun2f662322014-12-10 01:12:12 +000090 // If this is the first time we see a subregister def, initialize
91 // subranges by creating a copy of the main range.
92 if (!LI.hasSubRanges() && !LI.empty()) {
Matthias Braune6a24852015-09-25 21:51:14 +000093 LaneBitmask ClassMask = MRI->getMaxLaneMaskForVReg(Reg);
Matthias Braun2f662322014-12-10 01:12:12 +000094 LI.createSubRangeFrom(*Alloc, ClassMask, LI);
95 }
96
Matthias Brauna04d7ad2017-03-03 19:05:34 +000097 LI.refineSubRanges(*Alloc, SubMask,
98 [&MO, this](LiveInterval::SubRange &SR) {
Matthias Braun1aed6ff2014-12-16 04:03:38 +000099 if (MO.isDef())
Matthias Brauna04d7ad2017-03-03 19:05:34 +0000100 createDeadDef(*Indexes, *Alloc, SR, MO);
101 });
Matthias Braun2f662322014-12-10 01:12:12 +0000102 }
103
Matthias Braundbcca0d2014-12-24 02:11:51 +0000104 // Create the def in the main liverange. We do not have to do this if
105 // subranges are tracked as we recreate the main range later in this case.
106 if (MO.isDef() && !LI.hasSubRanges())
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000107 createDeadDef(*Indexes, *Alloc, LI, MO);
Matthias Braun2f662322014-12-10 01:12:12 +0000108 }
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000109
110 // We may have created empty live ranges for partially undefined uses, we
111 // can't keep them because we won't find defs in them later.
112 LI.removeEmptySubRanges();
113
114 // Step 2: Extend live segments to all uses, constructing SSA form as
115 // necessary.
Matthias Braundbcca0d2014-12-24 02:11:51 +0000116 if (LI.hasSubRanges()) {
117 for (LiveInterval::SubRange &S : LI.subranges()) {
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000118 LiveRangeCalc SubLRC;
119 SubLRC.reset(MF, Indexes, DomTree, Alloc);
120 SubLRC.extendToUses(S, Reg, S.LaneMask, &LI);
Matthias Braundbcca0d2014-12-24 02:11:51 +0000121 }
122 LI.clear();
Matthias Braun71f95642016-05-20 23:14:56 +0000123 constructMainRangeFromSubranges(LI);
Matthias Braundbcca0d2014-12-24 02:11:51 +0000124 } else {
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000125 resetLiveOutMap();
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000126 extendToUses(LI, Reg, LaneBitmask::getAll());
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000127 }
Matthias Braun2f662322014-12-10 01:12:12 +0000128}
129
Matthias Braun71f95642016-05-20 23:14:56 +0000130void LiveRangeCalc::constructMainRangeFromSubranges(LiveInterval &LI) {
131 // First create dead defs at all defs found in subranges.
132 LiveRange &MainRange = LI;
133 assert(MainRange.segments.empty() && MainRange.valnos.empty() &&
134 "Expect empty main liverange");
135
136 for (const LiveInterval::SubRange &SR : LI.subranges()) {
137 for (const VNInfo *VNI : SR.valnos) {
138 if (!VNI->isUnused() && !VNI->isPHIDef())
139 MainRange.createDeadDef(VNI->def, *Alloc);
140 }
141 }
Matthias Braun71f95642016-05-20 23:14:56 +0000142 resetLiveOutMap();
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000143 extendToUses(MainRange, LI.reg, LaneBitmask::getAll(), &LI);
Matthias Braun71f95642016-05-20 23:14:56 +0000144}
Matthias Braun2f662322014-12-10 01:12:12 +0000145
Matthias Braunc3a72c22014-12-15 21:36:35 +0000146void LiveRangeCalc::createDeadDefs(LiveRange &LR, unsigned Reg) {
Jakob Stoklund Olesen989b3b12012-06-05 21:54:09 +0000147 assert(MRI && Indexes && "call reset() first");
148
149 // Visit all def operands. If the same instruction has multiple defs of Reg,
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000150 // LR.createDeadDef() will deduplicate.
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000151 for (MachineOperand &MO : MRI->def_operands(Reg))
152 createDeadDef(*Indexes, *Alloc, LR, MO);
Jakob Stoklund Olesen989b3b12012-06-05 21:54:09 +0000153}
154
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000155void LiveRangeCalc::extendToUses(LiveRange &LR, unsigned Reg, LaneBitmask Mask,
156 LiveInterval *LI) {
157 SmallVector<SlotIndex, 4> Undefs;
158 if (LI != nullptr)
159 LI->computeSubRangeUndefs(Undefs, Mask, *MRI, *Indexes);
160
Jakob Stoklund Olesen989b3b12012-06-05 21:54:09 +0000161 // Visit all operands that read Reg. This may include partial defs.
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000162 bool IsSubRange = !Mask.all();
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000163 const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
Owen Andersonb36376e2014-03-17 19:36:09 +0000164 for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
Jakob Stoklund Olesen4aed4702012-09-06 18:15:15 +0000165 // Clear all kill flags. They will be reinserted after register allocation
Matthias Braunf8422972017-12-13 02:51:04 +0000166 // by LiveIntervals::addKillFlags().
Jakob Stoklund Olesen4aed4702012-09-06 18:15:15 +0000167 if (MO.isUse())
168 MO.setIsKill(false);
Krzysztof Parzyszek3bf4aec2016-09-02 19:48:55 +0000169 // MO::readsReg returns "true" for subregister defs. This is for keeping
170 // liveness of the entire register (i.e. for the main range of the live
171 // interval). For subranges, definitions of non-overlapping subregisters
172 // do not count as uses.
173 if (!MO.readsReg() || (IsSubRange && MO.isDef()))
Jakob Stoklund Olesen989b3b12012-06-05 21:54:09 +0000174 continue;
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000175
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000176 unsigned SubReg = MO.getSubReg();
177 if (SubReg != 0) {
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000178 LaneBitmask SLM = TRI.getSubRegIndexLaneMask(SubReg);
179 if (MO.isDef())
Krzysztof Parzyszek0a955d62016-08-29 13:15:35 +0000180 SLM = ~SLM;
181 // Ignore uses not reading the current (sub)range.
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000182 if ((SLM & Mask).none())
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000183 continue;
184 }
185
186 // Determine the actual place of the use.
187 const MachineInstr *MI = MO.getParent();
188 unsigned OpNo = (&MO - &MI->getOperand(0));
189 SlotIndex UseIdx;
190 if (MI->isPHI()) {
191 assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
192 // The actual place where a phi operand is used is the end of the pred
193 // MBB. PHI operands are paired: (Reg, PredMBB).
194 UseIdx = Indexes->getMBBEndIdx(MI->getOperand(OpNo+1).getMBB());
195 } else {
196 // Check for early-clobber redefs.
197 bool isEarlyClobber = false;
198 unsigned DefIdx;
199 if (MO.isDef())
200 isEarlyClobber = MO.isEarlyClobber();
201 else if (MI->isRegTiedToDefOperand(OpNo, &DefIdx)) {
202 // FIXME: This would be a lot easier if tied early-clobber uses also
203 // had an early-clobber flag.
204 isEarlyClobber = MI->getOperand(DefIdx).isEarlyClobber();
205 }
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000206 UseIdx = Indexes->getInstructionIndex(*MI).getRegSlot(isEarlyClobber);
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000207 }
208
Jakob Stoklund Olesen989b3b12012-06-05 21:54:09 +0000209 // MI is reading Reg. We may have visited MI before if it happens to be
210 // reading Reg multiple times. That is OK, extend() is idempotent.
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000211 extend(LR, UseIdx, Reg, Undefs);
Jakob Stoklund Olesen989b3b12012-06-05 21:54:09 +0000212 }
213}
214
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000215void LiveRangeCalc::updateFromLiveIns() {
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +0000216 LiveRangeUpdater Updater;
Matthias Braun42fab342014-12-15 19:40:46 +0000217 for (const LiveInBlock &I : LiveIn) {
218 if (!I.DomNode)
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000219 continue;
Matthias Braun42fab342014-12-15 19:40:46 +0000220 MachineBasicBlock *MBB = I.DomNode->getBlock();
221 assert(I.Value && "No live-in value found");
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000222 SlotIndex Start, End;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000223 std::tie(Start, End) = Indexes->getMBBRange(MBB);
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000224
Matthias Braun42fab342014-12-15 19:40:46 +0000225 if (I.Kill.isValid())
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +0000226 // Value is killed inside this block.
Matthias Braun42fab342014-12-15 19:40:46 +0000227 End = I.Kill;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000228 else {
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +0000229 // The value is live-through, update LiveOut as well.
230 // Defer the Domtree lookup until it is needed.
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000231 assert(Seen.test(MBB->getNumber()));
232 Map[MBB] = LiveOutPair(I.Value, nullptr);
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000233 }
Matthias Braun42fab342014-12-15 19:40:46 +0000234 Updater.setDest(&I.LR);
235 Updater.add(Start, End, I.Value);
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000236 }
237 LiveIn.clear();
238}
239
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000240void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Use, unsigned PhysReg,
241 ArrayRef<SlotIndex> Undefs) {
Matthias Braun11042c82015-02-18 01:50:52 +0000242 assert(Use.isValid() && "Invalid SlotIndex");
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000243 assert(Indexes && "Missing SlotIndexes");
244 assert(DomTree && "Missing dominator tree");
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000245
Matthias Braun11042c82015-02-18 01:50:52 +0000246 MachineBasicBlock *UseMBB = Indexes->getMBBFromIndex(Use.getPrevSlot());
247 assert(UseMBB && "No MBB at Use");
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000248
249 // Is there a def in the same MBB we can extend?
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000250 auto EP = LR.extendInBlock(Undefs, Indexes->getMBBStartIdx(UseMBB), Use);
251 if (EP.first != nullptr || EP.second)
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000252 return;
253
Matthias Braun11042c82015-02-18 01:50:52 +0000254 // Find the single reaching def, or determine if Use is jointly dominated by
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000255 // multiple values, and we may need to create even more phi-defs to preserve
256 // VNInfo SSA form. Perform a search for all predecessor blocks where we
257 // know the dominating VNInfo.
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000258 if (findReachingDefs(LR, *UseMBB, Use, PhysReg, Undefs))
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +0000259 return;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000260
261 // When there were multiple different values, we may need new PHIs.
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000262 calculateValues();
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000263}
264
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000265// This function is called by a client after using the low-level API to add
266// live-out and live-in blocks. The unique value optimization is not
267// available, SplitEditor::transferValues handles that case directly anyway.
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000268void LiveRangeCalc::calculateValues() {
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000269 assert(Indexes && "Missing SlotIndexes");
270 assert(DomTree && "Missing dominator tree");
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000271 updateSSA();
272 updateFromLiveIns();
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000273}
274
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000275bool LiveRangeCalc::isDefOnEntry(LiveRange &LR, ArrayRef<SlotIndex> Undefs,
276 MachineBasicBlock &MBB, BitVector &DefOnEntry,
277 BitVector &UndefOnEntry) {
278 unsigned BN = MBB.getNumber();
279 if (DefOnEntry[BN])
280 return true;
281 if (UndefOnEntry[BN])
282 return false;
283
Malcolm Parsons17d266b2017-01-13 17:12:16 +0000284 auto MarkDefined = [BN, &DefOnEntry](MachineBasicBlock &B) -> bool {
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000285 for (MachineBasicBlock *S : B.successors())
286 DefOnEntry[S->getNumber()] = true;
287 DefOnEntry[BN] = true;
288 return true;
289 };
290
291 SetVector<unsigned> WorkList;
292 // Checking if the entry of MBB is reached by some def: add all predecessors
293 // that are potentially defined-on-exit to the work list.
294 for (MachineBasicBlock *P : MBB.predecessors())
295 WorkList.insert(P->getNumber());
296
297 for (unsigned i = 0; i != WorkList.size(); ++i) {
298 // Determine if the exit from the block is reached by some def.
299 unsigned N = WorkList[i];
300 MachineBasicBlock &B = *MF->getBlockNumbered(N);
Krzysztof Parzyszek0b7688e2017-06-27 21:30:46 +0000301 if (Seen[N]) {
302 const LiveOutPair &LOB = Map[&B];
303 if (LOB.first != nullptr && LOB.first != &UndefVNI)
304 return MarkDefined(B);
305 }
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000306 SlotIndex Begin, End;
307 std::tie(Begin, End) = Indexes->getMBBRange(&B);
Krzysztof Parzyszekde44c9d2017-01-18 23:12:19 +0000308 // Treat End as not belonging to B.
309 // If LR has a segment S that starts at the next block, i.e. [End, ...),
310 // std::upper_bound will return the segment following S. Instead,
311 // S should be treated as the first segment that does not overlap B.
312 LiveRange::iterator UB = std::upper_bound(LR.begin(), LR.end(),
313 End.getPrevSlot());
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000314 if (UB != LR.begin()) {
315 LiveRange::Segment &Seg = *std::prev(UB);
316 if (Seg.end > Begin) {
317 // There is a segment that overlaps B. If the range is not explicitly
318 // undefined between the end of the segment and the end of the block,
319 // treat the block as defined on exit. If it is, go to the next block
320 // on the work list.
321 if (LR.isUndefIn(Undefs, Seg.end, End))
322 continue;
323 return MarkDefined(B);
324 }
325 }
326
327 // No segment overlaps with this block. If this block is not defined on
328 // entry, or it undefines the range, do not process its predecessors.
329 if (UndefOnEntry[N] || LR.isUndefIn(Undefs, Begin, End)) {
330 UndefOnEntry[N] = true;
331 continue;
332 }
333 if (DefOnEntry[N])
334 return MarkDefined(B);
335
336 // Still don't know: add all predecessors to the work list.
337 for (MachineBasicBlock *P : B.predecessors())
338 WorkList.insert(P->getNumber());
339 }
340
341 UndefOnEntry[BN] = true;
342 return false;
343}
344
Matthias Braun11042c82015-02-18 01:50:52 +0000345bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &UseMBB,
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000346 SlotIndex Use, unsigned PhysReg,
347 ArrayRef<SlotIndex> Undefs) {
Matthias Braun11042c82015-02-18 01:50:52 +0000348 unsigned UseMBBNum = UseMBB.getNumber();
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +0000349
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000350 // Block numbers where LR should be live-in.
Matthias Braun11042c82015-02-18 01:50:52 +0000351 SmallVector<unsigned, 16> WorkList(1, UseMBBNum);
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000352
353 // Remember if we have seen more than one value.
354 bool UniqueVNI = true;
Craig Topperc0196b12014-04-14 00:51:57 +0000355 VNInfo *TheVNI = nullptr;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000356
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000357 bool FoundUndef = false;
358
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000359 // Using Seen as a visited set, perform a BFS for all reaching defs.
360 for (unsigned i = 0; i != WorkList.size(); ++i) {
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +0000361 MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
Jakob Stoklund Olesen3d604ab2012-07-13 23:39:05 +0000362
363#ifndef NDEBUG
Matthias Braune1d96282016-09-19 16:49:45 +0000364 if (MBB->pred_empty()) {
Jakob Stoklund Olesen3d604ab2012-07-13 23:39:05 +0000365 MBB->getParent()->verify();
Matt Arsenault901a95f2018-10-30 01:11:31 +0000366 errs() << "Use of " << printReg(PhysReg, MRI->getTargetRegisterInfo())
Matthias Braun53917542015-05-11 18:47:47 +0000367 << " does not have a corresponding definition on every path:\n";
368 const MachineInstr *MI = Indexes->getInstructionFromIndex(Use);
369 if (MI != nullptr)
370 errs() << Use << " " << *MI;
Matthias Braune1d96282016-09-19 16:49:45 +0000371 report_fatal_error("Use not jointly dominated by defs.");
Jakob Stoklund Olesen3d604ab2012-07-13 23:39:05 +0000372 }
373
374 if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
375 !MBB->isLiveIn(PhysReg)) {
376 MBB->getParent()->verify();
Matt Arsenaultf3d1a1a2016-09-03 06:57:49 +0000377 const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo();
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000378 errs() << "The register " << printReg(PhysReg, TRI)
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000379 << " needs to be live in to " << printMBBReference(*MBB)
Jakob Stoklund Olesen3d604ab2012-07-13 23:39:05 +0000380 << ", but is missing from the live-in list.\n";
Matthias Braune1d96282016-09-19 16:49:45 +0000381 report_fatal_error("Invalid global physical register");
Jakob Stoklund Olesen3d604ab2012-07-13 23:39:05 +0000382 }
383#endif
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000384 FoundUndef |= MBB->pred_empty();
Jakob Stoklund Olesen3d604ab2012-07-13 23:39:05 +0000385
Krzysztof Parzyszek93cf2322017-06-28 16:02:00 +0000386 for (MachineBasicBlock *Pred : MBB->predecessors()) {
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000387 // Is this a known live-out block?
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000388 if (Seen.test(Pred->getNumber())) {
389 if (VNInfo *VNI = Map[Pred].first) {
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000390 if (TheVNI && TheVNI != VNI)
391 UniqueVNI = false;
392 TheVNI = VNI;
393 }
394 continue;
395 }
396
397 SlotIndex Start, End;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000398 std::tie(Start, End) = Indexes->getMBBRange(Pred);
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000399
400 // First time we see Pred. Try to determine the live-out value, but set
401 // it as null if Pred is live-through with an unknown value.
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000402 auto EP = LR.extendInBlock(Undefs, Start, End);
403 VNInfo *VNI = EP.first;
404 FoundUndef |= EP.second;
Krzysztof Parzyszek0b7688e2017-06-27 21:30:46 +0000405 setLiveOutValue(Pred, EP.second ? &UndefVNI : VNI);
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000406 if (VNI) {
407 if (TheVNI && TheVNI != VNI)
408 UniqueVNI = false;
409 TheVNI = VNI;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000410 }
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000411 if (VNI || EP.second)
412 continue;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000413
414 // No, we need a live-in value for Pred as well
Matthias Braun11042c82015-02-18 01:50:52 +0000415 if (Pred != &UseMBB)
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000416 WorkList.push_back(Pred->getNumber());
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000417 else
Matthias Braun11042c82015-02-18 01:50:52 +0000418 // Loopback to UseMBB, so value is really live through.
419 Use = SlotIndex();
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000420 }
421 }
422
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000423 LiveIn.clear();
Krzysztof Parzyszek30085942017-06-28 15:46:16 +0000424 FoundUndef |= (TheVNI == nullptr || TheVNI == &UndefVNI);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000425 if (!Undefs.empty() && FoundUndef)
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000426 UniqueVNI = false;
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +0000427
428 // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
429 // neither require it. Skip the sorting overhead for small updates.
430 if (WorkList.size() > 4)
431 array_pod_sort(WorkList.begin(), WorkList.end());
432
433 // If a unique reaching def was found, blit in the live ranges immediately.
434 if (UniqueVNI) {
Krzysztof Parzyszek0b7688e2017-06-27 21:30:46 +0000435 assert(TheVNI != nullptr && TheVNI != &UndefVNI);
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000436 LiveRangeUpdater Updater(&LR);
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000437 for (unsigned BN : WorkList) {
438 SlotIndex Start, End;
439 std::tie(Start, End) = Indexes->getMBBRange(BN);
440 // Trim the live range in UseMBB.
441 if (BN == UseMBBNum && Use.isValid())
442 End = Use;
443 else
444 Map[MF->getBlockNumbered(BN)] = LiveOutPair(TheVNI, nullptr);
445 Updater.add(Start, End, TheVNI);
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +0000446 }
447 return true;
448 }
449
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000450 // Prepare the defined/undefined bit vectors.
Matthias Brauna6e77402017-06-27 18:05:26 +0000451 EntryInfoMap::iterator Entry;
452 bool DidInsert;
453 std::tie(Entry, DidInsert) = EntryInfos.insert(
454 std::make_pair(&LR, std::make_pair(BitVector(), BitVector())));
455 if (DidInsert) {
456 // Initialize newly inserted entries.
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000457 unsigned N = MF->getNumBlockIDs();
Matthias Brauna6e77402017-06-27 18:05:26 +0000458 Entry->second.first.resize(N);
459 Entry->second.second.resize(N);
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000460 }
Matthias Brauna6e77402017-06-27 18:05:26 +0000461 BitVector &DefOnEntry = Entry->second.first;
462 BitVector &UndefOnEntry = Entry->second.second;
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000463
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +0000464 // Multiple values were found, so transfer the work list to the LiveIn array
465 // where UpdateSSA will use it as a work list.
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000466 LiveIn.reserve(WorkList.size());
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000467 for (unsigned BN : WorkList) {
468 MachineBasicBlock *MBB = MF->getBlockNumbered(BN);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000469 if (!Undefs.empty() &&
Krzysztof Parzyszek93cf2322017-06-28 16:02:00 +0000470 !isDefOnEntry(LR, Undefs, *MBB, DefOnEntry, UndefOnEntry))
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000471 continue;
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000472 addLiveInBlock(LR, DomTree->getNode(MBB));
Matthias Braun11042c82015-02-18 01:50:52 +0000473 if (MBB == &UseMBB)
474 LiveIn.back().Kill = Use;
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +0000475 }
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000476
Jakob Stoklund Olesenb3892712013-02-20 23:08:26 +0000477 return false;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000478}
479
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000480// This is essentially the same iterative algorithm that SSAUpdater uses,
481// except we already have a dominator tree, so we don't have to recompute it.
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000482void LiveRangeCalc::updateSSA() {
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000483 assert(Indexes && "Missing SlotIndexes");
484 assert(DomTree && "Missing dominator tree");
485
486 // Interate until convergence.
Krzysztof Parzyszek93cf2322017-06-28 16:02:00 +0000487 bool Changed;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000488 do {
Krzysztof Parzyszek93cf2322017-06-28 16:02:00 +0000489 Changed = false;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000490 // Propagate live-out values down the dominator tree, inserting phi-defs
491 // when necessary.
Matthias Braun42fab342014-12-15 19:40:46 +0000492 for (LiveInBlock &I : LiveIn) {
493 MachineDomTreeNode *Node = I.DomNode;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000494 // Skip block if the live-in value has already been determined.
495 if (!Node)
496 continue;
497 MachineBasicBlock *MBB = Node->getBlock();
498 MachineDomTreeNode *IDom = Node->getIDom();
499 LiveOutPair IDomValue;
500
501 // We need a live-in value to a block with no immediate dominator?
502 // This is probably an unreachable block that has survived somehow.
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000503 bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000504
505 // IDom dominates all of our predecessors, but it may not be their
506 // immediate dominator. Check if any of them have live-out values that are
507 // properly dominated by IDom. If so, we need a phi-def here.
508 if (!needPHI) {
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000509 IDomValue = Map[IDom->getBlock()];
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000510
511 // Cache the DomTree node that defined the value.
Krzysztof Parzyszek93cf2322017-06-28 16:02:00 +0000512 if (IDomValue.first && IDomValue.first != &UndefVNI &&
513 !IDomValue.second) {
514 Map[IDom->getBlock()].second = IDomValue.second =
515 DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
516 }
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000517
Krzysztof Parzyszek93cf2322017-06-28 16:02:00 +0000518 for (MachineBasicBlock *Pred : MBB->predecessors()) {
519 LiveOutPair &Value = Map[Pred];
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000520 if (!Value.first || Value.first == IDomValue.first)
521 continue;
Krzysztof Parzyszek0b7688e2017-06-27 21:30:46 +0000522 if (Value.first == &UndefVNI) {
523 needPHI = true;
524 break;
525 }
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000526
527 // Cache the DomTree node that defined the value.
528 if (!Value.second)
529 Value.second =
530 DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
531
532 // This predecessor is carrying something other than IDomValue.
533 // It could be because IDomValue hasn't propagated yet, or it could be
534 // because MBB is in the dominance frontier of that value.
535 if (DomTree->dominates(IDom, Value.second)) {
536 needPHI = true;
537 break;
538 }
539 }
540 }
541
542 // The value may be live-through even if Kill is set, as can happen when
543 // we are called from extendRange. In that case LiveOutSeen is true, and
544 // LiveOut indicates a foreign or missing value.
Matthias Braun1aed6ff2014-12-16 04:03:38 +0000545 LiveOutPair &LOP = Map[MBB];
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000546
547 // Create a phi-def if required.
548 if (needPHI) {
Krzysztof Parzyszek93cf2322017-06-28 16:02:00 +0000549 Changed = true;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000550 assert(Alloc && "Need VNInfo allocator to create PHI-defs");
551 SlotIndex Start, End;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000552 std::tie(Start, End) = Indexes->getMBBRange(MBB);
Matthias Braun42fab342014-12-15 19:40:46 +0000553 LiveRange &LR = I.LR;
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000554 VNInfo *VNI = LR.getNextValue(Start, *Alloc);
Matthias Braun42fab342014-12-15 19:40:46 +0000555 I.Value = VNI;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000556 // This block is done, we know the final value.
Matthias Braun42fab342014-12-15 19:40:46 +0000557 I.DomNode = nullptr;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000558
Matthias Braun2f662322014-12-10 01:12:12 +0000559 // Add liveness since updateFromLiveIns now skips this node.
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000560 if (I.Kill.isValid()) {
561 if (VNI)
562 LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
563 } else {
564 if (VNI)
565 LR.addSegment(LiveInterval::Segment(Start, End, VNI));
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000566 LOP = LiveOutPair(VNI, Node);
567 }
Krzysztof Parzyszek0b7688e2017-06-27 21:30:46 +0000568 } else if (IDomValue.first && IDomValue.first != &UndefVNI) {
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000569 // No phi-def here. Remember incoming value.
Matthias Braun42fab342014-12-15 19:40:46 +0000570 I.Value = IDomValue.first;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000571
572 // If the IDomValue is killed in the block, don't propagate through.
Matthias Braun42fab342014-12-15 19:40:46 +0000573 if (I.Kill.isValid())
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000574 continue;
575
576 // Propagate IDomValue if it isn't killed:
577 // MBB is live-out and doesn't define its own value.
578 if (LOP.first == IDomValue.first)
579 continue;
Krzysztof Parzyszek93cf2322017-06-28 16:02:00 +0000580 Changed = true;
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000581 LOP = IDomValue;
582 }
583 }
Krzysztof Parzyszek93cf2322017-06-28 16:02:00 +0000584 } while (Changed);
Jakob Stoklund Olesen487f2a32011-09-13 01:34:21 +0000585}
Krzysztof Parzyszek70f02702018-06-26 14:37:16 +0000586
587bool LiveRangeCalc::isJointlyDominated(const MachineBasicBlock *MBB,
588 ArrayRef<SlotIndex> Defs,
589 const SlotIndexes &Indexes) {
590 const MachineFunction &MF = *MBB->getParent();
591 BitVector DefBlocks(MF.getNumBlockIDs());
592 for (SlotIndex I : Defs)
593 DefBlocks.set(Indexes.getMBBFromIndex(I)->getNumber());
594
595 SetVector<unsigned> PredQueue;
596 PredQueue.insert(MBB->getNumber());
597 for (unsigned i = 0; i != PredQueue.size(); ++i) {
598 unsigned BN = PredQueue[i];
599 if (DefBlocks[BN])
600 return true;
601 const MachineBasicBlock *B = MF.getBlockNumbered(BN);
602 for (const MachineBasicBlock *P : B->predecessors())
603 PredQueue.insert(P->getNumber());
604 }
605 return false;
606}