blob: 01779b1eb9b015e59a73abd61d2f1b98006ff68e [file] [log] [blame]
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +00001//===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveDebugVariables analysis.
11//
12// Remove all DBG_VALUE instructions referencing virtual registers and replace
13// them with a data structure tracking where live user variables are kept - in a
14// virtual register or in a stack slot.
15//
16// Allow the data structure to be updated during register allocation when values
17// are moved between registers and stack slots. Finally emit new DBG_VALUE
18// instructions after register allocation is complete.
19//
20//===----------------------------------------------------------------------===//
21
22#include "LiveDebugVariables.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000023#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/DenseMap.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000025#include "llvm/ADT/IntervalMap.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000026#include "llvm/ADT/STLExtras.h"
Robert Lougher10f740d2017-08-03 11:54:02 +000027#include "llvm/ADT/SmallSet.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000028#include "llvm/ADT/SmallVector.h"
Devang Patelb4568662011-08-04 18:45:38 +000029#include "llvm/ADT/Statistic.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000030#include "llvm/ADT/StringRef.h"
Robert Lougher10f740d2017-08-03 11:54:02 +000031#include "llvm/CodeGen/LexicalScopes.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000032#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunf8422972017-12-13 02:51:04 +000033#include "llvm/CodeGen/LiveIntervals.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000034#include "llvm/CodeGen/MachineBasicBlock.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000035#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +000036#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000037#include "llvm/CodeGen/MachineInstr.h"
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +000038#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000039#include "llvm/CodeGen/MachineOperand.h"
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +000040#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000041#include "llvm/CodeGen/SlotIndexes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000042#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000043#include "llvm/CodeGen/TargetOpcodes.h"
44#include "llvm/CodeGen/TargetRegisterInfo.h"
45#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000046#include "llvm/CodeGen/VirtRegMap.h"
Nico Weber432a3882018-04-30 14:59:11 +000047#include "llvm/Config/llvm-config.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000048#include "llvm/IR/DebugInfoMetadata.h"
49#include "llvm/IR/DebugLoc.h"
50#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Metadata.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000052#include "llvm/MC/MCRegisterInfo.h"
53#include "llvm/Pass.h"
54#include "llvm/Support/Casting.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000055#include "llvm/Support/CommandLine.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000056#include "llvm/Support/Compiler.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000057#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000058#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000059#include <algorithm>
60#include <cassert>
61#include <iterator>
David Blaikie2b1dfa72014-04-21 20:37:07 +000062#include <memory>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000063#include <utility>
David Blaikie2b1dfa72014-04-21 20:37:07 +000064
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000065using namespace llvm;
66
Matthias Braun1527baa2017-05-25 21:26:32 +000067#define DEBUG_TYPE "livedebugvars"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000068
Devang Patelacbee0b2011-01-07 22:33:41 +000069static cl::opt<bool>
Jakob Stoklund Olesen74ded572011-01-12 23:36:21 +000070EnableLDV("live-debug-variables", cl::init(true),
Devang Patelacbee0b2011-01-07 22:33:41 +000071 cl::desc("Enable the live debug variables pass"), cl::Hidden);
72
Devang Patelb4568662011-08-04 18:45:38 +000073STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
Eugene Zelenko5df3d892017-08-24 21:21:39 +000074
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000075char LiveDebugVariables::ID = 0;
76
Matthias Braun1527baa2017-05-25 21:26:32 +000077INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000078 "Debug Variable Analysis", false, false)
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000079INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000080INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun1527baa2017-05-25 21:26:32 +000081INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000082 "Debug Variable Analysis", false, false)
83
84void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000085 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000086 AU.addRequiredTransitive<LiveIntervals>();
87 AU.setPreservesAll();
88 MachineFunctionPass::getAnalysisUsage(AU);
89}
90
Eugene Zelenko5df3d892017-08-24 21:21:39 +000091LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000092 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
93}
94
Reid Kleckner04e25e02017-10-03 17:59:02 +000095enum : unsigned { UndefLocNo = ~0U };
96
97/// Describes a location by number along with some flags about the original
98/// usage of the location.
99class DbgValueLocation {
100public:
101 DbgValueLocation(unsigned LocNo, bool WasIndirect)
102 : LocNo(LocNo), WasIndirect(WasIndirect) {
103 static_assert(sizeof(*this) == sizeof(unsigned), "bad bitfield packing");
104 assert(locNo() == LocNo && "location truncation");
105 }
106
107 DbgValueLocation() : LocNo(0), WasIndirect(0) {}
108
109 unsigned locNo() const {
110 // Fix up the undef location number, which gets truncated.
111 return LocNo == INT_MAX ? UndefLocNo : LocNo;
112 }
113 bool wasIndirect() const { return WasIndirect; }
114 bool isUndef() const { return locNo() == UndefLocNo; }
115
116 DbgValueLocation changeLocNo(unsigned NewLocNo) const {
117 return DbgValueLocation(NewLocNo, WasIndirect);
118 }
119
Reid Klecknerb4569de72017-10-03 18:30:11 +0000120 friend inline bool operator==(const DbgValueLocation &LHS,
121 const DbgValueLocation &RHS) {
122 return LHS.LocNo == RHS.LocNo && LHS.WasIndirect == RHS.WasIndirect;
Reid Kleckner04e25e02017-10-03 17:59:02 +0000123 }
Reid Klecknerb4569de72017-10-03 18:30:11 +0000124
125 friend inline bool operator!=(const DbgValueLocation &LHS,
126 const DbgValueLocation &RHS) {
127 return !(LHS == RHS);
128 }
Reid Kleckner04e25e02017-10-03 17:59:02 +0000129
130private:
131 unsigned LocNo : 31;
132 unsigned WasIndirect : 1;
133};
134
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000135/// LocMap - Map of where a user value is live, and its location.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000136using LocMap = IntervalMap<SlotIndex, DbgValueLocation, 4>;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000137
David Stenberg45acc962018-09-07 13:54:07 +0000138/// SpillOffsetMap - Map of stack slot offsets for spilled locations.
139/// Non-spilled locations are not added to the map.
140using SpillOffsetMap = DenseMap<unsigned, unsigned>;
141
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000142namespace {
143
144class LDVImpl;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000145
146/// UserValue - A user value is a part of a debug info user variable.
147///
148/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
149/// holds part of a user variable. The part is identified by a byte offset.
150///
151/// UserValues are grouped into equivalence classes for easier searching. Two
152/// user values are related if they refer to the same variable, or if they are
153/// held by the same virtual register. The equivalence class is the transitive
154/// closure of that relation.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000155class UserValue {
Reid Kleckner4e040282017-09-20 18:19:08 +0000156 const DILocalVariable *Variable; ///< The debug info variable we are part of.
157 const DIExpression *Expression; ///< Any complex address expression.
Devang Patel26ffa012011-02-04 01:43:25 +0000158 DebugLoc dl; ///< The debug location for the variable. This is
159 ///< used by dwarf writer to find lexical scope.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000160 UserValue *leader; ///< Equivalence class leader.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000161 UserValue *next = nullptr; ///< Next value in equivalence class, or null.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000162
163 /// Numbered locations referenced by locmap.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000164 SmallVector<MachineOperand, 4> locations;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000165
166 /// Map of slot indices where this value is live.
167 LocMap locInts;
168
Robert Lougher10f740d2017-08-03 11:54:02 +0000169 /// Set of interval start indexes that have been trimmed to the
170 /// lexical scope.
171 SmallSet<SlotIndex, 2> trimmedDefs;
172
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000173 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +0000174 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
David Stenberg45acc962018-09-07 13:54:07 +0000175 SlotIndex StopIdx, DbgValueLocation Loc, bool Spilled,
176 unsigned SpillOffset, LiveIntervals &LIS,
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +0000177 const TargetInstrInfo &TII,
178 const TargetRegisterInfo &TRI);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000179
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000180 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
181 /// is live. Returns true if any changes were made.
Mark Laceyf9ea8852013-08-14 23:50:04 +0000182 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
183 LiveIntervals &LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000184
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000185public:
186 /// UserValue - Create a new UserValue.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000187 UserValue(const DILocalVariable *var, const DIExpression *expr, DebugLoc L,
188 LocMap::Allocator &alloc)
189 : Variable(var), Expression(expr), dl(std::move(L)), leader(this),
190 locInts(alloc) {}
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000191
192 /// getLeader - Get the leader of this value's equivalence class.
193 UserValue *getLeader() {
194 UserValue *l = leader;
195 while (l != l->leader)
196 l = l->leader;
197 return leader = l;
198 }
199
200 /// getNext - Return the next UserValue in the equivalence class.
201 UserValue *getNext() const { return next; }
202
Devang Patel338e4322011-07-06 23:09:51 +0000203 /// match - Does this UserValue match the parameters?
Reid Kleckner4e040282017-09-20 18:19:08 +0000204 bool match(const DILocalVariable *Var, const DIExpression *Expr,
Reid Kleckner04e25e02017-10-03 17:59:02 +0000205 const DILocation *IA) const {
206 // FIXME: The fragment should be part of the equivalence class, but not
207 // other things in the expression like stack values.
208 return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000209 }
210
211 /// merge - Merge equivalence classes.
212 static UserValue *merge(UserValue *L1, UserValue *L2) {
213 L2 = L2->getLeader();
214 if (!L1)
215 return L2;
216 L1 = L1->getLeader();
217 if (L1 == L2)
218 return L1;
219 // Splice L2 before L1's members.
220 UserValue *End = L2;
Richard Trieu7a083812016-02-18 22:09:30 +0000221 while (End->next) {
222 End->leader = L1;
223 End = End->next;
224 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000225 End->leader = L1;
226 End->next = L1->next;
227 L1->next = L2;
228 return L1;
229 }
230
Mikael Holmen57b33f62018-06-21 07:02:46 +0000231 /// Return the location number that matches Loc.
232 ///
233 /// For undef values we always return location number UndefLocNo without
234 /// inserting anything in locations. Since locations is a vector and the
235 /// location number is the position in the vector and UndefLocNo is ~0,
236 /// we would need a very big vector to put the value at the right position.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000237 unsigned getLocationNo(const MachineOperand &LocMO) {
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000238 if (LocMO.isReg()) {
239 if (LocMO.getReg() == 0)
Reid Klecknereed09732017-09-15 22:08:50 +0000240 return UndefLocNo;
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000241 // For register locations we dont care about use/def and other flags.
242 for (unsigned i = 0, e = locations.size(); i != e; ++i)
243 if (locations[i].isReg() &&
244 locations[i].getReg() == LocMO.getReg() &&
245 locations[i].getSubReg() == LocMO.getSubReg())
246 return i;
247 } else
248 for (unsigned i = 0, e = locations.size(); i != e; ++i)
249 if (LocMO.isIdenticalTo(locations[i]))
250 return i;
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000251 locations.push_back(LocMO);
252 // We are storing a MachineOperand outside a MachineInstr.
253 locations.back().clearParent();
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000254 // Don't store def operands.
Geoff Berryb3d126d2017-12-29 21:01:09 +0000255 if (locations.back().isReg()) {
256 if (locations.back().isDef())
257 locations.back().setIsDead(false);
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000258 locations.back().setIsUse();
Geoff Berryb3d126d2017-12-29 21:01:09 +0000259 }
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000260 return locations.size() - 1;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000261 }
262
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000263 /// mapVirtRegs - Ensure that all virtual register locations are mapped.
264 void mapVirtRegs(LDVImpl *LDV);
265
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000266 /// addDef - Add a definition point to this value.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000267 void addDef(SlotIndex Idx, const MachineOperand &LocMO, bool IsIndirect) {
268 DbgValueLocation Loc(getLocationNo(LocMO), IsIndirect);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000269 // Add a singular (Idx,Idx) -> Loc mapping.
270 LocMap::iterator I = locInts.find(Idx);
271 if (!I.valid() || I.start() != Idx)
Reid Kleckner04e25e02017-10-03 17:59:02 +0000272 I.insert(Idx, Idx.getNextSlot(), Loc);
Jakob Stoklund Olesen2539af62011-08-03 23:44:31 +0000273 else
274 // A later DBG_VALUE at the same SlotIndex overrides the old location.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000275 I.setValue(Loc);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000276 }
277
Adrian Prantlf8d10ce2016-09-28 21:34:23 +0000278 /// extendDef - Extend the current definition as far as possible down.
279 /// Stop when meeting an existing def or when leaving the live
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000280 /// range of VNI.
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000281 /// End points where VNI is no longer live are added to Kills.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000282 /// @param Idx Starting point for the definition.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000283 /// @param Loc Location number to propagate.
Matthias Braun34e1be92013-10-10 21:29:02 +0000284 /// @param LR Restrict liveness to where LR has the value VNI. May be null.
285 /// @param VNI When LR is not null, this is the value to restrict to.
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000286 /// @param Kills Append end points of VNI's live range to Kills.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000287 /// @param LIS Live intervals analysis.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000288 void extendDef(SlotIndex Idx, DbgValueLocation Loc,
Matthias Braun34e1be92013-10-10 21:29:02 +0000289 LiveRange *LR, const VNInfo *VNI,
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000290 SmallVectorImpl<SlotIndex> *Kills,
Adrian Prantlf8d10ce2016-09-28 21:34:23 +0000291 LiveIntervals &LIS);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000292
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000293 /// addDefsFromCopies - The value in LI/LocNo may be copies to other
294 /// registers. Determine if any of the copies are available at the kill
295 /// points, and add defs if possible.
296 /// @param LI Scan for copies of the value in LI->reg.
297 /// @param LocNo Location number of LI->reg.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000298 /// @param WasIndirect Indicates if the original use of LI->reg was indirect
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000299 /// @param Kills Points where the range of LocNo could be extended.
300 /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000301 void addDefsFromCopies(
302 LiveInterval *LI, unsigned LocNo, bool WasIndirect,
303 const SmallVectorImpl<SlotIndex> &Kills,
304 SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
305 MachineRegisterInfo &MRI, LiveIntervals &LIS);
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000306
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000307 /// computeIntervals - Compute the live intervals of all locations after
308 /// collecting all their def points.
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000309 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
Robert Lougher10f740d2017-08-03 11:54:02 +0000310 LiveIntervals &LIS, LexicalScopes &LS);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000311
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000312 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
313 /// live. Returns true if any changes were made.
Fangrui Songcb0bab82018-07-16 18:51:40 +0000314 bool splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000315 LiveIntervals &LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000316
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000317 /// rewriteLocations - Rewrite virtual register locations according to the
David Stenberg45acc962018-09-07 13:54:07 +0000318 /// provided virtual register map. Record the stack slot offsets for the
319 /// locations that were spilled.
320 void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
321 const TargetInstrInfo &TII,
322 const TargetRegisterInfo &TRI,
323 SpillOffsetMap &SpillOffsets);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000324
Eric Christopherbc671702013-02-13 02:29:18 +0000325 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
Reid Kleckner4e040282017-09-20 18:19:08 +0000326 void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +0000327 const TargetInstrInfo &TII,
328 const TargetRegisterInfo &TRI,
David Stenberg45acc962018-09-07 13:54:07 +0000329 const SpillOffsetMap &SpillOffsets);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000330
Devang Patelf9e2ae92011-09-13 18:40:53 +0000331 /// getDebugLoc - Return DebugLoc of this UserValue.
332 DebugLoc getDebugLoc() { return dl;}
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000333
Eric Christopher1cdefae2015-02-27 00:11:34 +0000334 void print(raw_ostream &, const TargetRegisterInfo *);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000335};
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000336
337/// LDVImpl - Implementation of the LiveDebugVariables pass.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000338class LDVImpl {
339 LiveDebugVariables &pass;
340 LocMap::Allocator allocator;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000341 MachineFunction *MF = nullptr;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000342 LiveIntervals *LIS;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000343 const TargetRegisterInfo *TRI;
344
Manman Ren7a4c8a72013-02-13 20:23:48 +0000345 /// Whether emitDebugValues is called.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000346 bool EmitDone = false;
347
Manman Ren7a4c8a72013-02-13 20:23:48 +0000348 /// Whether the machine function is modified during the pass.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000349 bool ModifiedMF = false;
Manman Ren7a4c8a72013-02-13 20:23:48 +0000350
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000351 /// userValues - All allocated UserValue instances.
David Blaikie2b1dfa72014-04-21 20:37:07 +0000352 SmallVector<std::unique_ptr<UserValue>, 8> userValues;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000353
354 /// Map virtual register to eq class leader.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000355 using VRMap = DenseMap<unsigned, UserValue *>;
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000356 VRMap virtRegToEqClass;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000357
358 /// Map user variable to eq class leader.
Reid Kleckner4e040282017-09-20 18:19:08 +0000359 using UVMap = DenseMap<const DILocalVariable *, UserValue *>;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000360 UVMap userVarMap;
361
362 /// getUserValue - Find or create a UserValue.
Reid Kleckner4e040282017-09-20 18:19:08 +0000363 UserValue *getUserValue(const DILocalVariable *Var, const DIExpression *Expr,
Reid Kleckner04e25e02017-10-03 17:59:02 +0000364 const DebugLoc &DL);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000365
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000366 /// lookupVirtReg - Find the EC leader for VirtReg or null.
367 UserValue *lookupVirtReg(unsigned VirtReg);
368
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000369 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
370 /// @param MI DBG_VALUE instruction
371 /// @param Idx Last valid SLotIndex before instruction.
372 /// @return True if the DBG_VALUE instruction should be deleted.
Duncan P. N. Exon Smithfb612ac2016-06-30 23:13:38 +0000373 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000374
375 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
376 /// a UserValue def for each instruction.
377 /// @param mf MachineFunction to be scanned.
378 /// @return True if any debug values were found.
379 bool collectDebugValues(MachineFunction &mf);
380
381 /// computeIntervals - Compute the live intervals of all user values after
382 /// collecting all their def points.
383 void computeIntervals();
384
385public:
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000386 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
387
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000388 bool runOnMachineFunction(MachineFunction &mf);
389
Manman Ren7a4c8a72013-02-13 20:23:48 +0000390 /// clear - Release all memory.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000391 void clear() {
David Blaikie2f040112014-07-25 16:10:16 +0000392 MF = nullptr;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000393 userValues.clear();
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000394 virtRegToEqClass.clear();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000395 userVarMap.clear();
Manman Ren7a4c8a72013-02-13 20:23:48 +0000396 // Make sure we call emitDebugValues if the machine function was modified.
397 assert((!ModifiedMF || EmitDone) &&
398 "Dbg values are not emitted in LDV");
399 EmitDone = false;
400 ModifiedMF = false;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000401 }
402
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000403 /// mapVirtReg - Map virtual register to an equivalence class.
404 void mapVirtReg(unsigned VirtReg, UserValue *EC);
405
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000406 /// splitRegister - Replace all references to OldReg with NewRegs.
Mark Laceyf9ea8852013-08-14 23:50:04 +0000407 void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000408
Eric Christopherbc671702013-02-13 02:29:18 +0000409 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000410 void emitDebugValues(VirtRegMap *VRM);
411
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000412 void print(raw_ostream&);
413};
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000414
415} // end anonymous namespace
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000416
Aaron Ballman615eb472017-10-15 14:32:27 +0000417#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000418static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000419 const LLVMContext &Ctx) {
420 if (!DL)
421 return;
422
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000423 auto *Scope = cast<DIScope>(DL.getScope());
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000424 // Omit the directory, because it's likely to be long and uninteresting.
Duncan P. N. Exon Smithb273d062015-04-16 01:37:00 +0000425 CommentOS << Scope->getFilename();
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000426 CommentOS << ':' << DL.getLine();
427 if (DL.getCol() != 0)
428 CommentOS << ':' << DL.getCol();
429
430 DebugLoc InlinedAtDL = DL.getInlinedAt();
431 if (!InlinedAtDL)
432 return;
433
434 CommentOS << " @[ ";
435 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
436 CommentOS << " ]";
437}
438
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000439static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
440 const DILocation *DL) {
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000441 const LLVMContext &Ctx = V->getContext();
442 StringRef Res = V->getName();
443 if (!Res.empty())
444 OS << Res << "," << V->getLine();
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +0000445 if (auto *InlinedAt = DL->getInlinedAt()) {
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000446 if (DebugLoc InlinedAtDL = InlinedAt) {
447 OS << " @[";
448 printDebugLoc(InlinedAtDL, OS, Ctx);
449 OS << "]";
450 }
451 }
452}
453
Eric Christopher1cdefae2015-02-27 00:11:34 +0000454void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000455 auto *DV = cast<DILocalVariable>(Variable);
Frederic Risse6bb1872014-08-07 20:04:00 +0000456 OS << "!\"";
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +0000457 printExtendedName(OS, DV, dl);
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000458
Devang Patel6c1ed312011-08-09 01:03:35 +0000459 OS << "\"\t";
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000460 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
461 OS << " [" << I.start() << ';' << I.stop() << "):";
Reid Kleckner04e25e02017-10-03 17:59:02 +0000462 if (I.value().isUndef())
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000463 OS << "undef";
Reid Kleckner04e25e02017-10-03 17:59:02 +0000464 else {
465 OS << I.value().locNo();
466 if (I.value().wasIndirect())
467 OS << " ind";
468 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000469 }
Jakob Stoklund Olesenc86fe052011-05-06 17:59:59 +0000470 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
471 OS << " Loc" << i << '=';
Eric Christopher1cdefae2015-02-27 00:11:34 +0000472 locations[i].print(OS, TRI);
Jakob Stoklund Olesenc86fe052011-05-06 17:59:59 +0000473 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000474 OS << '\n';
475}
476
477void LDVImpl::print(raw_ostream &OS) {
478 OS << "********** DEBUG VARIABLES **********\n";
479 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
Eric Christopher1cdefae2015-02-27 00:11:34 +0000480 userValues[i]->print(OS, TRI);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000481}
Florian Hahn6b3216a2017-07-31 10:07:49 +0000482#endif
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000483
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000484void UserValue::mapVirtRegs(LDVImpl *LDV) {
485 for (unsigned i = 0, e = locations.size(); i != e; ++i)
486 if (locations[i].isReg() &&
487 TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
488 LDV->mapVirtReg(locations[i].getReg(), this);
489}
490
Reid Kleckner4e040282017-09-20 18:19:08 +0000491UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
Reid Kleckner04e25e02017-10-03 17:59:02 +0000492 const DIExpression *Expr, const DebugLoc &DL) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000493 UserValue *&Leader = userVarMap[Var];
494 if (Leader) {
495 UserValue *UV = Leader->getLeader();
496 Leader = UV;
497 for (; UV; UV = UV->getNext())
Reid Kleckner04e25e02017-10-03 17:59:02 +0000498 if (UV->match(Var, Expr, DL->getInlinedAt()))
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000499 return UV;
500 }
501
David Blaikie2b1dfa72014-04-21 20:37:07 +0000502 userValues.push_back(
Reid Kleckner04e25e02017-10-03 17:59:02 +0000503 llvm::make_unique<UserValue>(Var, Expr, DL, allocator));
David Blaikie2b1dfa72014-04-21 20:37:07 +0000504 UserValue *UV = userValues.back().get();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000505 Leader = UserValue::merge(Leader, UV);
506 return UV;
507}
508
509void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
510 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000511 UserValue *&Leader = virtRegToEqClass[VirtReg];
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000512 Leader = UserValue::merge(Leader, EC);
513}
514
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000515UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000516 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000517 return UV->getLeader();
Craig Topperc0196b12014-04-14 00:51:57 +0000518 return nullptr;
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000519}
520
Duncan P. N. Exon Smithfb612ac2016-06-30 23:13:38 +0000521bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000522 // DBG_VALUE loc, offset, variable
Duncan P. N. Exon Smithfb612ac2016-06-30 23:13:38 +0000523 if (MI.getNumOperands() != 4 ||
524 !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
525 !MI.getOperand(2).isMetadata()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000526 LLVM_DEBUG(dbgs() << "Can't handle " << MI);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000527 return false;
528 }
529
Bjorn Petterssonbdf0c002018-03-06 08:47:07 +0000530 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
531 // register that hasn't been defined yet. If we do not remove those here, then
532 // the re-insertion of the DBG_VALUE instruction after register allocation
533 // will be incorrect.
534 // TODO: If earlier passes are corrected to generate sane debug information
535 // (and if the machine verifier is improved to catch this), then these checks
536 // could be removed or replaced by asserts.
537 bool Discard = false;
538 if (MI.getOperand(0).isReg() &&
539 TargetRegisterInfo::isVirtualRegister(MI.getOperand(0).getReg())) {
540 const unsigned Reg = MI.getOperand(0).getReg();
541 if (!LIS->hasInterval(Reg)) {
542 // The DBG_VALUE is described by a virtual register that does not have a
543 // live interval. Discard the DBG_VALUE.
544 Discard = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000545 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
546 << " " << MI);
Bjorn Petterssonbdf0c002018-03-06 08:47:07 +0000547 } else {
548 // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg
549 // is defined dead at Idx (where Idx is the slot index for the instruction
550 // preceeding the DBG_VALUE).
551 const LiveInterval &LI = LIS->getInterval(Reg);
552 LiveQueryResult LRQ = LI.Query(Idx);
553 if (!LRQ.valueOutOrDead()) {
554 // We have found a DBG_VALUE with the value in a virtual register that
555 // is not live. Discard the DBG_VALUE.
556 Discard = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000557 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
558 << " " << MI);
Bjorn Petterssonbdf0c002018-03-06 08:47:07 +0000559 }
560 }
561 }
562
Reid Kleckner04e25e02017-10-03 17:59:02 +0000563 // Get or create the UserValue for (variable,offset) here.
Reid Kleckner4e040282017-09-20 18:19:08 +0000564 bool IsIndirect = MI.getOperand(1).isImm();
Adrian Prantlb2811e52017-07-28 23:06:50 +0000565 if (IsIndirect)
566 assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
Reid Kleckner4e040282017-09-20 18:19:08 +0000567 const DILocalVariable *Var = MI.getDebugVariable();
568 const DIExpression *Expr = MI.getDebugExpression();
Reid Kleckner04e25e02017-10-03 17:59:02 +0000569 UserValue *UV =
570 getUserValue(Var, Expr, MI.getDebugLoc());
Bjorn Petterssonbdf0c002018-03-06 08:47:07 +0000571 if (!Discard)
572 UV->addDef(Idx, MI.getOperand(0), IsIndirect);
Bjorn Petterssone0050d72018-03-06 13:23:28 +0000573 else {
574 MachineOperand MO = MachineOperand::CreateReg(0U, false);
575 MO.setIsDebug();
576 UV->addDef(Idx, MO, false);
577 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000578 return true;
579}
580
581bool LDVImpl::collectDebugValues(MachineFunction &mf) {
582 bool Changed = false;
583 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
584 ++MFI) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000585 MachineBasicBlock *MBB = &*MFI;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000586 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
587 MBBI != MBBE;) {
Hsiangkai Wangb2b7f5f2018-09-05 05:58:53 +0000588 // Use the first debug instruction in the sequence to get a SlotIndex
589 // for following consecutive debug instructions.
590 if (!MBBI->isDebugInstr()) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000591 ++MBBI;
592 continue;
593 }
Hsiangkai Wangb2b7f5f2018-09-05 05:58:53 +0000594 // Debug instructions has no slot index. Use the previous
595 // non-debug instruction's SlotIndex as its SlotIndex.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000596 SlotIndex Idx =
597 MBBI == MBB->begin()
598 ? LIS->getMBBStartIdx(MBB)
599 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
Hsiangkai Wangb2b7f5f2018-09-05 05:58:53 +0000600 // Handle consecutive debug instructions with the same slot index.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000601 do {
Hsiangkai Wangb2b7f5f2018-09-05 05:58:53 +0000602 // Only handle DBG_VALUE in handleDebugValue(). Skip all other
603 // kinds of debug instructions.
604 if (MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000605 MBBI = MBB->erase(MBBI);
606 Changed = true;
607 } else
608 ++MBBI;
Hsiangkai Wangb2b7f5f2018-09-05 05:58:53 +0000609 } while (MBBI != MBBE && MBBI->isDebugInstr());
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000610 }
611 }
612 return Changed;
613}
614
Adrian Prantlce858132015-12-21 20:03:00 +0000615/// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
616/// data-flow analysis to propagate them beyond basic block boundaries.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000617void UserValue::extendDef(SlotIndex Idx, DbgValueLocation Loc, LiveRange *LR,
Adrian Prantlce858132015-12-21 20:03:00 +0000618 const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
Adrian Prantlf8d10ce2016-09-28 21:34:23 +0000619 LiveIntervals &LIS) {
Adrian Prantlce858132015-12-21 20:03:00 +0000620 SlotIndex Start = Idx;
621 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
622 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
623 LocMap::iterator I = locInts.find(Start);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000624
Adrian Prantlce858132015-12-21 20:03:00 +0000625 // Limit to VNI's live range.
626 bool ToEnd = true;
627 if (LR && VNI) {
628 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
629 if (!Segment || Segment->valno != VNI) {
630 if (Kills)
631 Kills->push_back(Start);
632 return;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000633 }
Richard Trieu7a083812016-02-18 22:09:30 +0000634 if (Segment->end < Stop) {
635 Stop = Segment->end;
636 ToEnd = false;
637 }
Adrian Prantlce858132015-12-21 20:03:00 +0000638 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000639
Adrian Prantlce858132015-12-21 20:03:00 +0000640 // There could already be a short def at Start.
641 if (I.valid() && I.start() <= Start) {
642 // Stop when meeting a different location or an already extended interval.
643 Start = Start.getNextSlot();
Reid Kleckner04e25e02017-10-03 17:59:02 +0000644 if (I.value() != Loc || I.stop() != Start)
Adrian Prantlce858132015-12-21 20:03:00 +0000645 return;
646 // This is a one-slot placeholder. Just skip it.
647 ++I;
648 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000649
Adrian Prantlce858132015-12-21 20:03:00 +0000650 // Limited by the next def.
Richard Trieu7a083812016-02-18 22:09:30 +0000651 if (I.valid() && I.start() < Stop) {
652 Stop = I.start();
653 ToEnd = false;
654 }
Adrian Prantlce858132015-12-21 20:03:00 +0000655 // Limited by VNI's live range.
656 else if (!ToEnd && Kills)
657 Kills->push_back(Stop);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000658
Adrian Prantlce858132015-12-21 20:03:00 +0000659 if (Start < Stop)
Reid Kleckner04e25e02017-10-03 17:59:02 +0000660 I.insert(Start, Stop, Loc);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000661}
662
Reid Kleckner04e25e02017-10-03 17:59:02 +0000663void UserValue::addDefsFromCopies(
664 LiveInterval *LI, unsigned LocNo, bool WasIndirect,
665 const SmallVectorImpl<SlotIndex> &Kills,
666 SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
667 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000668 if (Kills.empty())
669 return;
670 // Don't track copies from physregs, there are too many uses.
671 if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
672 return;
673
674 // Collect all the (vreg, valno) pairs that are copies of LI.
675 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
Owen Andersonb36376e2014-03-17 19:36:09 +0000676 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
677 MachineInstr *MI = MO.getParent();
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000678 // Copies of the full value.
Owen Andersonb36376e2014-03-17 19:36:09 +0000679 if (MO.getSubReg() || !MI->isCopy())
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000680 continue;
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000681 unsigned DstReg = MI->getOperand(0).getReg();
682
Jakob Stoklund Olesenec0ac3c2011-03-22 22:33:08 +0000683 // Don't follow copies to physregs. These are usually setting up call
684 // arguments, and the argument registers are always call clobbered. We are
685 // better off in the source register which could be a callee-saved register,
686 // or it could be spilled.
687 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
688 continue;
689
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000690 // Is LocNo extended to reach this copy? If not, another def may be blocking
691 // it, or we are looking at a wrong value of LI.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000692 SlotIndex Idx = LIS.getInstructionIndex(*MI);
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000693 LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
Reid Kleckner04e25e02017-10-03 17:59:02 +0000694 if (!I.valid() || I.value().locNo() != LocNo)
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000695 continue;
696
697 if (!LIS.hasInterval(DstReg))
698 continue;
699 LiveInterval *DstLI = &LIS.getInterval(DstReg);
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000700 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
701 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000702 CopyValues.push_back(std::make_pair(DstLI, DstVNI));
703 }
704
705 if (CopyValues.empty())
706 return;
707
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000708 LLVM_DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI
709 << '\n');
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000710
711 // Try to add defs of the copied values for each kill point.
712 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
713 SlotIndex Idx = Kills[i];
714 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
715 LiveInterval *DstLI = CopyValues[j].first;
716 const VNInfo *DstVNI = CopyValues[j].second;
717 if (DstLI->getVNInfoAt(Idx) != DstVNI)
718 continue;
719 // Check that there isn't already a def at Idx
720 LocMap::iterator I = locInts.find(Idx);
721 if (I.valid() && I.start() <= Idx)
722 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000723 LLVM_DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
724 << DstVNI->id << " in " << *DstLI << '\n');
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000725 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
726 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
727 unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
Reid Kleckner04e25e02017-10-03 17:59:02 +0000728 DbgValueLocation NewLoc(LocNo, WasIndirect);
729 I.insert(Idx, Idx.getNextSlot(), NewLoc);
730 NewDefs.push_back(std::make_pair(Idx, NewLoc));
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000731 break;
732 }
733 }
734}
735
Robert Lougher10f740d2017-08-03 11:54:02 +0000736void UserValue::computeIntervals(MachineRegisterInfo &MRI,
737 const TargetRegisterInfo &TRI,
738 LiveIntervals &LIS, LexicalScopes &LS) {
Reid Kleckner04e25e02017-10-03 17:59:02 +0000739 SmallVector<std::pair<SlotIndex, DbgValueLocation>, 16> Defs;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000740
741 // Collect all defs to be extended (Skipping undefs).
742 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
Reid Kleckner04e25e02017-10-03 17:59:02 +0000743 if (!I.value().isUndef())
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000744 Defs.push_back(std::make_pair(I.start(), I.value()));
745
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000746 // Extend all defs, and possibly add new ones along the way.
747 for (unsigned i = 0; i != Defs.size(); ++i) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000748 SlotIndex Idx = Defs[i].first;
Reid Kleckner04e25e02017-10-03 17:59:02 +0000749 DbgValueLocation Loc = Defs[i].second;
750 const MachineOperand &LocMO = locations[Loc.locNo()];
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000751
Reid Kleckner04e25e02017-10-03 17:59:02 +0000752 if (!LocMO.isReg()) {
753 extendDef(Idx, Loc, nullptr, nullptr, nullptr, LIS);
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000754 continue;
755 }
756
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000757 // Register locations are constrained to where the register value is live.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000758 if (TargetRegisterInfo::isVirtualRegister(LocMO.getReg())) {
Craig Topperc0196b12014-04-14 00:51:57 +0000759 LiveInterval *LI = nullptr;
760 const VNInfo *VNI = nullptr;
Reid Kleckner04e25e02017-10-03 17:59:02 +0000761 if (LIS.hasInterval(LocMO.getReg())) {
762 LI = &LIS.getInterval(LocMO.getReg());
Jakob Stoklund Olesen48a16472012-06-22 18:51:35 +0000763 VNI = LI->getVNInfoAt(Idx);
764 }
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000765 SmallVector<SlotIndex, 16> Kills;
Reid Kleckner04e25e02017-10-03 17:59:02 +0000766 extendDef(Idx, Loc, LI, VNI, &Kills, LIS);
Bjorn Pettersson84830042018-08-25 10:02:03 +0000767 // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
768 // if the original location for example is %vreg0:sub_hi, and we find a
769 // full register copy in addDefsFromCopies (at the moment it only handles
770 // full register copies), then we must add the sub1 sub-register index to
771 // the new location. However, that is only possible if the new virtual
772 // register is of the same regclass (or if there is an equivalent
773 // sub-register in that regclass). For now, simply skip handling copies if
774 // a sub-register is involved.
775 if (LI && !LocMO.getSubReg())
Reid Kleckner04e25e02017-10-03 17:59:02 +0000776 addDefsFromCopies(LI, Loc.locNo(), Loc.wasIndirect(), Kills, Defs, MRI,
777 LIS);
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000778 continue;
779 }
780
Bjorn Pettersson715a5ef2017-09-28 13:10:06 +0000781 // For physregs, we only mark the start slot idx. DwarfDebug will see it
782 // as if the DBG_VALUE is valid up until the end of the basic block, or
783 // the next def of the physical register. So we do not need to extend the
784 // range. It might actually happen that the DBG_VALUE is the last use of
785 // the physical register (e.g. if this is an unused input argument to a
786 // function).
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000787 }
788
Robert Lougher10f740d2017-08-03 11:54:02 +0000789 // The computed intervals may extend beyond the range of the debug
790 // location's lexical scope. In this case, splitting of an interval
791 // can result in an interval outside of the scope being created,
792 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
793 // this, trim the intervals to the lexical scope.
794
795 LexicalScope *Scope = LS.findLexicalScope(dl);
796 if (!Scope)
797 return;
798
799 SlotIndex PrevEnd;
800 LocMap::iterator I = locInts.begin();
801
802 // Iterate over the lexical scope ranges. Each time round the loop
803 // we check the intervals for overlap with the end of the previous
804 // range and the start of the next. The first range is handled as
805 // a special case where there is no PrevEnd.
806 for (const InsnRange &Range : Scope->getRanges()) {
807 SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
808 SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
809
810 // At the start of each iteration I has been advanced so that
811 // I.stop() >= PrevEnd. Check for overlap.
812 if (PrevEnd && I.start() < PrevEnd) {
813 SlotIndex IStop = I.stop();
Reid Kleckner04e25e02017-10-03 17:59:02 +0000814 DbgValueLocation Loc = I.value();
Robert Lougher10f740d2017-08-03 11:54:02 +0000815
816 // Stop overlaps previous end - trim the end of the interval to
817 // the scope range.
818 I.setStopUnchecked(PrevEnd);
819 ++I;
820
821 // If the interval also overlaps the start of the "next" (i.e.
822 // current) range create a new interval for the remainder (which
823 // may be further trimmed).
824 if (RStart < IStop)
Reid Kleckner04e25e02017-10-03 17:59:02 +0000825 I.insert(RStart, IStop, Loc);
Robert Lougher10f740d2017-08-03 11:54:02 +0000826 }
827
828 // Advance I so that I.stop() >= RStart, and check for overlap.
829 I.advanceTo(RStart);
830 if (!I.valid())
831 return;
832
833 if (I.start() < RStart) {
834 // Interval start overlaps range - trim to the scope range.
835 I.setStartUnchecked(RStart);
836 // Remember that this interval was trimmed.
837 trimmedDefs.insert(RStart);
838 }
839
840 // The end of a lexical scope range is the last instruction in the
841 // range. To convert to an interval we need the index of the
842 // instruction after it.
843 REnd = REnd.getNextIndex();
844
845 // Advance I to first interval outside current range.
846 I.advanceTo(REnd);
847 if (!I.valid())
848 return;
849
850 PrevEnd = REnd;
851 }
852
853 // Check for overlap with end of final range.
854 if (PrevEnd && I.start() < PrevEnd)
855 I.setStopUnchecked(PrevEnd);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000856}
857
858void LDVImpl::computeIntervals() {
Robert Lougher10f740d2017-08-03 11:54:02 +0000859 LexicalScopes LS;
860 LS.initialize(*MF);
861
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000862 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
Robert Lougher10f740d2017-08-03 11:54:02 +0000863 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000864 userValues[i]->mapVirtRegs(this);
865 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000866}
867
868bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
David Blaikie2f040112014-07-25 16:10:16 +0000869 clear();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000870 MF = &mf;
871 LIS = &pass.getAnalysis<LiveIntervals>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000872 TRI = mf.getSubtarget().getRegisterInfo();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000873 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
874 << mf.getName() << " **********\n");
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000875
876 bool Changed = collectDebugValues(mf);
877 computeIntervals();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000878 LLVM_DEBUG(print(dbgs()));
Manman Ren7a4c8a72013-02-13 20:23:48 +0000879 ModifiedMF = Changed;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000880 return Changed;
881}
882
David Blaikie2f040112014-07-25 16:10:16 +0000883static void removeDebugValues(MachineFunction &mf) {
884 for (MachineBasicBlock &MBB : mf) {
885 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
886 if (!MBBI->isDebugValue()) {
887 ++MBBI;
888 continue;
889 }
890 MBBI = MBB.erase(MBBI);
891 }
892 }
893}
894
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +0000895bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
Devang Patelacbee0b2011-01-07 22:33:41 +0000896 if (!EnableLDV)
897 return false;
Matthias Braunf1caa282017-12-15 22:22:58 +0000898 if (!mf.getFunction().getSubprogram()) {
David Blaikie2f040112014-07-25 16:10:16 +0000899 removeDebugValues(mf);
900 return false;
901 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000902 if (!pImpl)
903 pImpl = new LDVImpl(this);
Manman Ren7a4c8a72013-02-13 20:23:48 +0000904 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000905}
906
907void LiveDebugVariables::releaseMemory() {
Manman Ren7a4c8a72013-02-13 20:23:48 +0000908 if (pImpl)
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000909 static_cast<LDVImpl*>(pImpl)->clear();
910}
911
912LiveDebugVariables::~LiveDebugVariables() {
913 if (pImpl)
914 delete static_cast<LDVImpl*>(pImpl);
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +0000915}
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000916
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000917//===----------------------------------------------------------------------===//
918// Live Range Splitting
919//===----------------------------------------------------------------------===//
920
921bool
Mark Laceyf9ea8852013-08-14 23:50:04 +0000922UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
923 LiveIntervals& LIS) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000924 LLVM_DEBUG({
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000925 dbgs() << "Splitting Loc" << OldLocNo << '\t';
Craig Topperc0196b12014-04-14 00:51:57 +0000926 print(dbgs(), nullptr);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000927 });
928 bool DidChange = false;
929 LocMap::iterator LocMapI;
930 LocMapI.setMap(locInts);
931 for (unsigned i = 0; i != NewRegs.size(); ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000932 LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000933 if (LI->empty())
934 continue;
935
936 // Don't allocate the new LocNo until it is needed.
Reid Klecknereed09732017-09-15 22:08:50 +0000937 unsigned NewLocNo = UndefLocNo;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000938
939 // Iterate over the overlaps between locInts and LI.
940 LocMapI.find(LI->beginIndex());
941 if (!LocMapI.valid())
942 continue;
943 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
944 LiveInterval::iterator LIE = LI->end();
945 while (LocMapI.valid() && LII != LIE) {
946 // At this point, we know that LocMapI.stop() > LII->start.
947 LII = LI->advanceTo(LII, LocMapI.start());
948 if (LII == LIE)
949 break;
950
951 // Now LII->end > LocMapI.start(). Do we have an overlap?
Reid Kleckner04e25e02017-10-03 17:59:02 +0000952 if (LocMapI.value().locNo() == OldLocNo && LII->start < LocMapI.stop()) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000953 // Overlapping correct location. Allocate NewLocNo now.
Reid Klecknereed09732017-09-15 22:08:50 +0000954 if (NewLocNo == UndefLocNo) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000955 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
956 MO.setSubReg(locations[OldLocNo].getSubReg());
957 NewLocNo = getLocationNo(MO);
958 DidChange = true;
959 }
960
961 SlotIndex LStart = LocMapI.start();
962 SlotIndex LStop = LocMapI.stop();
Reid Kleckner04e25e02017-10-03 17:59:02 +0000963 DbgValueLocation OldLoc = LocMapI.value();
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000964
965 // Trim LocMapI down to the LII overlap.
966 if (LStart < LII->start)
967 LocMapI.setStartUnchecked(LII->start);
968 if (LStop > LII->end)
969 LocMapI.setStopUnchecked(LII->end);
970
971 // Change the value in the overlap. This may trigger coalescing.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000972 LocMapI.setValue(OldLoc.changeLocNo(NewLocNo));
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000973
974 // Re-insert any removed OldLocNo ranges.
975 if (LStart < LocMapI.start()) {
Reid Kleckner04e25e02017-10-03 17:59:02 +0000976 LocMapI.insert(LStart, LocMapI.start(), OldLoc);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000977 ++LocMapI;
978 assert(LocMapI.valid() && "Unexpected coalescing");
979 }
980 if (LStop > LocMapI.stop()) {
981 ++LocMapI;
Reid Kleckner04e25e02017-10-03 17:59:02 +0000982 LocMapI.insert(LII->end, LStop, OldLoc);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000983 --LocMapI;
984 }
985 }
986
987 // Advance to the next overlap.
988 if (LII->end < LocMapI.stop()) {
989 if (++LII == LIE)
990 break;
991 LocMapI.advanceTo(LII->start);
992 } else {
993 ++LocMapI;
994 if (!LocMapI.valid())
995 break;
996 LII = LI->advanceTo(LII, LocMapI.start());
997 }
998 }
999 }
1000
1001 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
1002 locations.erase(locations.begin() + OldLocNo);
1003 LocMapI.goToBegin();
1004 while (LocMapI.valid()) {
Reid Kleckner04e25e02017-10-03 17:59:02 +00001005 DbgValueLocation v = LocMapI.value();
1006 if (v.locNo() == OldLocNo) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001007 LLVM_DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
1008 << LocMapI.stop() << ")\n");
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001009 LocMapI.erase();
1010 } else {
Mikael Holmen57b33f62018-06-21 07:02:46 +00001011 // Undef values always have location number UndefLocNo, so don't change
1012 // locNo in that case. See getLocationNo().
1013 if (!v.isUndef() && v.locNo() > OldLocNo)
Reid Kleckner04e25e02017-10-03 17:59:02 +00001014 LocMapI.setValueUnchecked(v.changeLocNo(v.locNo() - 1));
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001015 ++LocMapI;
1016 }
1017 }
1018
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001019 LLVM_DEBUG({
1020 dbgs() << "Split result: \t";
1021 print(dbgs(), nullptr);
1022 });
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001023 return DidChange;
1024}
1025
1026bool
Mark Laceyf9ea8852013-08-14 23:50:04 +00001027UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
1028 LiveIntervals &LIS) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001029 bool DidChange = false;
Jakob Stoklund Olesen57c8f582011-05-06 19:31:19 +00001030 // Split locations referring to OldReg. Iterate backwards so splitLocation can
Eric Christopherbe153e62012-03-15 21:33:35 +00001031 // safely erase unused locations.
Jakob Stoklund Olesen57c8f582011-05-06 19:31:19 +00001032 for (unsigned i = locations.size(); i ; --i) {
1033 unsigned LocNo = i-1;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001034 const MachineOperand *Loc = &locations[LocNo];
1035 if (!Loc->isReg() || Loc->getReg() != OldReg)
1036 continue;
Mark Laceyf9ea8852013-08-14 23:50:04 +00001037 DidChange |= splitLocation(LocNo, NewRegs, LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001038 }
1039 return DidChange;
1040}
1041
Mark Laceyf9ea8852013-08-14 23:50:04 +00001042void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001043 bool DidChange = false;
1044 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
Mark Laceyf9ea8852013-08-14 23:50:04 +00001045 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001046
1047 if (!DidChange)
1048 return;
1049
1050 // Map all of the new virtual registers.
1051 UserValue *UV = lookupVirtReg(OldReg);
1052 for (unsigned i = 0; i != NewRegs.size(); ++i)
Mark Laceyf9ea8852013-08-14 23:50:04 +00001053 mapVirtReg(NewRegs[i], UV);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001054}
1055
1056void LiveDebugVariables::
Mark Laceyf9ea8852013-08-14 23:50:04 +00001057splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001058 if (pImpl)
1059 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
1060}
1061
David Stenberg45acc962018-09-07 13:54:07 +00001062void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
1063 const TargetInstrInfo &TII,
1064 const TargetRegisterInfo &TRI,
1065 SpillOffsetMap &SpillOffsets) {
Reid Kleckner92687d42017-09-20 17:32:54 +00001066 // Build a set of new locations with new numbers so we can coalesce our
1067 // IntervalMap if two vreg intervals collapse to the same physical location.
1068 // Use MapVector instead of SetVector because MapVector::insert returns the
Reid Kleckner4e040282017-09-20 18:19:08 +00001069 // position of the previously or newly inserted element. The boolean value
1070 // tracks if the location was produced by a spill.
1071 // FIXME: This will be problematic if we ever support direct and indirect
1072 // frame index locations, i.e. expressing both variables in memory and
1073 // 'int x, *px = &x'. The "spilled" bit must become part of the location.
David Stenberg45acc962018-09-07 13:54:07 +00001074 MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
Reid Kleckner92687d42017-09-20 17:32:54 +00001075 SmallVector<unsigned, 4> LocNoMap(locations.size());
1076 for (unsigned I = 0, E = locations.size(); I != E; ++I) {
Reid Kleckner4e040282017-09-20 18:19:08 +00001077 bool Spilled = false;
David Stenberg45acc962018-09-07 13:54:07 +00001078 unsigned SpillOffset = 0;
Reid Kleckner92687d42017-09-20 17:32:54 +00001079 MachineOperand Loc = locations[I];
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001080 // Only virtual registers are rewritten.
Reid Kleckner92687d42017-09-20 17:32:54 +00001081 if (Loc.isReg() && Loc.getReg() &&
1082 TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
1083 unsigned VirtReg = Loc.getReg();
1084 if (VRM.isAssignedReg(VirtReg) &&
1085 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
1086 // This can create a %noreg operand in rare cases when the sub-register
1087 // index is no longer available. That means the user value is in a
1088 // non-existent sub-register, and %noreg is exactly what we want.
1089 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
1090 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
David Stenberg45acc962018-09-07 13:54:07 +00001091 // Retrieve the stack slot offset.
1092 unsigned SpillSize;
1093 const MachineRegisterInfo &MRI = MF.getRegInfo();
1094 const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
1095 bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
1096 SpillOffset, MF);
1097
1098 // FIXME: Invalidate the location if the offset couldn't be calculated.
1099 (void)Success;
1100
Reid Kleckner92687d42017-09-20 17:32:54 +00001101 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
Reid Kleckner4e040282017-09-20 18:19:08 +00001102 Spilled = true;
Reid Kleckner92687d42017-09-20 17:32:54 +00001103 } else {
1104 Loc.setReg(0);
1105 Loc.setSubReg(0);
1106 }
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001107 }
Reid Kleckner92687d42017-09-20 17:32:54 +00001108
1109 // Insert this location if it doesn't already exist and record a mapping
1110 // from the old number to the new number.
David Stenberg45acc962018-09-07 13:54:07 +00001111 auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
Reid Kleckner4e040282017-09-20 18:19:08 +00001112 unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
1113 LocNoMap[I] = NewLocNo;
Reid Kleckner92687d42017-09-20 17:32:54 +00001114 }
1115
David Stenberg45acc962018-09-07 13:54:07 +00001116 // Rewrite the locations and record the stack slot offsets for spills.
Reid Kleckner92687d42017-09-20 17:32:54 +00001117 locations.clear();
David Stenberg45acc962018-09-07 13:54:07 +00001118 SpillOffsets.clear();
Reid Kleckner4e040282017-09-20 18:19:08 +00001119 for (auto &Pair : NewLocations) {
David Stenberg45acc962018-09-07 13:54:07 +00001120 bool Spilled;
1121 unsigned SpillOffset;
1122 std::tie(Spilled, SpillOffset) = Pair.second;
Reid Kleckner92687d42017-09-20 17:32:54 +00001123 locations.push_back(Pair.first);
David Stenberg45acc962018-09-07 13:54:07 +00001124 if (Spilled) {
Reid Kleckner4e040282017-09-20 18:19:08 +00001125 unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
David Stenberg45acc962018-09-07 13:54:07 +00001126 SpillOffsets[NewLocNo] = SpillOffset;
Reid Kleckner4e040282017-09-20 18:19:08 +00001127 }
1128 }
Reid Kleckner92687d42017-09-20 17:32:54 +00001129
1130 // Update the interval map, but only coalesce left, since intervals to the
1131 // right use the old location numbers. This should merge two contiguous
1132 // DBG_VALUE intervals with different vregs that were allocated to the same
1133 // physical register.
1134 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
Reid Kleckner04e25e02017-10-03 17:59:02 +00001135 DbgValueLocation Loc = I.value();
Mikael Holmen57b33f62018-06-21 07:02:46 +00001136 // Undef values don't exist in locations (and thus not in LocNoMap either)
1137 // so skip over them. See getLocationNo().
1138 if (Loc.isUndef())
1139 continue;
Reid Kleckner04e25e02017-10-03 17:59:02 +00001140 unsigned NewLocNo = LocNoMap[Loc.locNo()];
1141 I.setValueUnchecked(Loc.changeLocNo(NewLocNo));
Reid Kleckner92687d42017-09-20 17:32:54 +00001142 I.setStart(I.start());
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001143 }
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001144}
1145
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001146/// Find an iterator for inserting a DBG_VALUE instruction.
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001147static MachineBasicBlock::iterator
Devang Patel26ffa012011-02-04 01:43:25 +00001148findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001149 LiveIntervals &LIS) {
1150 SlotIndex Start = LIS.getMBBStartIdx(MBB);
1151 Idx = Idx.getBaseIndex();
1152
1153 // Try to find an insert location by going backwards from Idx.
1154 MachineInstr *MI;
1155 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1156 // We've reached the beginning of MBB.
1157 if (Idx == Start) {
Keith Walker830a8c12016-09-16 14:07:29 +00001158 MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001159 return I;
1160 }
1161 Idx = Idx.getPrevIndex();
1162 }
Devang Patel26ffa012011-02-04 01:43:25 +00001163
Jakob Stoklund Olesen088b30a2011-01-13 23:35:53 +00001164 // Don't insert anything after the first terminator, though.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001165 return MI->isTerminator() ? MBB->getFirstTerminator() :
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001166 std::next(MachineBasicBlock::iterator(MI));
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001167}
1168
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001169/// Find an iterator for inserting the next DBG_VALUE instruction
1170/// (or end if no more insert locations found).
1171static MachineBasicBlock::iterator
1172findNextInsertLocation(MachineBasicBlock *MBB,
1173 MachineBasicBlock::iterator I,
1174 SlotIndex StopIdx, MachineOperand &LocMO,
1175 LiveIntervals &LIS,
1176 const TargetRegisterInfo &TRI) {
1177 if (!LocMO.isReg())
1178 return MBB->instr_end();
1179 unsigned Reg = LocMO.getReg();
1180
1181 // Find the next instruction in the MBB that define the register Reg.
Stefan Maksimovic991af7a2018-02-09 14:03:26 +00001182 while (I != MBB->end() && !I->isTerminator()) {
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001183 if (!LIS.isNotInMIMap(*I) &&
1184 SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
1185 break;
1186 if (I->definesRegister(Reg, &TRI))
1187 // The insert location is directly after the instruction/bundle.
1188 return std::next(I);
1189 ++I;
1190 }
1191 return MBB->end();
1192}
1193
1194void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
David Stenberg45acc962018-09-07 13:54:07 +00001195 SlotIndex StopIdx, DbgValueLocation Loc,
1196 bool Spilled, unsigned SpillOffset,
1197 LiveIntervals &LIS, const TargetInstrInfo &TII,
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001198 const TargetRegisterInfo &TRI) {
1199 SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
1200 // Only search within the current MBB.
1201 StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1202 MachineBasicBlock::iterator I = findInsertLocation(MBB, StartIdx, LIS);
Mikael Holmen57b33f62018-06-21 07:02:46 +00001203 // Undef values don't exist in locations so create new "noreg" register MOs
1204 // for them. See getLocationNo().
1205 MachineOperand MO = !Loc.isUndef() ?
1206 locations[Loc.locNo()] :
1207 MachineOperand::CreateReg(/* Reg */ 0, /* isDef */ false, /* isImp */ false,
1208 /* isKill */ false, /* isDead */ false,
1209 /* isUndef */ false, /* isEarlyClobber */ false,
1210 /* SubReg */ 0, /* isDebug */ true);
1211
Devang Pateleabc3cea2011-08-04 20:42:11 +00001212 ++NumInsertedDebugValues;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001213
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001214 assert(cast<DILocalVariable>(Variable)
Duncan P. N. Exon Smithe686f152015-04-06 23:27:40 +00001215 ->isValidLocationForIntrinsic(getDebugLoc()) &&
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00001216 "Expected inlined-at fields to agree");
Reid Kleckner4e040282017-09-20 18:19:08 +00001217
1218 // If the location was spilled, the new DBG_VALUE will be indirect. If the
1219 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
David Stenberg45acc962018-09-07 13:54:07 +00001220 // that the original virtual register was a pointer. Also, add the stack slot
1221 // offset for the spilled register to the expression.
Reid Kleckner4e040282017-09-20 18:19:08 +00001222 const DIExpression *Expr = Expression;
Reid Kleckner04e25e02017-10-03 17:59:02 +00001223 bool IsIndirect = Loc.wasIndirect();
1224 if (Spilled) {
David Stenberg45acc962018-09-07 13:54:07 +00001225 auto Deref = IsIndirect ? DIExpression::WithDeref : DIExpression::NoDeref;
1226 Expr =
1227 DIExpression::prepend(Expr, DIExpression::NoDeref, SpillOffset, Deref);
Reid Kleckner04e25e02017-10-03 17:59:02 +00001228 IsIndirect = true;
1229 }
Reid Kleckner4e040282017-09-20 18:19:08 +00001230
Reid Kleckner04e25e02017-10-03 17:59:02 +00001231 assert((!Spilled || MO.isFI()) && "a spilled location must be a frame index");
Reid Kleckner4e040282017-09-20 18:19:08 +00001232
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001233 do {
Mikael Holmen42f7bc92018-06-21 10:03:34 +00001234 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
1235 IsIndirect, MO, Variable, Expr);
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001236
1237 // Continue and insert DBG_VALUES after every redefinition of register
1238 // associated with the debug value within the range
1239 I = findNextInsertLocation(MBB, I, StopIdx, MO, LIS, TRI);
1240 } while (I != MBB->end());
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001241}
1242
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001243void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
Reid Kleckner4e040282017-09-20 18:19:08 +00001244 const TargetInstrInfo &TII,
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001245 const TargetRegisterInfo &TRI,
David Stenberg45acc962018-09-07 13:54:07 +00001246 const SpillOffsetMap &SpillOffsets) {
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001247 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1248
1249 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1250 SlotIndex Start = I.start();
1251 SlotIndex Stop = I.stop();
Reid Kleckner04e25e02017-10-03 17:59:02 +00001252 DbgValueLocation Loc = I.value();
David Stenberg45acc962018-09-07 13:54:07 +00001253 auto SpillIt =
1254 !Loc.isUndef() ? SpillOffsets.find(Loc.locNo()) : SpillOffsets.end();
1255 bool Spilled = SpillIt != SpillOffsets.end();
1256 unsigned SpillOffset = Spilled ? SpillIt->second : 0;
Robert Lougher10f740d2017-08-03 11:54:02 +00001257
1258 // If the interval start was trimmed to the lexical scope insert the
1259 // DBG_VALUE at the previous index (otherwise it appears after the
1260 // first instruction in the range).
1261 if (trimmedDefs.count(Start))
1262 Start = Start.getPrevIndex();
1263
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001264 LLVM_DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << Loc.locNo());
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001265 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1266 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001267
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001268 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
David Stenberg45acc962018-09-07 13:54:07 +00001269 insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, SpillOffset, LIS, TII,
1270 TRI);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001271 // This interval may span multiple basic blocks.
1272 // Insert a DBG_VALUE into each one.
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001273 while (Stop > MBBEnd) {
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001274 // Move to the next block.
1275 Start = MBBEnd;
1276 if (++MBB == MFEnd)
1277 break;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001278 MBBEnd = LIS.getMBBEndIdx(&*MBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001279 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
David Stenberg45acc962018-09-07 13:54:07 +00001280 insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, SpillOffset, LIS, TII,
1281 TRI);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001282 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001283 LLVM_DEBUG(dbgs() << '\n');
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001284 if (MBB == MFEnd)
1285 break;
1286
1287 ++I;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001288 }
1289}
1290
1291void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001292 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
David Blaikie2f040112014-07-25 16:10:16 +00001293 if (!MF)
1294 return;
Eric Christopherfc6de422014-08-05 02:39:49 +00001295 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
David Stenberg45acc962018-09-07 13:54:07 +00001296 SpillOffsetMap SpillOffsets;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001297 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001298 LLVM_DEBUG(userValues[i]->print(dbgs(), TRI));
David Stenberg45acc962018-09-07 13:54:07 +00001299 userValues[i]->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
1300 userValues[i]->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001301 }
Manman Ren7a4c8a72013-02-13 20:23:48 +00001302 EmitDone = true;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001303}
1304
1305void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
Manman Ren7a4c8a72013-02-13 20:23:48 +00001306 if (pImpl)
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001307 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1308}
1309
David Blaikie2f040112014-07-25 16:10:16 +00001310bool LiveDebugVariables::doInitialization(Module &M) {
David Blaikie2f040112014-07-25 16:10:16 +00001311 return Pass::doInitialization(M);
1312}
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001313
Aaron Ballman615eb472017-10-15 14:32:27 +00001314#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Clegg705f7982017-06-21 22:19:17 +00001315LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +00001316 if (pImpl)
1317 static_cast<LDVImpl*>(pImpl)->print(dbgs());
1318}
1319#endif