12cab237bSDimitry Andric //===- LiveRangeCalc.cpp - Calculate live ranges --------------------------===//
26122f3e6SDimitry Andric //
36122f3e6SDimitry Andric // The LLVM Compiler Infrastructure
46122f3e6SDimitry Andric //
56122f3e6SDimitry Andric // This file is distributed under the University of Illinois Open Source
66122f3e6SDimitry Andric // License. See LICENSE.TXT for details.
76122f3e6SDimitry Andric //
86122f3e6SDimitry Andric //===----------------------------------------------------------------------===//
96122f3e6SDimitry Andric //
106122f3e6SDimitry Andric // Implementation of the LiveRangeCalc class.
116122f3e6SDimitry Andric //
126122f3e6SDimitry Andric //===----------------------------------------------------------------------===//
136122f3e6SDimitry Andric
146122f3e6SDimitry Andric #include "LiveRangeCalc.h"
152cab237bSDimitry Andric #include "llvm/ADT/BitVector.h"
162cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
17d88c1a5aSDimitry Andric #include "llvm/ADT/SetVector.h"
182cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
192cab237bSDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
202cab237bSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
216122f3e6SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
222cab237bSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
232cab237bSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
242cab237bSDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
257ae0e2c9SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
262cab237bSDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
272cab237bSDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
282cab237bSDimitry Andric #include "llvm/MC/LaneBitmask.h"
292cab237bSDimitry Andric #include "llvm/Support/ErrorHandling.h"
302cab237bSDimitry Andric #include "llvm/Support/raw_ostream.h"
312cab237bSDimitry Andric #include <algorithm>
322cab237bSDimitry Andric #include <cassert>
332cab237bSDimitry Andric #include <iterator>
342cab237bSDimitry Andric #include <tuple>
352cab237bSDimitry Andric #include <utility>
366122f3e6SDimitry Andric
376122f3e6SDimitry Andric using namespace llvm;
386122f3e6SDimitry Andric
3991bc56edSDimitry Andric #define DEBUG_TYPE "regalloc"
4091bc56edSDimitry Andric
41a580b014SDimitry Andric // Reserve an address that indicates a value that is known to be "undef".
42a580b014SDimitry Andric static VNInfo UndefVNI(0xbad, SlotIndex());
43a580b014SDimitry Andric
resetLiveOutMap()4439d628a0SDimitry Andric void LiveRangeCalc::resetLiveOutMap() {
4539d628a0SDimitry Andric unsigned NumBlocks = MF->getNumBlockIDs();
4639d628a0SDimitry Andric Seen.clear();
4739d628a0SDimitry Andric Seen.resize(NumBlocks);
48a580b014SDimitry Andric EntryInfos.clear();
4939d628a0SDimitry Andric Map.resize(NumBlocks);
5039d628a0SDimitry Andric }
5139d628a0SDimitry Andric
reset(const MachineFunction * mf,SlotIndexes * SI,MachineDominatorTree * MDT,VNInfo::Allocator * VNIA)52139f7f9bSDimitry Andric void LiveRangeCalc::reset(const MachineFunction *mf,
537ae0e2c9SDimitry Andric SlotIndexes *SI,
547ae0e2c9SDimitry Andric MachineDominatorTree *MDT,
557ae0e2c9SDimitry Andric VNInfo::Allocator *VNIA) {
56139f7f9bSDimitry Andric MF = mf;
577ae0e2c9SDimitry Andric MRI = &MF->getRegInfo();
587ae0e2c9SDimitry Andric Indexes = SI;
597ae0e2c9SDimitry Andric DomTree = MDT;
607ae0e2c9SDimitry Andric Alloc = VNIA;
6139d628a0SDimitry Andric resetLiveOutMap();
626122f3e6SDimitry Andric LiveIn.clear();
636122f3e6SDimitry Andric }
646122f3e6SDimitry Andric
createDeadDef(SlotIndexes & Indexes,VNInfo::Allocator & Alloc,LiveRange & LR,const MachineOperand & MO)6539d628a0SDimitry Andric static void createDeadDef(SlotIndexes &Indexes, VNInfo::Allocator &Alloc,
6639d628a0SDimitry Andric LiveRange &LR, const MachineOperand &MO) {
673ca95b02SDimitry Andric const MachineInstr &MI = *MO.getParent();
68ff0cc061SDimitry Andric SlotIndex DefIdx =
69ff0cc061SDimitry Andric Indexes.getInstructionIndex(MI).getRegSlot(MO.isEarlyClobber());
7039d628a0SDimitry Andric
7139d628a0SDimitry Andric // Create the def in LR. This may find an existing def.
7239d628a0SDimitry Andric LR.createDeadDef(DefIdx, Alloc);
7339d628a0SDimitry Andric }
7439d628a0SDimitry Andric
calculate(LiveInterval & LI,bool TrackSubRegs)75ff0cc061SDimitry Andric void LiveRangeCalc::calculate(LiveInterval &LI, bool TrackSubRegs) {
7639d628a0SDimitry Andric assert(MRI && Indexes && "call reset() first");
7739d628a0SDimitry Andric
7839d628a0SDimitry Andric // Step 1: Create minimal live segments for every definition of Reg.
7939d628a0SDimitry Andric // Visit all def operands. If the same instruction has multiple defs of Reg,
8039d628a0SDimitry Andric // createDeadDef() will deduplicate.
8139d628a0SDimitry Andric const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
8239d628a0SDimitry Andric unsigned Reg = LI.reg;
8339d628a0SDimitry Andric for (const MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
8439d628a0SDimitry Andric if (!MO.isDef() && !MO.readsReg())
8539d628a0SDimitry Andric continue;
8639d628a0SDimitry Andric
8739d628a0SDimitry Andric unsigned SubReg = MO.getSubReg();
88ff0cc061SDimitry Andric if (LI.hasSubRanges() || (SubReg != 0 && TrackSubRegs)) {
89d88c1a5aSDimitry Andric LaneBitmask SubMask = SubReg != 0 ? TRI.getSubRegIndexLaneMask(SubReg)
9039d628a0SDimitry Andric : MRI->getMaxLaneMaskForVReg(Reg);
9139d628a0SDimitry Andric // If this is the first time we see a subregister def, initialize
9239d628a0SDimitry Andric // subranges by creating a copy of the main range.
9339d628a0SDimitry Andric if (!LI.hasSubRanges() && !LI.empty()) {
947d523365SDimitry Andric LaneBitmask ClassMask = MRI->getMaxLaneMaskForVReg(Reg);
9539d628a0SDimitry Andric LI.createSubRangeFrom(*Alloc, ClassMask, LI);
9639d628a0SDimitry Andric }
9739d628a0SDimitry Andric
987a7e6055SDimitry Andric LI.refineSubRanges(*Alloc, SubMask,
997a7e6055SDimitry Andric [&MO, this](LiveInterval::SubRange &SR) {
10039d628a0SDimitry Andric if (MO.isDef())
1017a7e6055SDimitry Andric createDeadDef(*Indexes, *Alloc, SR, MO);
1027a7e6055SDimitry Andric });
10339d628a0SDimitry Andric }
10439d628a0SDimitry Andric
10539d628a0SDimitry Andric // Create the def in the main liverange. We do not have to do this if
10639d628a0SDimitry Andric // subranges are tracked as we recreate the main range later in this case.
10739d628a0SDimitry Andric if (MO.isDef() && !LI.hasSubRanges())
10839d628a0SDimitry Andric createDeadDef(*Indexes, *Alloc, LI, MO);
10939d628a0SDimitry Andric }
11039d628a0SDimitry Andric
11139d628a0SDimitry Andric // We may have created empty live ranges for partially undefined uses, we
11239d628a0SDimitry Andric // can't keep them because we won't find defs in them later.
11339d628a0SDimitry Andric LI.removeEmptySubRanges();
11439d628a0SDimitry Andric
11539d628a0SDimitry Andric // Step 2: Extend live segments to all uses, constructing SSA form as
11639d628a0SDimitry Andric // necessary.
11739d628a0SDimitry Andric if (LI.hasSubRanges()) {
11839d628a0SDimitry Andric for (LiveInterval::SubRange &S : LI.subranges()) {
119d88c1a5aSDimitry Andric LiveRangeCalc SubLRC;
120d88c1a5aSDimitry Andric SubLRC.reset(MF, Indexes, DomTree, Alloc);
121d88c1a5aSDimitry Andric SubLRC.extendToUses(S, Reg, S.LaneMask, &LI);
12239d628a0SDimitry Andric }
12339d628a0SDimitry Andric LI.clear();
1243ca95b02SDimitry Andric constructMainRangeFromSubranges(LI);
12539d628a0SDimitry Andric } else {
12639d628a0SDimitry Andric resetLiveOutMap();
127d88c1a5aSDimitry Andric extendToUses(LI, Reg, LaneBitmask::getAll());
12839d628a0SDimitry Andric }
12939d628a0SDimitry Andric }
13039d628a0SDimitry Andric
constructMainRangeFromSubranges(LiveInterval & LI)1313ca95b02SDimitry Andric void LiveRangeCalc::constructMainRangeFromSubranges(LiveInterval &LI) {
1323ca95b02SDimitry Andric // First create dead defs at all defs found in subranges.
1333ca95b02SDimitry Andric LiveRange &MainRange = LI;
1343ca95b02SDimitry Andric assert(MainRange.segments.empty() && MainRange.valnos.empty() &&
1353ca95b02SDimitry Andric "Expect empty main liverange");
1363ca95b02SDimitry Andric
1373ca95b02SDimitry Andric for (const LiveInterval::SubRange &SR : LI.subranges()) {
1383ca95b02SDimitry Andric for (const VNInfo *VNI : SR.valnos) {
1393ca95b02SDimitry Andric if (!VNI->isUnused() && !VNI->isPHIDef())
1403ca95b02SDimitry Andric MainRange.createDeadDef(VNI->def, *Alloc);
1413ca95b02SDimitry Andric }
1423ca95b02SDimitry Andric }
1433ca95b02SDimitry Andric resetLiveOutMap();
144d88c1a5aSDimitry Andric extendToUses(MainRange, LI.reg, LaneBitmask::getAll(), &LI);
1453ca95b02SDimitry Andric }
14639d628a0SDimitry Andric
createDeadDefs(LiveRange & LR,unsigned Reg)147f785676fSDimitry Andric void LiveRangeCalc::createDeadDefs(LiveRange &LR, unsigned Reg) {
1487ae0e2c9SDimitry Andric assert(MRI && Indexes && "call reset() first");
1497ae0e2c9SDimitry Andric
1507ae0e2c9SDimitry Andric // Visit all def operands. If the same instruction has multiple defs of Reg,
151f785676fSDimitry Andric // LR.createDeadDef() will deduplicate.
15239d628a0SDimitry Andric for (MachineOperand &MO : MRI->def_operands(Reg))
15339d628a0SDimitry Andric createDeadDef(*Indexes, *Alloc, LR, MO);
1547ae0e2c9SDimitry Andric }
1557ae0e2c9SDimitry Andric
extendToUses(LiveRange & LR,unsigned Reg,LaneBitmask Mask,LiveInterval * LI)156d88c1a5aSDimitry Andric void LiveRangeCalc::extendToUses(LiveRange &LR, unsigned Reg, LaneBitmask Mask,
157d88c1a5aSDimitry Andric LiveInterval *LI) {
158d88c1a5aSDimitry Andric SmallVector<SlotIndex, 4> Undefs;
159d88c1a5aSDimitry Andric if (LI != nullptr)
160d88c1a5aSDimitry Andric LI->computeSubRangeUndefs(Undefs, Mask, *MRI, *Indexes);
161d88c1a5aSDimitry Andric
1627ae0e2c9SDimitry Andric // Visit all operands that read Reg. This may include partial defs.
163d88c1a5aSDimitry Andric bool IsSubRange = !Mask.all();
16439d628a0SDimitry Andric const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
16591bc56edSDimitry Andric for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
1663861d79fSDimitry Andric // Clear all kill flags. They will be reinserted after register allocation
1672cab237bSDimitry Andric // by LiveIntervals::addKillFlags().
1683861d79fSDimitry Andric if (MO.isUse())
1693861d79fSDimitry Andric MO.setIsKill(false);
170d88c1a5aSDimitry Andric // MO::readsReg returns "true" for subregister defs. This is for keeping
171d88c1a5aSDimitry Andric // liveness of the entire register (i.e. for the main range of the live
172d88c1a5aSDimitry Andric // interval). For subranges, definitions of non-overlapping subregisters
173d88c1a5aSDimitry Andric // do not count as uses.
174d88c1a5aSDimitry Andric if (!MO.readsReg() || (IsSubRange && MO.isDef()))
17539d628a0SDimitry Andric continue;
17639d628a0SDimitry Andric
17739d628a0SDimitry Andric unsigned SubReg = MO.getSubReg();
17839d628a0SDimitry Andric if (SubReg != 0) {
179d88c1a5aSDimitry Andric LaneBitmask SLM = TRI.getSubRegIndexLaneMask(SubReg);
180d88c1a5aSDimitry Andric if (MO.isDef())
181d88c1a5aSDimitry Andric SLM = ~SLM;
182d88c1a5aSDimitry Andric // Ignore uses not reading the current (sub)range.
183d88c1a5aSDimitry Andric if ((SLM & Mask).none())
18439d628a0SDimitry Andric continue;
18539d628a0SDimitry Andric }
18639d628a0SDimitry Andric
18739d628a0SDimitry Andric // Determine the actual place of the use.
18891bc56edSDimitry Andric const MachineInstr *MI = MO.getParent();
18991bc56edSDimitry Andric unsigned OpNo = (&MO - &MI->getOperand(0));
19039d628a0SDimitry Andric SlotIndex UseIdx;
1917ae0e2c9SDimitry Andric if (MI->isPHI()) {
1927ae0e2c9SDimitry Andric assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
19339d628a0SDimitry Andric // The actual place where a phi operand is used is the end of the pred
19439d628a0SDimitry Andric // MBB. PHI operands are paired: (Reg, PredMBB).
19539d628a0SDimitry Andric UseIdx = Indexes->getMBBEndIdx(MI->getOperand(OpNo+1).getMBB());
1967ae0e2c9SDimitry Andric } else {
1977ae0e2c9SDimitry Andric // Check for early-clobber redefs.
19839d628a0SDimitry Andric bool isEarlyClobber = false;
1997ae0e2c9SDimitry Andric unsigned DefIdx;
20039d628a0SDimitry Andric if (MO.isDef())
20139d628a0SDimitry Andric isEarlyClobber = MO.isEarlyClobber();
20239d628a0SDimitry Andric else if (MI->isRegTiedToDefOperand(OpNo, &DefIdx)) {
2037ae0e2c9SDimitry Andric // FIXME: This would be a lot easier if tied early-clobber uses also
2047ae0e2c9SDimitry Andric // had an early-clobber flag.
20539d628a0SDimitry Andric isEarlyClobber = MI->getOperand(DefIdx).isEarlyClobber();
2067ae0e2c9SDimitry Andric }
2073ca95b02SDimitry Andric UseIdx = Indexes->getInstructionIndex(*MI).getRegSlot(isEarlyClobber);
2087ae0e2c9SDimitry Andric }
20939d628a0SDimitry Andric
21039d628a0SDimitry Andric // MI is reading Reg. We may have visited MI before if it happens to be
21139d628a0SDimitry Andric // reading Reg multiple times. That is OK, extend() is idempotent.
212d88c1a5aSDimitry Andric extend(LR, UseIdx, Reg, Undefs);
2137ae0e2c9SDimitry Andric }
2147ae0e2c9SDimitry Andric }
2157ae0e2c9SDimitry Andric
updateFromLiveIns()21639d628a0SDimitry Andric void LiveRangeCalc::updateFromLiveIns() {
217139f7f9bSDimitry Andric LiveRangeUpdater Updater;
21839d628a0SDimitry Andric for (const LiveInBlock &I : LiveIn) {
21939d628a0SDimitry Andric if (!I.DomNode)
2206122f3e6SDimitry Andric continue;
22139d628a0SDimitry Andric MachineBasicBlock *MBB = I.DomNode->getBlock();
22239d628a0SDimitry Andric assert(I.Value && "No live-in value found");
2236122f3e6SDimitry Andric SlotIndex Start, End;
22491bc56edSDimitry Andric std::tie(Start, End) = Indexes->getMBBRange(MBB);
2256122f3e6SDimitry Andric
22639d628a0SDimitry Andric if (I.Kill.isValid())
227139f7f9bSDimitry Andric // Value is killed inside this block.
22839d628a0SDimitry Andric End = I.Kill;
2296122f3e6SDimitry Andric else {
230139f7f9bSDimitry Andric // The value is live-through, update LiveOut as well.
231139f7f9bSDimitry Andric // Defer the Domtree lookup until it is needed.
2326122f3e6SDimitry Andric assert(Seen.test(MBB->getNumber()));
23339d628a0SDimitry Andric Map[MBB] = LiveOutPair(I.Value, nullptr);
2346122f3e6SDimitry Andric }
23539d628a0SDimitry Andric Updater.setDest(&I.LR);
23639d628a0SDimitry Andric Updater.add(Start, End, I.Value);
2376122f3e6SDimitry Andric }
2386122f3e6SDimitry Andric LiveIn.clear();
2396122f3e6SDimitry Andric }
2406122f3e6SDimitry Andric
extend(LiveRange & LR,SlotIndex Use,unsigned PhysReg,ArrayRef<SlotIndex> Undefs)241d88c1a5aSDimitry Andric void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Use, unsigned PhysReg,
242d88c1a5aSDimitry Andric ArrayRef<SlotIndex> Undefs) {
243ff0cc061SDimitry Andric assert(Use.isValid() && "Invalid SlotIndex");
2446122f3e6SDimitry Andric assert(Indexes && "Missing SlotIndexes");
2456122f3e6SDimitry Andric assert(DomTree && "Missing dominator tree");
2466122f3e6SDimitry Andric
247ff0cc061SDimitry Andric MachineBasicBlock *UseMBB = Indexes->getMBBFromIndex(Use.getPrevSlot());
248ff0cc061SDimitry Andric assert(UseMBB && "No MBB at Use");
2496122f3e6SDimitry Andric
2506122f3e6SDimitry Andric // Is there a def in the same MBB we can extend?
251d88c1a5aSDimitry Andric auto EP = LR.extendInBlock(Undefs, Indexes->getMBBStartIdx(UseMBB), Use);
252d88c1a5aSDimitry Andric if (EP.first != nullptr || EP.second)
2536122f3e6SDimitry Andric return;
2546122f3e6SDimitry Andric
255ff0cc061SDimitry Andric // Find the single reaching def, or determine if Use is jointly dominated by
2566122f3e6SDimitry Andric // multiple values, and we may need to create even more phi-defs to preserve
2576122f3e6SDimitry Andric // VNInfo SSA form. Perform a search for all predecessor blocks where we
2586122f3e6SDimitry Andric // know the dominating VNInfo.
259d88c1a5aSDimitry Andric if (findReachingDefs(LR, *UseMBB, Use, PhysReg, Undefs))
260139f7f9bSDimitry Andric return;
2616122f3e6SDimitry Andric
2626122f3e6SDimitry Andric // When there were multiple different values, we may need new PHIs.
263139f7f9bSDimitry Andric calculateValues();
2646122f3e6SDimitry Andric }
2656122f3e6SDimitry Andric
2666122f3e6SDimitry Andric // This function is called by a client after using the low-level API to add
2676122f3e6SDimitry Andric // live-out and live-in blocks. The unique value optimization is not
2686122f3e6SDimitry Andric // available, SplitEditor::transferValues handles that case directly anyway.
calculateValues()2697ae0e2c9SDimitry Andric void LiveRangeCalc::calculateValues() {
2706122f3e6SDimitry Andric assert(Indexes && "Missing SlotIndexes");
2716122f3e6SDimitry Andric assert(DomTree && "Missing dominator tree");
2727ae0e2c9SDimitry Andric updateSSA();
27339d628a0SDimitry Andric updateFromLiveIns();
2746122f3e6SDimitry Andric }
2756122f3e6SDimitry Andric
isDefOnEntry(LiveRange & LR,ArrayRef<SlotIndex> Undefs,MachineBasicBlock & MBB,BitVector & DefOnEntry,BitVector & UndefOnEntry)276d88c1a5aSDimitry Andric bool LiveRangeCalc::isDefOnEntry(LiveRange &LR, ArrayRef<SlotIndex> Undefs,
277d88c1a5aSDimitry Andric MachineBasicBlock &MBB, BitVector &DefOnEntry,
278d88c1a5aSDimitry Andric BitVector &UndefOnEntry) {
279d88c1a5aSDimitry Andric unsigned BN = MBB.getNumber();
280d88c1a5aSDimitry Andric if (DefOnEntry[BN])
281d88c1a5aSDimitry Andric return true;
282d88c1a5aSDimitry Andric if (UndefOnEntry[BN])
283d88c1a5aSDimitry Andric return false;
284d88c1a5aSDimitry Andric
2857a7e6055SDimitry Andric auto MarkDefined = [BN, &DefOnEntry](MachineBasicBlock &B) -> bool {
286d88c1a5aSDimitry Andric for (MachineBasicBlock *S : B.successors())
287d88c1a5aSDimitry Andric DefOnEntry[S->getNumber()] = true;
288d88c1a5aSDimitry Andric DefOnEntry[BN] = true;
289d88c1a5aSDimitry Andric return true;
290d88c1a5aSDimitry Andric };
291d88c1a5aSDimitry Andric
292d88c1a5aSDimitry Andric SetVector<unsigned> WorkList;
293d88c1a5aSDimitry Andric // Checking if the entry of MBB is reached by some def: add all predecessors
294d88c1a5aSDimitry Andric // that are potentially defined-on-exit to the work list.
295d88c1a5aSDimitry Andric for (MachineBasicBlock *P : MBB.predecessors())
296d88c1a5aSDimitry Andric WorkList.insert(P->getNumber());
297d88c1a5aSDimitry Andric
298d88c1a5aSDimitry Andric for (unsigned i = 0; i != WorkList.size(); ++i) {
299d88c1a5aSDimitry Andric // Determine if the exit from the block is reached by some def.
300d88c1a5aSDimitry Andric unsigned N = WorkList[i];
301d88c1a5aSDimitry Andric MachineBasicBlock &B = *MF->getBlockNumbered(N);
302a580b014SDimitry Andric if (Seen[N]) {
303a580b014SDimitry Andric const LiveOutPair &LOB = Map[&B];
304a580b014SDimitry Andric if (LOB.first != nullptr && LOB.first != &UndefVNI)
305d88c1a5aSDimitry Andric return MarkDefined(B);
306a580b014SDimitry Andric }
307d88c1a5aSDimitry Andric SlotIndex Begin, End;
308d88c1a5aSDimitry Andric std::tie(Begin, End) = Indexes->getMBBRange(&B);
3097a7e6055SDimitry Andric // Treat End as not belonging to B.
3107a7e6055SDimitry Andric // If LR has a segment S that starts at the next block, i.e. [End, ...),
3117a7e6055SDimitry Andric // std::upper_bound will return the segment following S. Instead,
3127a7e6055SDimitry Andric // S should be treated as the first segment that does not overlap B.
3137a7e6055SDimitry Andric LiveRange::iterator UB = std::upper_bound(LR.begin(), LR.end(),
3147a7e6055SDimitry Andric End.getPrevSlot());
315d88c1a5aSDimitry Andric if (UB != LR.begin()) {
316d88c1a5aSDimitry Andric LiveRange::Segment &Seg = *std::prev(UB);
317d88c1a5aSDimitry Andric if (Seg.end > Begin) {
318d88c1a5aSDimitry Andric // There is a segment that overlaps B. If the range is not explicitly
319d88c1a5aSDimitry Andric // undefined between the end of the segment and the end of the block,
320d88c1a5aSDimitry Andric // treat the block as defined on exit. If it is, go to the next block
321d88c1a5aSDimitry Andric // on the work list.
322d88c1a5aSDimitry Andric if (LR.isUndefIn(Undefs, Seg.end, End))
323d88c1a5aSDimitry Andric continue;
324d88c1a5aSDimitry Andric return MarkDefined(B);
325d88c1a5aSDimitry Andric }
326d88c1a5aSDimitry Andric }
327d88c1a5aSDimitry Andric
328d88c1a5aSDimitry Andric // No segment overlaps with this block. If this block is not defined on
329d88c1a5aSDimitry Andric // entry, or it undefines the range, do not process its predecessors.
330d88c1a5aSDimitry Andric if (UndefOnEntry[N] || LR.isUndefIn(Undefs, Begin, End)) {
331d88c1a5aSDimitry Andric UndefOnEntry[N] = true;
332d88c1a5aSDimitry Andric continue;
333d88c1a5aSDimitry Andric }
334d88c1a5aSDimitry Andric if (DefOnEntry[N])
335d88c1a5aSDimitry Andric return MarkDefined(B);
336d88c1a5aSDimitry Andric
337d88c1a5aSDimitry Andric // Still don't know: add all predecessors to the work list.
338d88c1a5aSDimitry Andric for (MachineBasicBlock *P : B.predecessors())
339d88c1a5aSDimitry Andric WorkList.insert(P->getNumber());
340d88c1a5aSDimitry Andric }
341d88c1a5aSDimitry Andric
342d88c1a5aSDimitry Andric UndefOnEntry[BN] = true;
343d88c1a5aSDimitry Andric return false;
344d88c1a5aSDimitry Andric }
345d88c1a5aSDimitry Andric
findReachingDefs(LiveRange & LR,MachineBasicBlock & UseMBB,SlotIndex Use,unsigned PhysReg,ArrayRef<SlotIndex> Undefs)346ff0cc061SDimitry Andric bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &UseMBB,
347d88c1a5aSDimitry Andric SlotIndex Use, unsigned PhysReg,
348d88c1a5aSDimitry Andric ArrayRef<SlotIndex> Undefs) {
349ff0cc061SDimitry Andric unsigned UseMBBNum = UseMBB.getNumber();
350139f7f9bSDimitry Andric
351f785676fSDimitry Andric // Block numbers where LR should be live-in.
352ff0cc061SDimitry Andric SmallVector<unsigned, 16> WorkList(1, UseMBBNum);
3536122f3e6SDimitry Andric
3546122f3e6SDimitry Andric // Remember if we have seen more than one value.
3556122f3e6SDimitry Andric bool UniqueVNI = true;
35691bc56edSDimitry Andric VNInfo *TheVNI = nullptr;
3576122f3e6SDimitry Andric
358d88c1a5aSDimitry Andric bool FoundUndef = false;
359d88c1a5aSDimitry Andric
3606122f3e6SDimitry Andric // Using Seen as a visited set, perform a BFS for all reaching defs.
3616122f3e6SDimitry Andric for (unsigned i = 0; i != WorkList.size(); ++i) {
362139f7f9bSDimitry Andric MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
3637ae0e2c9SDimitry Andric
3647ae0e2c9SDimitry Andric #ifndef NDEBUG
3657ae0e2c9SDimitry Andric if (MBB->pred_empty()) {
3667ae0e2c9SDimitry Andric MBB->getParent()->verify();
367*b5893f02SDimitry Andric errs() << "Use of " << printReg(PhysReg, MRI->getTargetRegisterInfo())
368ff0cc061SDimitry Andric << " does not have a corresponding definition on every path:\n";
369ff0cc061SDimitry Andric const MachineInstr *MI = Indexes->getInstructionFromIndex(Use);
370ff0cc061SDimitry Andric if (MI != nullptr)
371ff0cc061SDimitry Andric errs() << Use << " " << *MI;
372d88c1a5aSDimitry Andric report_fatal_error("Use not jointly dominated by defs.");
3737ae0e2c9SDimitry Andric }
3747ae0e2c9SDimitry Andric
3757ae0e2c9SDimitry Andric if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
3767ae0e2c9SDimitry Andric !MBB->isLiveIn(PhysReg)) {
3777ae0e2c9SDimitry Andric MBB->getParent()->verify();
378d88c1a5aSDimitry Andric const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo();
3792cab237bSDimitry Andric errs() << "The register " << printReg(PhysReg, TRI)
3802cab237bSDimitry Andric << " needs to be live in to " << printMBBReference(*MBB)
3817ae0e2c9SDimitry Andric << ", but is missing from the live-in list.\n";
382d88c1a5aSDimitry Andric report_fatal_error("Invalid global physical register");
3837ae0e2c9SDimitry Andric }
3847ae0e2c9SDimitry Andric #endif
385d88c1a5aSDimitry Andric FoundUndef |= MBB->pred_empty();
3867ae0e2c9SDimitry Andric
387a580b014SDimitry Andric for (MachineBasicBlock *Pred : MBB->predecessors()) {
3886122f3e6SDimitry Andric // Is this a known live-out block?
3896122f3e6SDimitry Andric if (Seen.test(Pred->getNumber())) {
39039d628a0SDimitry Andric if (VNInfo *VNI = Map[Pred].first) {
3916122f3e6SDimitry Andric if (TheVNI && TheVNI != VNI)
3926122f3e6SDimitry Andric UniqueVNI = false;
3936122f3e6SDimitry Andric TheVNI = VNI;
3946122f3e6SDimitry Andric }
3956122f3e6SDimitry Andric continue;
3966122f3e6SDimitry Andric }
3976122f3e6SDimitry Andric
3986122f3e6SDimitry Andric SlotIndex Start, End;
39991bc56edSDimitry Andric std::tie(Start, End) = Indexes->getMBBRange(Pred);
4006122f3e6SDimitry Andric
4016122f3e6SDimitry Andric // First time we see Pred. Try to determine the live-out value, but set
4026122f3e6SDimitry Andric // it as null if Pred is live-through with an unknown value.
403d88c1a5aSDimitry Andric auto EP = LR.extendInBlock(Undefs, Start, End);
404d88c1a5aSDimitry Andric VNInfo *VNI = EP.first;
405d88c1a5aSDimitry Andric FoundUndef |= EP.second;
406a580b014SDimitry Andric setLiveOutValue(Pred, EP.second ? &UndefVNI : VNI);
4076122f3e6SDimitry Andric if (VNI) {
4086122f3e6SDimitry Andric if (TheVNI && TheVNI != VNI)
4096122f3e6SDimitry Andric UniqueVNI = false;
4106122f3e6SDimitry Andric TheVNI = VNI;
4116122f3e6SDimitry Andric }
412d88c1a5aSDimitry Andric if (VNI || EP.second)
413d88c1a5aSDimitry Andric continue;
4146122f3e6SDimitry Andric
4156122f3e6SDimitry Andric // No, we need a live-in value for Pred as well
416ff0cc061SDimitry Andric if (Pred != &UseMBB)
417139f7f9bSDimitry Andric WorkList.push_back(Pred->getNumber());
4186122f3e6SDimitry Andric else
419ff0cc061SDimitry Andric // Loopback to UseMBB, so value is really live through.
420ff0cc061SDimitry Andric Use = SlotIndex();
4216122f3e6SDimitry Andric }
4226122f3e6SDimitry Andric }
4236122f3e6SDimitry Andric
4246122f3e6SDimitry Andric LiveIn.clear();
425a580b014SDimitry Andric FoundUndef |= (TheVNI == nullptr || TheVNI == &UndefVNI);
4262cab237bSDimitry Andric if (!Undefs.empty() && FoundUndef)
427d88c1a5aSDimitry Andric UniqueVNI = false;
428139f7f9bSDimitry Andric
429139f7f9bSDimitry Andric // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
430139f7f9bSDimitry Andric // neither require it. Skip the sorting overhead for small updates.
431139f7f9bSDimitry Andric if (WorkList.size() > 4)
432139f7f9bSDimitry Andric array_pod_sort(WorkList.begin(), WorkList.end());
433139f7f9bSDimitry Andric
434139f7f9bSDimitry Andric // If a unique reaching def was found, blit in the live ranges immediately.
435139f7f9bSDimitry Andric if (UniqueVNI) {
436a580b014SDimitry Andric assert(TheVNI != nullptr && TheVNI != &UndefVNI);
437f785676fSDimitry Andric LiveRangeUpdater Updater(&LR);
438d88c1a5aSDimitry Andric for (unsigned BN : WorkList) {
439139f7f9bSDimitry Andric SlotIndex Start, End;
440d88c1a5aSDimitry Andric std::tie(Start, End) = Indexes->getMBBRange(BN);
441ff0cc061SDimitry Andric // Trim the live range in UseMBB.
442d88c1a5aSDimitry Andric if (BN == UseMBBNum && Use.isValid())
443ff0cc061SDimitry Andric End = Use;
444139f7f9bSDimitry Andric else
445d88c1a5aSDimitry Andric Map[MF->getBlockNumbered(BN)] = LiveOutPair(TheVNI, nullptr);
446139f7f9bSDimitry Andric Updater.add(Start, End, TheVNI);
447139f7f9bSDimitry Andric }
448139f7f9bSDimitry Andric return true;
449139f7f9bSDimitry Andric }
450139f7f9bSDimitry Andric
451d88c1a5aSDimitry Andric // Prepare the defined/undefined bit vectors.
452a580b014SDimitry Andric EntryInfoMap::iterator Entry;
453a580b014SDimitry Andric bool DidInsert;
454a580b014SDimitry Andric std::tie(Entry, DidInsert) = EntryInfos.insert(
455a580b014SDimitry Andric std::make_pair(&LR, std::make_pair(BitVector(), BitVector())));
456a580b014SDimitry Andric if (DidInsert) {
457a580b014SDimitry Andric // Initialize newly inserted entries.
458d88c1a5aSDimitry Andric unsigned N = MF->getNumBlockIDs();
459a580b014SDimitry Andric Entry->second.first.resize(N);
460a580b014SDimitry Andric Entry->second.second.resize(N);
461d88c1a5aSDimitry Andric }
462a580b014SDimitry Andric BitVector &DefOnEntry = Entry->second.first;
463a580b014SDimitry Andric BitVector &UndefOnEntry = Entry->second.second;
464d88c1a5aSDimitry Andric
465139f7f9bSDimitry Andric // Multiple values were found, so transfer the work list to the LiveIn array
466139f7f9bSDimitry Andric // where UpdateSSA will use it as a work list.
4676122f3e6SDimitry Andric LiveIn.reserve(WorkList.size());
468d88c1a5aSDimitry Andric for (unsigned BN : WorkList) {
469d88c1a5aSDimitry Andric MachineBasicBlock *MBB = MF->getBlockNumbered(BN);
4702cab237bSDimitry Andric if (!Undefs.empty() &&
471a580b014SDimitry Andric !isDefOnEntry(LR, Undefs, *MBB, DefOnEntry, UndefOnEntry))
472d88c1a5aSDimitry Andric continue;
473f785676fSDimitry Andric addLiveInBlock(LR, DomTree->getNode(MBB));
474ff0cc061SDimitry Andric if (MBB == &UseMBB)
475ff0cc061SDimitry Andric LiveIn.back().Kill = Use;
476139f7f9bSDimitry Andric }
4776122f3e6SDimitry Andric
478139f7f9bSDimitry Andric return false;
4796122f3e6SDimitry Andric }
4806122f3e6SDimitry Andric
4816122f3e6SDimitry Andric // This is essentially the same iterative algorithm that SSAUpdater uses,
4826122f3e6SDimitry Andric // except we already have a dominator tree, so we don't have to recompute it.
updateSSA()4837ae0e2c9SDimitry Andric void LiveRangeCalc::updateSSA() {
4846122f3e6SDimitry Andric assert(Indexes && "Missing SlotIndexes");
4856122f3e6SDimitry Andric assert(DomTree && "Missing dominator tree");
4866122f3e6SDimitry Andric
4876122f3e6SDimitry Andric // Interate until convergence.
488a580b014SDimitry Andric bool Changed;
4896122f3e6SDimitry Andric do {
490a580b014SDimitry Andric Changed = false;
4916122f3e6SDimitry Andric // Propagate live-out values down the dominator tree, inserting phi-defs
4926122f3e6SDimitry Andric // when necessary.
49339d628a0SDimitry Andric for (LiveInBlock &I : LiveIn) {
49439d628a0SDimitry Andric MachineDomTreeNode *Node = I.DomNode;
4956122f3e6SDimitry Andric // Skip block if the live-in value has already been determined.
4966122f3e6SDimitry Andric if (!Node)
4976122f3e6SDimitry Andric continue;
4986122f3e6SDimitry Andric MachineBasicBlock *MBB = Node->getBlock();
4996122f3e6SDimitry Andric MachineDomTreeNode *IDom = Node->getIDom();
5006122f3e6SDimitry Andric LiveOutPair IDomValue;
5016122f3e6SDimitry Andric
5026122f3e6SDimitry Andric // We need a live-in value to a block with no immediate dominator?
5036122f3e6SDimitry Andric // This is probably an unreachable block that has survived somehow.
5046122f3e6SDimitry Andric bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
5056122f3e6SDimitry Andric
5066122f3e6SDimitry Andric // IDom dominates all of our predecessors, but it may not be their
5076122f3e6SDimitry Andric // immediate dominator. Check if any of them have live-out values that are
5086122f3e6SDimitry Andric // properly dominated by IDom. If so, we need a phi-def here.
5096122f3e6SDimitry Andric if (!needPHI) {
51039d628a0SDimitry Andric IDomValue = Map[IDom->getBlock()];
5116122f3e6SDimitry Andric
5126122f3e6SDimitry Andric // Cache the DomTree node that defined the value.
513a580b014SDimitry Andric if (IDomValue.first && IDomValue.first != &UndefVNI &&
514a580b014SDimitry Andric !IDomValue.second) {
51539d628a0SDimitry Andric Map[IDom->getBlock()].second = IDomValue.second =
5166122f3e6SDimitry Andric DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
517a580b014SDimitry Andric }
5186122f3e6SDimitry Andric
519a580b014SDimitry Andric for (MachineBasicBlock *Pred : MBB->predecessors()) {
520a580b014SDimitry Andric LiveOutPair &Value = Map[Pred];
5216122f3e6SDimitry Andric if (!Value.first || Value.first == IDomValue.first)
5226122f3e6SDimitry Andric continue;
523a580b014SDimitry Andric if (Value.first == &UndefVNI) {
524a580b014SDimitry Andric needPHI = true;
525a580b014SDimitry Andric break;
526a580b014SDimitry Andric }
5276122f3e6SDimitry Andric
5286122f3e6SDimitry Andric // Cache the DomTree node that defined the value.
5296122f3e6SDimitry Andric if (!Value.second)
5306122f3e6SDimitry Andric Value.second =
5316122f3e6SDimitry Andric DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
5326122f3e6SDimitry Andric
5336122f3e6SDimitry Andric // This predecessor is carrying something other than IDomValue.
5346122f3e6SDimitry Andric // It could be because IDomValue hasn't propagated yet, or it could be
5356122f3e6SDimitry Andric // because MBB is in the dominance frontier of that value.
5366122f3e6SDimitry Andric if (DomTree->dominates(IDom, Value.second)) {
5376122f3e6SDimitry Andric needPHI = true;
5386122f3e6SDimitry Andric break;
5396122f3e6SDimitry Andric }
5406122f3e6SDimitry Andric }
5416122f3e6SDimitry Andric }
5426122f3e6SDimitry Andric
5436122f3e6SDimitry Andric // The value may be live-through even if Kill is set, as can happen when
5446122f3e6SDimitry Andric // we are called from extendRange. In that case LiveOutSeen is true, and
5456122f3e6SDimitry Andric // LiveOut indicates a foreign or missing value.
54639d628a0SDimitry Andric LiveOutPair &LOP = Map[MBB];
5476122f3e6SDimitry Andric
5486122f3e6SDimitry Andric // Create a phi-def if required.
5496122f3e6SDimitry Andric if (needPHI) {
550a580b014SDimitry Andric Changed = true;
5516122f3e6SDimitry Andric assert(Alloc && "Need VNInfo allocator to create PHI-defs");
5526122f3e6SDimitry Andric SlotIndex Start, End;
55391bc56edSDimitry Andric std::tie(Start, End) = Indexes->getMBBRange(MBB);
55439d628a0SDimitry Andric LiveRange &LR = I.LR;
555f785676fSDimitry Andric VNInfo *VNI = LR.getNextValue(Start, *Alloc);
55639d628a0SDimitry Andric I.Value = VNI;
5576122f3e6SDimitry Andric // This block is done, we know the final value.
55839d628a0SDimitry Andric I.DomNode = nullptr;
5596122f3e6SDimitry Andric
56039d628a0SDimitry Andric // Add liveness since updateFromLiveIns now skips this node.
561d88c1a5aSDimitry Andric if (I.Kill.isValid()) {
562d88c1a5aSDimitry Andric if (VNI)
56339d628a0SDimitry Andric LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
564d88c1a5aSDimitry Andric } else {
565d88c1a5aSDimitry Andric if (VNI)
566f785676fSDimitry Andric LR.addSegment(LiveInterval::Segment(Start, End, VNI));
5676122f3e6SDimitry Andric LOP = LiveOutPair(VNI, Node);
5686122f3e6SDimitry Andric }
569a580b014SDimitry Andric } else if (IDomValue.first && IDomValue.first != &UndefVNI) {
5706122f3e6SDimitry Andric // No phi-def here. Remember incoming value.
57139d628a0SDimitry Andric I.Value = IDomValue.first;
5726122f3e6SDimitry Andric
5736122f3e6SDimitry Andric // If the IDomValue is killed in the block, don't propagate through.
57439d628a0SDimitry Andric if (I.Kill.isValid())
5756122f3e6SDimitry Andric continue;
5766122f3e6SDimitry Andric
5776122f3e6SDimitry Andric // Propagate IDomValue if it isn't killed:
5786122f3e6SDimitry Andric // MBB is live-out and doesn't define its own value.
5796122f3e6SDimitry Andric if (LOP.first == IDomValue.first)
5806122f3e6SDimitry Andric continue;
581a580b014SDimitry Andric Changed = true;
5826122f3e6SDimitry Andric LOP = IDomValue;
5836122f3e6SDimitry Andric }
5846122f3e6SDimitry Andric }
585a580b014SDimitry Andric } while (Changed);
5866122f3e6SDimitry Andric }
5874ba319b5SDimitry Andric
isJointlyDominated(const MachineBasicBlock * MBB,ArrayRef<SlotIndex> Defs,const SlotIndexes & Indexes)5884ba319b5SDimitry Andric bool LiveRangeCalc::isJointlyDominated(const MachineBasicBlock *MBB,
5894ba319b5SDimitry Andric ArrayRef<SlotIndex> Defs,
5904ba319b5SDimitry Andric const SlotIndexes &Indexes) {
5914ba319b5SDimitry Andric const MachineFunction &MF = *MBB->getParent();
5924ba319b5SDimitry Andric BitVector DefBlocks(MF.getNumBlockIDs());
5934ba319b5SDimitry Andric for (SlotIndex I : Defs)
5944ba319b5SDimitry Andric DefBlocks.set(Indexes.getMBBFromIndex(I)->getNumber());
5954ba319b5SDimitry Andric
5964ba319b5SDimitry Andric SetVector<unsigned> PredQueue;
5974ba319b5SDimitry Andric PredQueue.insert(MBB->getNumber());
5984ba319b5SDimitry Andric for (unsigned i = 0; i != PredQueue.size(); ++i) {
5994ba319b5SDimitry Andric unsigned BN = PredQueue[i];
6004ba319b5SDimitry Andric if (DefBlocks[BN])
6014ba319b5SDimitry Andric return true;
6024ba319b5SDimitry Andric const MachineBasicBlock *B = MF.getBlockNumbered(BN);
6034ba319b5SDimitry Andric for (const MachineBasicBlock *P : B->predecessors())
6044ba319b5SDimitry Andric PredQueue.insert(P->getNumber());
6054ba319b5SDimitry Andric }
6064ba319b5SDimitry Andric return false;
6074ba319b5SDimitry Andric }
608