blob: 2e8615219c8a131ebaf154aa7fc81eb2387ebcb7 [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"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000023#include "llvm/ADT/IntervalMap.h"
Devang Patelb4568662011-08-04 18:45:38 +000024#include "llvm/ADT/Statistic.h"
Devang Patel37a62052011-08-10 21:25:34 +000025#include "llvm/CodeGen/LexicalScopes.h"
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000026#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000027#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000031#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000032#include "llvm/CodeGen/VirtRegMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000034#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Metadata.h"
36#include "llvm/IR/Value.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000037#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000039#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +000040#include "llvm/Target/TargetInstrInfo.h"
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000041#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000042#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000043#include "llvm/Target/TargetSubtargetInfo.h"
David Blaikie2b1dfa72014-04-21 20:37:07 +000044#include <memory>
45
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000046using namespace llvm;
47
Chandler Carruth1b9dde02014-04-22 02:02:50 +000048#define DEBUG_TYPE "livedebug"
49
Devang Patelacbee0b2011-01-07 22:33:41 +000050static cl::opt<bool>
Jakob Stoklund Olesen74ded572011-01-12 23:36:21 +000051EnableLDV("live-debug-variables", cl::init(true),
Devang Patelacbee0b2011-01-07 22:33:41 +000052 cl::desc("Enable the live debug variables pass"), cl::Hidden);
53
Devang Patelb4568662011-08-04 18:45:38 +000054STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000055char LiveDebugVariables::ID = 0;
56
57INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
58 "Debug Variable Analysis", false, false)
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000059INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000060INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
61INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
62 "Debug Variable Analysis", false, false)
63
64void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000065 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000066 AU.addRequiredTransitive<LiveIntervals>();
67 AU.setPreservesAll();
68 MachineFunctionPass::getAnalysisUsage(AU);
69}
70
Craig Topperc0196b12014-04-14 00:51:57 +000071LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(nullptr) {
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000072 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
73}
74
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000075/// LocMap - Map of where a user value is live, and its location.
76typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
77
Benjamin Kramer67b014b2011-09-16 00:35:06 +000078namespace {
Eric Christopher9d7d5da2013-11-20 00:54:25 +000079/// UserValueScopes - Keeps track of lexical scopes associated with a
Devang Patelf9e2ae92011-09-13 18:40:53 +000080/// user value's source location.
81class UserValueScopes {
82 DebugLoc DL;
83 LexicalScopes &LS;
84 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
85
86public:
87 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(D), LS(L) {}
88
89 /// dominates - Return true if current scope dominates at least one machine
90 /// instruction in a given machine basic block.
91 bool dominates(MachineBasicBlock *MBB) {
92 if (LBlocks.empty())
93 LS.getMachineBasicBlocks(DL, LBlocks);
94 if (LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB))
95 return true;
96 return false;
97 }
98};
Benjamin Kramer67b014b2011-09-16 00:35:06 +000099} // end anonymous namespace
Devang Patelf9e2ae92011-09-13 18:40:53 +0000100
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000101/// UserValue - A user value is a part of a debug info user variable.
102///
103/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
104/// holds part of a user variable. The part is identified by a byte offset.
105///
106/// UserValues are grouped into equivalence classes for easier searching. Two
107/// user values are related if they refer to the same variable, or if they are
108/// held by the same virtual register. The equivalence class is the transitive
109/// closure of that relation.
110namespace {
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000111class LDVImpl;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000112class UserValue {
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000113 const MDNode *Variable; ///< The debug info variable we are part of.
114 const MDNode *Expression; ///< Any complex address expression.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000115 unsigned offset; ///< Byte offset into variable.
Adrian Prantl418d1d12013-07-09 20:28:37 +0000116 bool IsIndirect; ///< true if this is a register-indirect+offset value.
Devang Patel26ffa012011-02-04 01:43:25 +0000117 DebugLoc dl; ///< The debug location for the variable. This is
118 ///< used by dwarf writer to find lexical scope.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000119 UserValue *leader; ///< Equivalence class leader.
120 UserValue *next; ///< Next value in equivalence class, or null.
121
122 /// Numbered locations referenced by locmap.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000123 SmallVector<MachineOperand, 4> locations;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000124
125 /// Map of slot indices where this value is live.
126 LocMap locInts;
127
Jakob Stoklund Olesen44086032010-12-03 22:25:07 +0000128 /// coalesceLocation - After LocNo was changed, check if it has become
129 /// identical to another location, and coalesce them. This may cause LocNo or
130 /// a later location to be erased, but no earlier location will be erased.
131 void coalesceLocation(unsigned LocNo);
132
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000133 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
134 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
135 LiveIntervals &LIS, const TargetInstrInfo &TII);
136
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000137 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
138 /// is live. Returns true if any changes were made.
Mark Laceyf9ea8852013-08-14 23:50:04 +0000139 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
140 LiveIntervals &LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000141
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000142public:
143 /// UserValue - Create a new UserValue.
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000144 UserValue(const MDNode *var, const MDNode *expr, unsigned o, bool i,
145 DebugLoc L, LocMap::Allocator &alloc)
146 : Variable(var), Expression(expr), offset(o), IsIndirect(i), dl(L),
147 leader(this), next(nullptr), locInts(alloc) {}
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000148
149 /// getLeader - Get the leader of this value's equivalence class.
150 UserValue *getLeader() {
151 UserValue *l = leader;
152 while (l != l->leader)
153 l = l->leader;
154 return leader = l;
155 }
156
157 /// getNext - Return the next UserValue in the equivalence class.
158 UserValue *getNext() const { return next; }
159
Devang Patel338e4322011-07-06 23:09:51 +0000160 /// match - Does this UserValue match the parameters?
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000161 bool match(const MDNode *Var, const MDNode *Expr, unsigned Offset,
162 bool indirect) const {
163 return Var == Variable && Expr == Expression && Offset == offset &&
164 indirect == IsIndirect;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000165 }
166
167 /// merge - Merge equivalence classes.
168 static UserValue *merge(UserValue *L1, UserValue *L2) {
169 L2 = L2->getLeader();
170 if (!L1)
171 return L2;
172 L1 = L1->getLeader();
173 if (L1 == L2)
174 return L1;
175 // Splice L2 before L1's members.
176 UserValue *End = L2;
177 while (End->next)
178 End->leader = L1, End = End->next;
179 End->leader = L1;
180 End->next = L1->next;
181 L1->next = L2;
182 return L1;
183 }
184
185 /// getLocationNo - Return the location number that matches Loc.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000186 unsigned getLocationNo(const MachineOperand &LocMO) {
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000187 if (LocMO.isReg()) {
188 if (LocMO.getReg() == 0)
189 return ~0u;
190 // For register locations we dont care about use/def and other flags.
191 for (unsigned i = 0, e = locations.size(); i != e; ++i)
192 if (locations[i].isReg() &&
193 locations[i].getReg() == LocMO.getReg() &&
194 locations[i].getSubReg() == LocMO.getSubReg())
195 return i;
196 } else
197 for (unsigned i = 0, e = locations.size(); i != e; ++i)
198 if (LocMO.isIdenticalTo(locations[i]))
199 return i;
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000200 locations.push_back(LocMO);
201 // We are storing a MachineOperand outside a MachineInstr.
202 locations.back().clearParent();
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000203 // Don't store def operands.
204 if (locations.back().isReg())
205 locations.back().setIsUse();
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000206 return locations.size() - 1;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000207 }
208
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000209 /// mapVirtRegs - Ensure that all virtual register locations are mapped.
210 void mapVirtRegs(LDVImpl *LDV);
211
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000212 /// addDef - Add a definition point to this value.
213 void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
214 // Add a singular (Idx,Idx) -> Loc mapping.
215 LocMap::iterator I = locInts.find(Idx);
216 if (!I.valid() || I.start() != Idx)
217 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
Jakob Stoklund Olesen2539af62011-08-03 23:44:31 +0000218 else
219 // A later DBG_VALUE at the same SlotIndex overrides the old location.
220 I.setValue(getLocationNo(LocMO));
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000221 }
222
223 /// extendDef - Extend the current definition as far as possible down the
224 /// dominator tree. Stop when meeting an existing def or when leaving the live
225 /// range of VNI.
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000226 /// End points where VNI is no longer live are added to Kills.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000227 /// @param Idx Starting point for the definition.
228 /// @param LocNo Location number to propagate.
Matthias Braun34e1be92013-10-10 21:29:02 +0000229 /// @param LR Restrict liveness to where LR has the value VNI. May be null.
230 /// @param VNI When LR is not null, this is the value to restrict to.
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000231 /// @param Kills Append end points of VNI's live range to Kills.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000232 /// @param LIS Live intervals analysis.
233 /// @param MDT Dominator tree.
234 void extendDef(SlotIndex Idx, unsigned LocNo,
Matthias Braun34e1be92013-10-10 21:29:02 +0000235 LiveRange *LR, const VNInfo *VNI,
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000236 SmallVectorImpl<SlotIndex> *Kills,
Devang Patel37a62052011-08-10 21:25:34 +0000237 LiveIntervals &LIS, MachineDominatorTree &MDT,
Eric Christopher6a0c6792012-03-15 21:33:39 +0000238 UserValueScopes &UVS);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000239
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000240 /// addDefsFromCopies - The value in LI/LocNo may be copies to other
241 /// registers. Determine if any of the copies are available at the kill
242 /// points, and add defs if possible.
243 /// @param LI Scan for copies of the value in LI->reg.
244 /// @param LocNo Location number of LI->reg.
245 /// @param Kills Points where the range of LocNo could be extended.
246 /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
247 void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
248 const SmallVectorImpl<SlotIndex> &Kills,
249 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
250 MachineRegisterInfo &MRI,
251 LiveIntervals &LIS);
252
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000253 /// computeIntervals - Compute the live intervals of all locations after
254 /// collecting all their def points.
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000255 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
Devang Patel37a62052011-08-10 21:25:34 +0000256 LiveIntervals &LIS, MachineDominatorTree &MDT,
Devang Patelf9e2ae92011-09-13 18:40:53 +0000257 UserValueScopes &UVS);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000258
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000259 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
260 /// live. Returns true if any changes were made.
Mark Laceyf9ea8852013-08-14 23:50:04 +0000261 bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
262 LiveIntervals &LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000263
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000264 /// rewriteLocations - Rewrite virtual register locations according to the
265 /// provided virtual register map.
266 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
267
Eric Christopherbc671702013-02-13 02:29:18 +0000268 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000269 void emitDebugValues(VirtRegMap *VRM,
270 LiveIntervals &LIS, const TargetInstrInfo &TRI);
271
Devang Patelf9e2ae92011-09-13 18:40:53 +0000272 /// getDebugLoc - Return DebugLoc of this UserValue.
273 DebugLoc getDebugLoc() { return dl;}
Eric Christopher1cdefae2015-02-27 00:11:34 +0000274 void print(raw_ostream &, const TargetRegisterInfo *);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000275};
276} // namespace
277
278/// LDVImpl - Implementation of the LiveDebugVariables pass.
279namespace {
280class LDVImpl {
281 LiveDebugVariables &pass;
282 LocMap::Allocator allocator;
283 MachineFunction *MF;
284 LiveIntervals *LIS;
Devang Patel37a62052011-08-10 21:25:34 +0000285 LexicalScopes LS;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000286 MachineDominatorTree *MDT;
287 const TargetRegisterInfo *TRI;
288
Manman Ren7a4c8a72013-02-13 20:23:48 +0000289 /// Whether emitDebugValues is called.
290 bool EmitDone;
291 /// Whether the machine function is modified during the pass.
292 bool ModifiedMF;
293
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000294 /// userValues - All allocated UserValue instances.
David Blaikie2b1dfa72014-04-21 20:37:07 +0000295 SmallVector<std::unique_ptr<UserValue>, 8> userValues;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000296
297 /// Map virtual register to eq class leader.
298 typedef DenseMap<unsigned, UserValue*> VRMap;
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000299 VRMap virtRegToEqClass;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000300
301 /// Map user variable to eq class leader.
302 typedef DenseMap<const MDNode *, UserValue*> UVMap;
303 UVMap userVarMap;
304
305 /// getUserValue - Find or create a UserValue.
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000306 UserValue *getUserValue(const MDNode *Var, const MDNode *Expr,
307 unsigned Offset, bool IsIndirect, DebugLoc DL);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000308
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000309 /// lookupVirtReg - Find the EC leader for VirtReg or null.
310 UserValue *lookupVirtReg(unsigned VirtReg);
311
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000312 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
313 /// @param MI DBG_VALUE instruction
314 /// @param Idx Last valid SLotIndex before instruction.
315 /// @return True if the DBG_VALUE instruction should be deleted.
316 bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
317
318 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
319 /// a UserValue def for each instruction.
320 /// @param mf MachineFunction to be scanned.
321 /// @return True if any debug values were found.
322 bool collectDebugValues(MachineFunction &mf);
323
324 /// computeIntervals - Compute the live intervals of all user values after
325 /// collecting all their def points.
326 void computeIntervals();
327
328public:
David Blaikie2f040112014-07-25 16:10:16 +0000329 LDVImpl(LiveDebugVariables *ps)
330 : pass(*ps), MF(nullptr), EmitDone(false), ModifiedMF(false) {}
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000331 bool runOnMachineFunction(MachineFunction &mf);
332
Manman Ren7a4c8a72013-02-13 20:23:48 +0000333 /// clear - Release all memory.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000334 void clear() {
David Blaikie2f040112014-07-25 16:10:16 +0000335 MF = nullptr;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000336 userValues.clear();
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000337 virtRegToEqClass.clear();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000338 userVarMap.clear();
Manman Ren7a4c8a72013-02-13 20:23:48 +0000339 // Make sure we call emitDebugValues if the machine function was modified.
340 assert((!ModifiedMF || EmitDone) &&
341 "Dbg values are not emitted in LDV");
342 EmitDone = false;
343 ModifiedMF = false;
Marcello Maggioni22594002014-10-24 02:46:50 +0000344 LS.reset();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000345 }
346
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000347 /// mapVirtReg - Map virtual register to an equivalence class.
348 void mapVirtReg(unsigned VirtReg, UserValue *EC);
349
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000350 /// splitRegister - Replace all references to OldReg with NewRegs.
Mark Laceyf9ea8852013-08-14 23:50:04 +0000351 void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000352
Eric Christopherbc671702013-02-13 02:29:18 +0000353 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000354 void emitDebugValues(VirtRegMap *VRM);
355
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000356 void print(raw_ostream&);
357};
358} // namespace
359
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000360static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
361 const LLVMContext &Ctx) {
362 if (!DL)
363 return;
364
365 DIScope Scope = cast<MDScope>(DL.getScope());
366 // Omit the directory, because it's likely to be long and uninteresting.
367 CommentOS << Scope.getFilename();
368 CommentOS << ':' << DL.getLine();
369 if (DL.getCol() != 0)
370 CommentOS << ':' << DL.getCol();
371
372 DebugLoc InlinedAtDL = DL.getInlinedAt();
373 if (!InlinedAtDL)
374 return;
375
376 CommentOS << " @[ ";
377 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
378 CommentOS << " ]";
379}
380
381static void printExtendedName(raw_ostream &OS, const MDLocalVariable *V) {
382 const LLVMContext &Ctx = V->getContext();
383 StringRef Res = V->getName();
384 if (!Res.empty())
385 OS << Res << "," << V->getLine();
386 if (auto *InlinedAt = V->getInlinedAt()) {
387 if (DebugLoc InlinedAtDL = InlinedAt) {
388 OS << " @[";
389 printDebugLoc(InlinedAtDL, OS, Ctx);
390 OS << "]";
391 }
392 }
393}
394
Eric Christopher1cdefae2015-02-27 00:11:34 +0000395void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
Duncan P. N. Exon Smithe686f152015-04-06 23:27:40 +0000396 DIVariable DV = cast<MDLocalVariable>(Variable);
Frederic Risse6bb1872014-08-07 20:04:00 +0000397 OS << "!\"";
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000398 printExtendedName(OS, DV);
399
Devang Patel6c1ed312011-08-09 01:03:35 +0000400 OS << "\"\t";
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000401 if (offset)
402 OS << '+' << offset;
403 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
404 OS << " [" << I.start() << ';' << I.stop() << "):";
405 if (I.value() == ~0u)
406 OS << "undef";
407 else
408 OS << I.value();
409 }
Jakob Stoklund Olesenc86fe052011-05-06 17:59:59 +0000410 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
411 OS << " Loc" << i << '=';
Eric Christopher1cdefae2015-02-27 00:11:34 +0000412 locations[i].print(OS, TRI);
Jakob Stoklund Olesenc86fe052011-05-06 17:59:59 +0000413 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000414 OS << '\n';
415}
416
417void LDVImpl::print(raw_ostream &OS) {
418 OS << "********** DEBUG VARIABLES **********\n";
419 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
Eric Christopher1cdefae2015-02-27 00:11:34 +0000420 userValues[i]->print(OS, TRI);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000421}
422
Jakob Stoklund Olesen44086032010-12-03 22:25:07 +0000423void UserValue::coalesceLocation(unsigned LocNo) {
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000424 unsigned KeepLoc = 0;
425 for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
426 if (KeepLoc == LocNo)
427 continue;
428 if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
429 break;
Jakob Stoklund Olesen44086032010-12-03 22:25:07 +0000430 }
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000431 // No matches.
432 if (KeepLoc == locations.size())
433 return;
434
435 // Keep the smaller location, erase the larger one.
436 unsigned EraseLoc = LocNo;
437 if (KeepLoc > EraseLoc)
438 std::swap(KeepLoc, EraseLoc);
Jakob Stoklund Olesen44086032010-12-03 22:25:07 +0000439 locations.erase(locations.begin() + EraseLoc);
440
441 // Rewrite values.
442 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
443 unsigned v = I.value();
444 if (v == EraseLoc)
445 I.setValue(KeepLoc); // Coalesce when possible.
446 else if (v > EraseLoc)
447 I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
448 }
449}
450
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000451void UserValue::mapVirtRegs(LDVImpl *LDV) {
452 for (unsigned i = 0, e = locations.size(); i != e; ++i)
453 if (locations[i].isReg() &&
454 TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
455 LDV->mapVirtReg(locations[i].getReg(), this);
456}
457
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000458UserValue *LDVImpl::getUserValue(const MDNode *Var, const MDNode *Expr,
459 unsigned Offset, bool IsIndirect,
460 DebugLoc DL) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000461 UserValue *&Leader = userVarMap[Var];
462 if (Leader) {
463 UserValue *UV = Leader->getLeader();
464 Leader = UV;
465 for (; UV; UV = UV->getNext())
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000466 if (UV->match(Var, Expr, Offset, IsIndirect))
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000467 return UV;
468 }
469
David Blaikie2b1dfa72014-04-21 20:37:07 +0000470 userValues.push_back(
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000471 make_unique<UserValue>(Var, Expr, Offset, IsIndirect, DL, allocator));
David Blaikie2b1dfa72014-04-21 20:37:07 +0000472 UserValue *UV = userValues.back().get();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000473 Leader = UserValue::merge(Leader, UV);
474 return UV;
475}
476
477void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
478 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000479 UserValue *&Leader = virtRegToEqClass[VirtReg];
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000480 Leader = UserValue::merge(Leader, EC);
481}
482
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000483UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000484 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000485 return UV->getLeader();
Craig Topperc0196b12014-04-14 00:51:57 +0000486 return nullptr;
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000487}
488
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000489bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
490 // DBG_VALUE loc, offset, variable
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000491 if (MI->getNumOperands() != 4 ||
Adrian Prantl418d1d12013-07-09 20:28:37 +0000492 !(MI->getOperand(1).isReg() || MI->getOperand(1).isImm()) ||
493 !MI->getOperand(2).isMetadata()) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000494 DEBUG(dbgs() << "Can't handle " << *MI);
495 return false;
496 }
497
498 // Get or create the UserValue for (variable,offset).
Adrian Prantldb3e26d2013-09-16 23:29:03 +0000499 bool IsIndirect = MI->isIndirectDebugValue();
Adrian Prantl418d1d12013-07-09 20:28:37 +0000500 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000501 const MDNode *Var = MI->getDebugVariable();
502 const MDNode *Expr = MI->getDebugExpression();
Adrian Prantldb3e26d2013-09-16 23:29:03 +0000503 //here.
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000504 UserValue *UV =
505 getUserValue(Var, Expr, Offset, IsIndirect, MI->getDebugLoc());
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000506 UV->addDef(Idx, MI->getOperand(0));
507 return true;
508}
509
510bool LDVImpl::collectDebugValues(MachineFunction &mf) {
511 bool Changed = false;
512 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
513 ++MFI) {
514 MachineBasicBlock *MBB = MFI;
515 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
516 MBBI != MBBE;) {
517 if (!MBBI->isDebugValue()) {
518 ++MBBI;
519 continue;
520 }
521 // DBG_VALUE has no slot index, use the previous instruction instead.
522 SlotIndex Idx = MBBI == MBB->begin() ?
523 LIS->getMBBStartIdx(MBB) :
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000524 LIS->getInstructionIndex(std::prev(MBBI)).getRegSlot();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000525 // Handle consecutive DBG_VALUE instructions with the same slot index.
526 do {
527 if (handleDebugValue(MBBI, Idx)) {
528 MBBI = MBB->erase(MBBI);
529 Changed = true;
530 } else
531 ++MBBI;
532 } while (MBBI != MBBE && MBBI->isDebugValue());
533 }
534 }
535 return Changed;
536}
537
538void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
Matthias Braun34e1be92013-10-10 21:29:02 +0000539 LiveRange *LR, const VNInfo *VNI,
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000540 SmallVectorImpl<SlotIndex> *Kills,
Devang Patel37a62052011-08-10 21:25:34 +0000541 LiveIntervals &LIS, MachineDominatorTree &MDT,
Eric Christopher6a0c6792012-03-15 21:33:39 +0000542 UserValueScopes &UVS) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000543 SmallVector<SlotIndex, 16> Todo;
544 Todo.push_back(Idx);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000545 do {
546 SlotIndex Start = Todo.pop_back_val();
547 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
548 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
Jakob Stoklund Olesen2ffee662011-01-12 23:14:04 +0000549 LocMap::iterator I = locInts.find(Start);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000550
551 // Limit to VNI's live range.
552 bool ToEnd = true;
Matthias Braun34e1be92013-10-10 21:29:02 +0000553 if (LR && VNI) {
554 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000555 if (!Segment || Segment->valno != VNI) {
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000556 if (Kills)
557 Kills->push_back(Start);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000558 continue;
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000559 }
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000560 if (Segment->end < Stop)
561 Stop = Segment->end, ToEnd = false;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000562 }
563
564 // There could already be a short def at Start.
565 if (I.valid() && I.start() <= Start) {
566 // Stop when meeting a different location or an already extended interval.
567 Start = Start.getNextSlot();
568 if (I.value() != LocNo || I.stop() != Start)
569 continue;
570 // This is a one-slot placeholder. Just skip it.
571 ++I;
572 }
573
574 // Limited by the next def.
575 if (I.valid() && I.start() < Stop)
576 Stop = I.start(), ToEnd = false;
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000577 // Limited by VNI's live range.
578 else if (!ToEnd && Kills)
579 Kills->push_back(Stop);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000580
581 if (Start >= Stop)
582 continue;
583
584 I.insert(Start, Stop, LocNo);
585
586 // If we extended to the MBB end, propagate down the dominator tree.
587 if (!ToEnd)
588 continue;
589 const std::vector<MachineDomTreeNode*> &Children =
590 MDT.getNode(MBB)->getChildren();
Devang Patel37a62052011-08-10 21:25:34 +0000591 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
592 MachineBasicBlock *MBB = Children[i]->getBlock();
Devang Patelf9e2ae92011-09-13 18:40:53 +0000593 if (UVS.dominates(MBB))
Devang Patel37a62052011-08-10 21:25:34 +0000594 Todo.push_back(LIS.getMBBStartIdx(MBB));
595 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000596 } while (!Todo.empty());
597}
598
599void
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000600UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
601 const SmallVectorImpl<SlotIndex> &Kills,
602 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
603 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
604 if (Kills.empty())
605 return;
606 // Don't track copies from physregs, there are too many uses.
607 if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
608 return;
609
610 // Collect all the (vreg, valno) pairs that are copies of LI.
611 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
Owen Andersonb36376e2014-03-17 19:36:09 +0000612 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
613 MachineInstr *MI = MO.getParent();
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000614 // Copies of the full value.
Owen Andersonb36376e2014-03-17 19:36:09 +0000615 if (MO.getSubReg() || !MI->isCopy())
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000616 continue;
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000617 unsigned DstReg = MI->getOperand(0).getReg();
618
Jakob Stoklund Olesenec0ac3c2011-03-22 22:33:08 +0000619 // Don't follow copies to physregs. These are usually setting up call
620 // arguments, and the argument registers are always call clobbered. We are
621 // better off in the source register which could be a callee-saved register,
622 // or it could be spilled.
623 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
624 continue;
625
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000626 // Is LocNo extended to reach this copy? If not, another def may be blocking
627 // it, or we are looking at a wrong value of LI.
628 SlotIndex Idx = LIS.getInstructionIndex(MI);
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000629 LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000630 if (!I.valid() || I.value() != LocNo)
631 continue;
632
633 if (!LIS.hasInterval(DstReg))
634 continue;
635 LiveInterval *DstLI = &LIS.getInterval(DstReg);
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000636 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
637 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000638 CopyValues.push_back(std::make_pair(DstLI, DstVNI));
639 }
640
641 if (CopyValues.empty())
642 return;
643
644 DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
645
646 // Try to add defs of the copied values for each kill point.
647 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
648 SlotIndex Idx = Kills[i];
649 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
650 LiveInterval *DstLI = CopyValues[j].first;
651 const VNInfo *DstVNI = CopyValues[j].second;
652 if (DstLI->getVNInfoAt(Idx) != DstVNI)
653 continue;
654 // Check that there isn't already a def at Idx
655 LocMap::iterator I = locInts.find(Idx);
656 if (I.valid() && I.start() <= Idx)
657 continue;
658 DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
659 << DstVNI->id << " in " << *DstLI << '\n');
660 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
661 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
662 unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
663 I.insert(Idx, Idx.getNextSlot(), LocNo);
664 NewDefs.push_back(std::make_pair(Idx, LocNo));
665 break;
666 }
667 }
668}
669
670void
671UserValue::computeIntervals(MachineRegisterInfo &MRI,
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000672 const TargetRegisterInfo &TRI,
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000673 LiveIntervals &LIS,
Devang Patel37a62052011-08-10 21:25:34 +0000674 MachineDominatorTree &MDT,
Eric Christopher6a0c6792012-03-15 21:33:39 +0000675 UserValueScopes &UVS) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000676 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
677
678 // Collect all defs to be extended (Skipping undefs).
679 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
680 if (I.value() != ~0u)
681 Defs.push_back(std::make_pair(I.start(), I.value()));
682
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000683 // Extend all defs, and possibly add new ones along the way.
684 for (unsigned i = 0; i != Defs.size(); ++i) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000685 SlotIndex Idx = Defs[i].first;
686 unsigned LocNo = Defs[i].second;
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000687 const MachineOperand &Loc = locations[LocNo];
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000688
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000689 if (!Loc.isReg()) {
Craig Topperc0196b12014-04-14 00:51:57 +0000690 extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS, MDT, UVS);
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000691 continue;
692 }
693
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000694 // Register locations are constrained to where the register value is live.
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000695 if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
Craig Topperc0196b12014-04-14 00:51:57 +0000696 LiveInterval *LI = nullptr;
697 const VNInfo *VNI = nullptr;
Jakob Stoklund Olesen48a16472012-06-22 18:51:35 +0000698 if (LIS.hasInterval(Loc.getReg())) {
699 LI = &LIS.getInterval(Loc.getReg());
700 VNI = LI->getVNInfoAt(Idx);
701 }
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000702 SmallVector<SlotIndex, 16> Kills;
Devang Patelf9e2ae92011-09-13 18:40:53 +0000703 extendDef(Idx, LocNo, LI, VNI, &Kills, LIS, MDT, UVS);
Jakob Stoklund Olesen48a16472012-06-22 18:51:35 +0000704 if (LI)
705 addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000706 continue;
707 }
708
709 // For physregs, use the live range of the first regunit as a guide.
710 unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
Matthias Braun34e1be92013-10-10 21:29:02 +0000711 LiveRange *LR = &LIS.getRegUnit(Unit);
712 const VNInfo *VNI = LR->getVNInfoAt(Idx);
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000713 // Don't track copies from physregs, it is too expensive.
Craig Topperc0196b12014-04-14 00:51:57 +0000714 extendDef(Idx, LocNo, LR, VNI, nullptr, LIS, MDT, UVS);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000715 }
716
717 // Finally, erase all the undefs.
718 for (LocMap::iterator I = locInts.begin(); I.valid();)
719 if (I.value() == ~0u)
720 I.erase();
721 else
722 ++I;
723}
724
725void LDVImpl::computeIntervals() {
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000726 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
Devang Patelf9e2ae92011-09-13 18:40:53 +0000727 UserValueScopes UVS(userValues[i]->getDebugLoc(), LS);
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000728 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, *MDT, UVS);
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000729 userValues[i]->mapVirtRegs(this);
730 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000731}
732
733bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
David Blaikie2f040112014-07-25 16:10:16 +0000734 clear();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000735 MF = &mf;
736 LIS = &pass.getAnalysis<LiveIntervals>();
737 MDT = &pass.getAnalysis<MachineDominatorTree>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000738 TRI = mf.getSubtarget().getRegisterInfo();
Devang Patel37a62052011-08-10 21:25:34 +0000739 LS.initialize(mf);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000740 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
David Blaikiec8c29202012-08-22 17:18:53 +0000741 << mf.getName() << " **********\n");
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000742
743 bool Changed = collectDebugValues(mf);
744 computeIntervals();
745 DEBUG(print(dbgs()));
Manman Ren7a4c8a72013-02-13 20:23:48 +0000746 ModifiedMF = Changed;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000747 return Changed;
748}
749
David Blaikie2f040112014-07-25 16:10:16 +0000750static void removeDebugValues(MachineFunction &mf) {
751 for (MachineBasicBlock &MBB : mf) {
752 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
753 if (!MBBI->isDebugValue()) {
754 ++MBBI;
755 continue;
756 }
757 MBBI = MBB.erase(MBBI);
758 }
759 }
760}
761
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +0000762bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
Devang Patelacbee0b2011-01-07 22:33:41 +0000763 if (!EnableLDV)
764 return false;
David Blaikie2f040112014-07-25 16:10:16 +0000765 if (!FunctionDIs.count(mf.getFunction())) {
766 removeDebugValues(mf);
767 return false;
768 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000769 if (!pImpl)
770 pImpl = new LDVImpl(this);
Manman Ren7a4c8a72013-02-13 20:23:48 +0000771 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000772}
773
774void LiveDebugVariables::releaseMemory() {
Manman Ren7a4c8a72013-02-13 20:23:48 +0000775 if (pImpl)
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000776 static_cast<LDVImpl*>(pImpl)->clear();
777}
778
779LiveDebugVariables::~LiveDebugVariables() {
780 if (pImpl)
781 delete static_cast<LDVImpl*>(pImpl);
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +0000782}
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000783
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000784//===----------------------------------------------------------------------===//
785// Live Range Splitting
786//===----------------------------------------------------------------------===//
787
788bool
Mark Laceyf9ea8852013-08-14 23:50:04 +0000789UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
790 LiveIntervals& LIS) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000791 DEBUG({
792 dbgs() << "Splitting Loc" << OldLocNo << '\t';
Craig Topperc0196b12014-04-14 00:51:57 +0000793 print(dbgs(), nullptr);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000794 });
795 bool DidChange = false;
796 LocMap::iterator LocMapI;
797 LocMapI.setMap(locInts);
798 for (unsigned i = 0; i != NewRegs.size(); ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000799 LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000800 if (LI->empty())
801 continue;
802
803 // Don't allocate the new LocNo until it is needed.
804 unsigned NewLocNo = ~0u;
805
806 // Iterate over the overlaps between locInts and LI.
807 LocMapI.find(LI->beginIndex());
808 if (!LocMapI.valid())
809 continue;
810 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
811 LiveInterval::iterator LIE = LI->end();
812 while (LocMapI.valid() && LII != LIE) {
813 // At this point, we know that LocMapI.stop() > LII->start.
814 LII = LI->advanceTo(LII, LocMapI.start());
815 if (LII == LIE)
816 break;
817
818 // Now LII->end > LocMapI.start(). Do we have an overlap?
819 if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
820 // Overlapping correct location. Allocate NewLocNo now.
821 if (NewLocNo == ~0u) {
822 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
823 MO.setSubReg(locations[OldLocNo].getSubReg());
824 NewLocNo = getLocationNo(MO);
825 DidChange = true;
826 }
827
828 SlotIndex LStart = LocMapI.start();
829 SlotIndex LStop = LocMapI.stop();
830
831 // Trim LocMapI down to the LII overlap.
832 if (LStart < LII->start)
833 LocMapI.setStartUnchecked(LII->start);
834 if (LStop > LII->end)
835 LocMapI.setStopUnchecked(LII->end);
836
837 // Change the value in the overlap. This may trigger coalescing.
838 LocMapI.setValue(NewLocNo);
839
840 // Re-insert any removed OldLocNo ranges.
841 if (LStart < LocMapI.start()) {
842 LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
843 ++LocMapI;
844 assert(LocMapI.valid() && "Unexpected coalescing");
845 }
846 if (LStop > LocMapI.stop()) {
847 ++LocMapI;
848 LocMapI.insert(LII->end, LStop, OldLocNo);
849 --LocMapI;
850 }
851 }
852
853 // Advance to the next overlap.
854 if (LII->end < LocMapI.stop()) {
855 if (++LII == LIE)
856 break;
857 LocMapI.advanceTo(LII->start);
858 } else {
859 ++LocMapI;
860 if (!LocMapI.valid())
861 break;
862 LII = LI->advanceTo(LII, LocMapI.start());
863 }
864 }
865 }
866
867 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
868 locations.erase(locations.begin() + OldLocNo);
869 LocMapI.goToBegin();
870 while (LocMapI.valid()) {
871 unsigned v = LocMapI.value();
872 if (v == OldLocNo) {
873 DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
874 << LocMapI.stop() << ")\n");
875 LocMapI.erase();
876 } else {
877 if (v > OldLocNo)
878 LocMapI.setValueUnchecked(v-1);
879 ++LocMapI;
880 }
881 }
882
Craig Topperc0196b12014-04-14 00:51:57 +0000883 DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000884 return DidChange;
885}
886
887bool
Mark Laceyf9ea8852013-08-14 23:50:04 +0000888UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
889 LiveIntervals &LIS) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000890 bool DidChange = false;
Jakob Stoklund Olesen57c8f582011-05-06 19:31:19 +0000891 // Split locations referring to OldReg. Iterate backwards so splitLocation can
Eric Christopherbe153e62012-03-15 21:33:35 +0000892 // safely erase unused locations.
Jakob Stoklund Olesen57c8f582011-05-06 19:31:19 +0000893 for (unsigned i = locations.size(); i ; --i) {
894 unsigned LocNo = i-1;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000895 const MachineOperand *Loc = &locations[LocNo];
896 if (!Loc->isReg() || Loc->getReg() != OldReg)
897 continue;
Mark Laceyf9ea8852013-08-14 23:50:04 +0000898 DidChange |= splitLocation(LocNo, NewRegs, LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000899 }
900 return DidChange;
901}
902
Mark Laceyf9ea8852013-08-14 23:50:04 +0000903void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000904 bool DidChange = false;
905 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
Mark Laceyf9ea8852013-08-14 23:50:04 +0000906 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000907
908 if (!DidChange)
909 return;
910
911 // Map all of the new virtual registers.
912 UserValue *UV = lookupVirtReg(OldReg);
913 for (unsigned i = 0; i != NewRegs.size(); ++i)
Mark Laceyf9ea8852013-08-14 23:50:04 +0000914 mapVirtReg(NewRegs[i], UV);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000915}
916
917void LiveDebugVariables::
Mark Laceyf9ea8852013-08-14 23:50:04 +0000918splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000919 if (pImpl)
920 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
921}
922
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000923void
924UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
925 // Iterate over locations in reverse makes it easier to handle coalescing.
926 for (unsigned i = locations.size(); i ; --i) {
927 unsigned LocNo = i-1;
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000928 MachineOperand &Loc = locations[LocNo];
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000929 // Only virtual registers are rewritten.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000930 if (!Loc.isReg() || !Loc.getReg() ||
931 !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000932 continue;
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000933 unsigned VirtReg = Loc.getReg();
Jakob Stoklund Olesen1a3534a2011-01-12 22:37:49 +0000934 if (VRM.isAssignedReg(VirtReg) &&
935 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
Jakob Stoklund Olesen89bd2ae2011-05-08 19:21:08 +0000936 // This can create a %noreg operand in rare cases when the sub-register
937 // index is no longer available. That means the user value is in a
938 // non-existent sub-register, and %noreg is exactly what we want.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000939 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
Jakob Stoklund Olesen28df7ef2011-11-13 01:23:30 +0000940 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000941 // FIXME: Translate SubIdx to a stackslot offset.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000942 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000943 } else {
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000944 Loc.setReg(0);
945 Loc.setSubReg(0);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000946 }
Jakob Stoklund Olesen44086032010-12-03 22:25:07 +0000947 coalesceLocation(LocNo);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000948 }
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000949}
950
Devang Patel26ffa012011-02-04 01:43:25 +0000951/// findInsertLocation - Find an iterator for inserting a DBG_VALUE
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000952/// instruction.
953static MachineBasicBlock::iterator
Devang Patel26ffa012011-02-04 01:43:25 +0000954findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000955 LiveIntervals &LIS) {
956 SlotIndex Start = LIS.getMBBStartIdx(MBB);
957 Idx = Idx.getBaseIndex();
958
959 // Try to find an insert location by going backwards from Idx.
960 MachineInstr *MI;
961 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
962 // We've reached the beginning of MBB.
963 if (Idx == Start) {
964 MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000965 return I;
966 }
967 Idx = Idx.getPrevIndex();
968 }
Devang Patel26ffa012011-02-04 01:43:25 +0000969
Jakob Stoklund Olesen088b30a2011-01-13 23:35:53 +0000970 // Don't insert anything after the first terminator, though.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000971 return MI->isTerminator() ? MBB->getFirstTerminator() :
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000972 std::next(MachineBasicBlock::iterator(MI));
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000973}
974
975void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
976 unsigned LocNo,
977 LiveIntervals &LIS,
978 const TargetInstrInfo &TII) {
Devang Patel26ffa012011-02-04 01:43:25 +0000979 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000980 MachineOperand &Loc = locations[LocNo];
Devang Pateleabc3cea2011-08-04 20:42:11 +0000981 ++NumInsertedDebugValues;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000982
Duncan P. N. Exon Smithe686f152015-04-06 23:27:40 +0000983 assert(cast<MDLocalVariable>(Variable)
984 ->isValidLocationForIntrinsic(getDebugLoc()) &&
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +0000985 "Expected inlined-at fields to agree");
Adrian Prantl418d1d12013-07-09 20:28:37 +0000986 if (Loc.isReg())
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +0000987 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000988 IsIndirect, Loc.getReg(), offset, Variable, Expression);
Adrian Prantl418d1d12013-07-09 20:28:37 +0000989 else
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +0000990 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000991 .addOperand(Loc)
992 .addImm(offset)
993 .addMetadata(Variable)
994 .addMetadata(Expression);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000995}
996
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000997void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
998 const TargetInstrInfo &TII) {
999 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1000
1001 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1002 SlotIndex Start = I.start();
1003 SlotIndex Stop = I.stop();
1004 unsigned LocNo = I.value();
1005 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
1006 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
1007 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
1008
1009 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
1010 insertDebugValue(MBB, Start, LocNo, LIS, TII);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001011 // This interval may span multiple basic blocks.
1012 // Insert a DBG_VALUE into each one.
1013 while(Stop > MBBEnd) {
1014 // Move to the next block.
1015 Start = MBBEnd;
1016 if (++MBB == MFEnd)
1017 break;
1018 MBBEnd = LIS.getMBBEndIdx(MBB);
1019 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
1020 insertDebugValue(MBB, Start, LocNo, LIS, TII);
1021 }
1022 DEBUG(dbgs() << '\n');
1023 if (MBB == MFEnd)
1024 break;
1025
1026 ++I;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001027 }
1028}
1029
1030void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1031 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
David Blaikie2f040112014-07-25 16:10:16 +00001032 if (!MF)
1033 return;
Eric Christopherfc6de422014-08-05 02:39:49 +00001034 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001035 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
Eric Christopher1cdefae2015-02-27 00:11:34 +00001036 DEBUG(userValues[i]->print(dbgs(), TRI));
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001037 userValues[i]->rewriteLocations(*VRM, *TRI);
1038 userValues[i]->emitDebugValues(VRM, *LIS, *TII);
1039 }
Manman Ren7a4c8a72013-02-13 20:23:48 +00001040 EmitDone = true;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001041}
1042
1043void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
Manman Ren7a4c8a72013-02-13 20:23:48 +00001044 if (pImpl)
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001045 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1046}
1047
David Blaikie2f040112014-07-25 16:10:16 +00001048bool LiveDebugVariables::doInitialization(Module &M) {
1049 FunctionDIs = makeSubprogramMap(M);
1050 return Pass::doInitialization(M);
1051}
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001052
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +00001053#ifndef NDEBUG
1054void LiveDebugVariables::dump() {
1055 if (pImpl)
1056 static_cast<LDVImpl*>(pImpl)->print(dbgs());
1057}
1058#endif