blob: 033394fb0f5bb4e9643906961a4adb5263856d91 [file] [log] [blame]
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001//===- LiveDebugValues.cpp - Tracking Debug Value MIs ---------------------===//
Vikram TV859ad292015-12-16 11:09:48 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Vikram TV859ad292015-12-16 11:09:48 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// This pass implements a data flow analysis that propagates debug location
Jeremy Morse67443c32019-08-21 09:22:31 +000010/// information by inserting additional DBG_VALUE insts into the machine
11/// instruction stream. Before running, each DBG_VALUE inst corresponds to a
12/// source assignment of a variable. Afterwards, a DBG_VALUE inst specifies a
13/// variable location for the current basic block (see SourceLevelDebugging.rst).
Vikram TV859ad292015-12-16 11:09:48 +000014///
15/// This is a separate pass from DbgValueHistoryCalculator to facilitate
16/// testing and improve modularity.
17///
Jeremy Morse67443c32019-08-21 09:22:31 +000018/// Each variable location is represented by a VarLoc object that identifies the
19/// source variable, its current machine-location, and the DBG_VALUE inst that
20/// specifies the location. Each VarLoc is indexed in the (function-scope)
21/// VarLocMap, giving each VarLoc a unique index. Rather than operate directly
22/// on machine locations, the dataflow analysis in this pass identifies
23/// locations by their index in the VarLocMap, meaning all the variable
24/// locations in a block can be described by a sparse vector of VarLocMap
25/// indexes.
26///
Vikram TV859ad292015-12-16 11:09:48 +000027//===----------------------------------------------------------------------===//
28
Eugene Zelenko5df3d892017-08-24 21:21:39 +000029#include "llvm/ADT/DenseMap.h"
Daniel Berlin72560592016-01-10 18:08:32 +000030#include "llvm/ADT/PostOrderIterator.h"
31#include "llvm/ADT/SmallPtrSet.h"
Jeremy Morsebf2b2f02019-06-13 12:51:57 +000032#include "llvm/ADT/SmallSet.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000033#include "llvm/ADT/SmallVector.h"
Adrian Prantl6ee02c72016-05-25 22:21:12 +000034#include "llvm/ADT/SparseBitVector.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000035#include "llvm/ADT/Statistic.h"
Adrian Prantl6ee02c72016-05-25 22:21:12 +000036#include "llvm/ADT/UniqueVector.h"
Adrian Prantl7f5866c2016-09-28 17:51:14 +000037#include "llvm/CodeGen/LexicalScopes.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000038#include "llvm/CodeGen/MachineBasicBlock.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000039#include "llvm/CodeGen/MachineFrameInfo.h"
Vikram TV859ad292015-12-16 11:09:48 +000040#include "llvm/CodeGen/MachineFunction.h"
41#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000042#include "llvm/CodeGen/MachineInstr.h"
Vikram TV859ad292015-12-16 11:09:48 +000043#include "llvm/CodeGen/MachineInstrBuilder.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000044#include "llvm/CodeGen/MachineMemOperand.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000045#include "llvm/CodeGen/MachineOperand.h"
46#include "llvm/CodeGen/PseudoSourceValue.h"
Wolfgang Pieb90d856c2019-02-04 20:42:45 +000047#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000048#include "llvm/CodeGen/TargetFrameLowering.h"
49#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000050#include "llvm/CodeGen/TargetLowering.h"
Djordje Todorovic12aca5d2019-07-09 08:36:34 +000051#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000052#include "llvm/CodeGen/TargetRegisterInfo.h"
53#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000054#include "llvm/Config/llvm-config.h"
Wolfgang Pieb90d856c2019-02-04 20:42:45 +000055#include "llvm/IR/DIBuilder.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000056#include "llvm/IR/DebugInfoMetadata.h"
57#include "llvm/IR/DebugLoc.h"
58#include "llvm/IR/Function.h"
59#include "llvm/IR/Module.h"
60#include "llvm/MC/MCRegisterInfo.h"
61#include "llvm/Pass.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/Compiler.h"
Vikram TV859ad292015-12-16 11:09:48 +000064#include "llvm/Support/Debug.h"
65#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000066#include <algorithm>
67#include <cassert>
68#include <cstdint>
69#include <functional>
Mehdi Aminib550cb12016-04-18 09:17:29 +000070#include <queue>
Jeremy Morsebf2b2f02019-06-13 12:51:57 +000071#include <tuple>
Eugene Zelenko5df3d892017-08-24 21:21:39 +000072#include <utility>
73#include <vector>
Vikram TV859ad292015-12-16 11:09:48 +000074
75using namespace llvm;
76
Matthias Braun1527baa2017-05-25 21:26:32 +000077#define DEBUG_TYPE "livedebugvalues"
Vikram TV859ad292015-12-16 11:09:48 +000078
79STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
80
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000081// If @MI is a DBG_VALUE with debug value described by a defined
Adrian Prantl6ee02c72016-05-25 22:21:12 +000082// register, returns the number of this register. In the other case, returns 0.
Matt Arsenaulte3a676e2019-06-24 15:50:29 +000083static Register isDbgValueDescribedByReg(const MachineInstr &MI) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +000084 assert(MI.isDebugValue() && "expected a DBG_VALUE");
85 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
86 // If location of variable is described using a register (directly
87 // or indirectly), this register is always a first operand.
Matt Arsenaulte3a676e2019-06-24 15:50:29 +000088 return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : Register();
Adrian Prantl6ee02c72016-05-25 22:21:12 +000089}
90
Eugene Zelenko5df3d892017-08-24 21:21:39 +000091namespace {
Vikram TV859ad292015-12-16 11:09:48 +000092
Eugene Zelenko5df3d892017-08-24 21:21:39 +000093class LiveDebugValues : public MachineFunctionPass {
Vikram TV859ad292015-12-16 11:09:48 +000094private:
95 const TargetRegisterInfo *TRI;
96 const TargetInstrInfo *TII;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000097 const TargetFrameLowering *TFI;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +000098 BitVector CalleeSavedRegs;
Adrian Prantl7f5866c2016-09-28 17:51:14 +000099 LexicalScopes LS;
100
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000101 enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
102
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000103 /// Keeps track of lexical scopes associated with a user value's source
104 /// location.
105 class UserValueScopes {
106 DebugLoc DL;
107 LexicalScopes &LS;
108 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
109
110 public:
111 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
112
113 /// Return true if current scope dominates at least one machine
114 /// instruction in a given machine basic block.
115 bool dominates(MachineBasicBlock *MBB) {
116 if (LBlocks.empty())
117 LS.getMachineBasicBlocks(DL, LBlocks);
118 return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
119 }
120 };
Vikram TV859ad292015-12-16 11:09:48 +0000121
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000122 using FragmentInfo = DIExpression::FragmentInfo;
123 using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
Vikram TV859ad292015-12-16 11:09:48 +0000124
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000125 /// Storage for identifying a potentially inlined instance of a variable,
126 /// or a fragment thereof.
127 class DebugVariable {
128 const DILocalVariable *Variable;
129 OptFragmentInfo Fragment;
130 const DILocation *InlinedAt;
Vikram TV859ad292015-12-16 11:09:48 +0000131
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000132 /// Fragment that will overlap all other fragments. Used as default when
133 /// caller demands a fragment.
134 static const FragmentInfo DefaultFragment;
135
136 public:
137 DebugVariable(const DILocalVariable *Var, OptFragmentInfo &&FragmentInfo,
138 const DILocation *InlinedAt)
139 : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
140
141 DebugVariable(const DILocalVariable *Var, OptFragmentInfo &FragmentInfo,
142 const DILocation *InlinedAt)
143 : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
144
145 DebugVariable(const DILocalVariable *Var, const DIExpression *DIExpr,
146 const DILocation *InlinedAt)
147 : DebugVariable(Var, DIExpr->getFragmentInfo(), InlinedAt) {}
148
149 DebugVariable(const MachineInstr &MI)
150 : DebugVariable(MI.getDebugVariable(),
151 MI.getDebugExpression()->getFragmentInfo(),
152 MI.getDebugLoc()->getInlinedAt()) {}
153
154 const DILocalVariable *getVar() const { return Variable; }
155 const OptFragmentInfo &getFragment() const { return Fragment; }
156 const DILocation *getInlinedAt() const { return InlinedAt; }
157
158 const FragmentInfo getFragmentDefault() const {
159 return Fragment.getValueOr(DefaultFragment);
160 }
161
162 static bool isFragmentDefault(FragmentInfo &F) {
163 return F == DefaultFragment;
164 }
165
166 bool operator==(const DebugVariable &Other) const {
167 return std::tie(Variable, Fragment, InlinedAt) ==
168 std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
169 }
170
171 bool operator<(const DebugVariable &Other) const {
172 return std::tie(Variable, Fragment, InlinedAt) <
173 std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
Vikram TV859ad292015-12-16 11:09:48 +0000174 }
175 };
176
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000177 friend struct llvm::DenseMapInfo<DebugVariable>;
178
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000179 /// A pair of debug variable and value location.
Vikram TV859ad292015-12-16 11:09:48 +0000180 struct VarLoc {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000181 // The location at which a spilled variable resides. It consists of a
182 // register and an offset.
183 struct SpillLoc {
184 unsigned SpillBase;
185 int SpillOffset;
186 bool operator==(const SpillLoc &Other) const {
187 return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
188 }
189 };
190
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000191 const DebugVariable Var;
192 const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000193 mutable UserValueScopes UVS;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000194 enum VarLocKind {
195 InvalidKind = 0,
196 RegisterKind,
Jeremy Morsebcff4172019-06-10 15:23:46 +0000197 SpillLocKind,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000198 ImmediateKind,
199 EntryValueKind
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000200 } Kind = InvalidKind;
Vikram TV859ad292015-12-16 11:09:48 +0000201
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000202 /// The value location. Stored separately to avoid repeatedly
203 /// extracting it from MI.
204 union {
Adrian Prantl359846f2017-07-28 23:25:51 +0000205 uint64_t RegNo;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000206 SpillLoc SpillLocation;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000207 uint64_t Hash;
Jeremy Morsebcff4172019-06-10 15:23:46 +0000208 int64_t Immediate;
209 const ConstantFP *FPImm;
210 const ConstantInt *CImm;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000211 } Loc;
212
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000213 VarLoc(const MachineInstr &MI, LexicalScopes &LS,
214 VarLocKind K = InvalidKind)
215 : Var(MI), MI(MI), UVS(MI.getDebugLoc(), LS){
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000216 static_assert((sizeof(Loc) == sizeof(uint64_t)),
217 "hash does not cover all members of Loc");
218 assert(MI.isDebugValue() && "not a DBG_VALUE");
219 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
Adrian Prantl00698732016-05-25 22:37:29 +0000220 if (int RegNo = isDbgValueDescribedByReg(MI)) {
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000221 Kind = MI.isDebugEntryValue() ? EntryValueKind : RegisterKind;
Adrian Prantl359846f2017-07-28 23:25:51 +0000222 Loc.RegNo = RegNo;
Jeremy Morsebcff4172019-06-10 15:23:46 +0000223 } else if (MI.getOperand(0).isImm()) {
224 Kind = ImmediateKind;
225 Loc.Immediate = MI.getOperand(0).getImm();
226 } else if (MI.getOperand(0).isFPImm()) {
227 Kind = ImmediateKind;
228 Loc.FPImm = MI.getOperand(0).getFPImm();
229 } else if (MI.getOperand(0).isCImm()) {
230 Kind = ImmediateKind;
231 Loc.CImm = MI.getOperand(0).getCImm();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000232 }
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000233 assert((Kind != ImmediateKind || !MI.isDebugEntryValue()) &&
234 "entry values must be register locations");
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000235 }
236
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000237 /// The constructor for spill locations.
238 VarLoc(const MachineInstr &MI, unsigned SpillBase, int SpillOffset,
Jeremy Morse8b593482019-08-16 10:04:17 +0000239 LexicalScopes &LS, const MachineInstr &OrigMI)
240 : Var(MI), MI(OrigMI), UVS(MI.getDebugLoc(), LS) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000241 assert(MI.isDebugValue() && "not a DBG_VALUE");
242 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
243 Kind = SpillLocKind;
244 Loc.SpillLocation = {SpillBase, SpillOffset};
245 }
246
Jeremy Morsebcff4172019-06-10 15:23:46 +0000247 // Is the Loc field a constant or constant object?
248 bool isConstant() const { return Kind == ImmediateKind; }
249
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000250 /// If this variable is described by a register, return it,
251 /// otherwise return 0.
252 unsigned isDescribedByReg() const {
253 if (Kind == RegisterKind)
Adrian Prantl359846f2017-07-28 23:25:51 +0000254 return Loc.RegNo;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000255 return 0;
256 }
257
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000258 /// Determine whether the lexical scope of this value's debug location
259 /// dominates MBB.
260 bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
261
Aaron Ballman615eb472017-10-15 14:32:27 +0000262#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun194ded52017-01-28 06:53:55 +0000263 LLVM_DUMP_METHOD void dump() const { MI.dump(); }
264#endif
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000265
266 bool operator==(const VarLoc &Other) const {
Jeremy Morsebcff4172019-06-10 15:23:46 +0000267 return Kind == Other.Kind && Var == Other.Var &&
268 Loc.Hash == Other.Loc.Hash;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000269 }
270
Adrian Prantl7509d542016-05-26 21:42:47 +0000271 /// This operator guarantees that VarLocs are sorted by Variable first.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000272 bool operator<(const VarLoc &Other) const {
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000273 return std::tie(Var, Kind, Loc.Hash) <
274 std::tie(Other.Var, Other.Kind, Other.Loc.Hash);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000275 }
Vikram TV859ad292015-12-16 11:09:48 +0000276 };
277
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000278 using DebugParamMap = SmallDenseMap<const DILocalVariable *, MachineInstr *>;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000279 using VarLocMap = UniqueVector<VarLoc>;
280 using VarLocSet = SparseBitVector<>;
281 using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000282 struct TransferDebugPair {
283 MachineInstr *TransferInst;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000284 MachineInstr *DebugInst;
285 };
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000286 using TransferMap = SmallVector<TransferDebugPair, 4>;
Vikram TV859ad292015-12-16 11:09:48 +0000287
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000288 // Types for recording sets of variable fragments that overlap. For a given
289 // local variable, we record all other fragments of that variable that could
290 // overlap it, to reduce search time.
291 using FragmentOfVar =
292 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
293 using OverlapMap =
294 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
295
296 // Helper while building OverlapMap, a map of all fragments seen for a given
297 // DILocalVariable.
298 using VarToFragments =
299 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
300
Adrian Prantl7509d542016-05-26 21:42:47 +0000301 /// This holds the working set of currently open ranges. For fast
302 /// access, this is done both as a set of VarLocIDs, and a map of
303 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
304 /// previous open ranges for the same variable.
305 class OpenRangesSet {
306 VarLocSet VarLocs;
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000307 SmallDenseMap<DebugVariable, unsigned, 8> Vars;
308 OverlapMap &OverlappingFragments;
Adrian Prantl7509d542016-05-26 21:42:47 +0000309
310 public:
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000311 OpenRangesSet(OverlapMap &_OLapMap) : OverlappingFragments(_OLapMap) {}
312
Adrian Prantl7509d542016-05-26 21:42:47 +0000313 const VarLocSet &getVarLocs() const { return VarLocs; }
314
315 /// Terminate all open ranges for Var by removing it from the set.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000316 void erase(DebugVariable Var);
Adrian Prantl7509d542016-05-26 21:42:47 +0000317
318 /// Terminate all open ranges listed in \c KillSet by removing
319 /// them from the set.
320 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
321 VarLocs.intersectWithComplement(KillSet);
322 for (unsigned ID : KillSet)
323 Vars.erase(VarLocIDs[ID].Var);
324 }
325
326 /// Insert a new range into the set.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000327 void insert(unsigned VarLocID, DebugVariable Var) {
Adrian Prantl7509d542016-05-26 21:42:47 +0000328 VarLocs.set(VarLocID);
329 Vars.insert({Var, VarLocID});
330 }
331
Jeremy Morse67443c32019-08-21 09:22:31 +0000332 /// Insert a set of ranges.
333 void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map) {
334 for (unsigned Id : ToLoad) {
335 const VarLoc &Var = Map[Id];
336 insert(Id, Var.Var);
337 }
338 }
339
Adrian Prantl7509d542016-05-26 21:42:47 +0000340 /// Empty the set.
341 void clear() {
342 VarLocs.clear();
343 Vars.clear();
344 }
345
346 /// Return whether the set is empty or not.
347 bool empty() const {
348 assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
349 return VarLocs.empty();
350 }
351 };
352
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000353 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
354 unsigned &Reg);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000355 /// If a given instruction is identified as a spill, return the spill location
356 /// and set \p Reg to the spilled register.
357 Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
358 MachineFunction *MF,
359 unsigned &Reg);
360 /// Given a spill instruction, extract the register and offset used to
361 /// address the spill location in a target independent way.
362 VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000363 void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
364 TransferMap &Transfers, VarLocMap &VarLocIDs,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000365 unsigned OldVarID, TransferKind Kind,
366 unsigned NewReg = 0);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000367
Adrian Prantl7509d542016-05-26 21:42:47 +0000368 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000369 VarLocMap &VarLocIDs);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000370 void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
371 VarLocMap &VarLocIDs, TransferMap &Transfers);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000372 void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
373 VarLocMap &VarLocIDs, TransferMap &Transfers,
374 DebugParamMap &DebugEntryVals,
375 SparseBitVector<> &KillSet);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000376 void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
377 VarLocMap &VarLocIDs, TransferMap &Transfers);
Adrian Prantl7509d542016-05-26 21:42:47 +0000378 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000379 VarLocMap &VarLocIDs, TransferMap &Transfers,
380 DebugParamMap &DebugEntryVals);
Jeremy Morse67443c32019-08-21 09:22:31 +0000381 bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges,
382 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
Nikola Prica441ad622019-05-27 13:51:30 +0000383
Jeremy Morse67443c32019-08-21 09:22:31 +0000384 void process(MachineInstr &MI, OpenRangesSet &OpenRanges,
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000385 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000386 TransferMap &Transfers, DebugParamMap &DebugEntryVals,
387 bool transferChanges, OverlapMap &OverlapFragments,
388 VarToFragments &SeenFragments);
Vikram TV859ad292015-12-16 11:09:48 +0000389
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000390 void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
391 OverlapMap &OLapMap);
392
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000393 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
Keith Walker83ebef52016-09-27 16:46:07 +0000394 const VarLocMap &VarLocIDs,
Vedant Kumar8c466682018-10-05 21:44:15 +0000395 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
Jeremy Morse67443c32019-08-21 09:22:31 +0000396 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks,
397 VarLocInMBB &PendingInLocs);
398
399 /// Create DBG_VALUE insts for inlocs that have been propagated but
400 /// had their instruction creation deferred.
401 void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs);
Vikram TV859ad292015-12-16 11:09:48 +0000402
403 bool ExtendRanges(MachineFunction &MF);
404
405public:
406 static char ID;
407
408 /// Default construct and initialize the pass.
409 LiveDebugValues();
410
411 /// Tell the pass manager which passes we depend on and what
412 /// information we preserve.
413 void getAnalysisUsage(AnalysisUsage &AU) const override;
414
Derek Schuffad154c82016-03-28 17:05:30 +0000415 MachineFunctionProperties getRequiredProperties() const override {
416 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000417 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000418 }
419
Vikram TV859ad292015-12-16 11:09:48 +0000420 /// Print to ostream with a message.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000421 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
422 const VarLocMap &VarLocIDs, const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000423 raw_ostream &Out) const;
424
425 /// Calculate the liveness information for the given machine function.
426 bool runOnMachineFunction(MachineFunction &MF) override;
427};
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000428
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000429} // end anonymous namespace
Vikram TV859ad292015-12-16 11:09:48 +0000430
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000431namespace llvm {
432
433template <> struct DenseMapInfo<LiveDebugValues::DebugVariable> {
434 using DV = LiveDebugValues::DebugVariable;
435 using OptFragmentInfo = LiveDebugValues::OptFragmentInfo;
436 using FragmentInfo = LiveDebugValues::FragmentInfo;
437
438 // Empty key: no key should be generated that has no DILocalVariable.
439 static inline DV getEmptyKey() {
440 return DV(nullptr, OptFragmentInfo(), nullptr);
441 }
442
443 // Difference in tombstone is that the Optional is meaningful
444 static inline DV getTombstoneKey() {
445 return DV(nullptr, OptFragmentInfo({0, 0}), nullptr);
446 }
447
448 static unsigned getHashValue(const DV &D) {
449 unsigned HV = 0;
450 const OptFragmentInfo &Fragment = D.getFragment();
451 if (Fragment)
452 HV = DenseMapInfo<FragmentInfo>::getHashValue(*Fragment);
453
454 return hash_combine(D.getVar(), HV, D.getInlinedAt());
455 }
456
457 static bool isEqual(const DV &A, const DV &B) { return A == B; }
458};
459
David Stenberg1278a192019-06-13 14:02:55 +0000460} // namespace llvm
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000461
Vikram TV859ad292015-12-16 11:09:48 +0000462//===----------------------------------------------------------------------===//
463// Implementation
464//===----------------------------------------------------------------------===//
465
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000466const DIExpression::FragmentInfo
467 LiveDebugValues::DebugVariable::DefaultFragment = {
468 std::numeric_limits<uint64_t>::max(),
469 std::numeric_limits<uint64_t>::min()};
470
Vikram TV859ad292015-12-16 11:09:48 +0000471char LiveDebugValues::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000472
Vikram TV859ad292015-12-16 11:09:48 +0000473char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000474
Matthias Braun1527baa2017-05-25 21:26:32 +0000475INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
Vikram TV859ad292015-12-16 11:09:48 +0000476 false, false)
477
478/// Default construct and initialize the pass.
479LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
480 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
481}
482
483/// Tell the pass manager which passes we depend on and what information we
484/// preserve.
485void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
Matt Arsenaultb1630a12016-06-08 05:18:01 +0000486 AU.setPreservesCFG();
Vikram TV859ad292015-12-16 11:09:48 +0000487 MachineFunctionPass::getAnalysisUsage(AU);
488}
489
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000490/// Erase a variable from the set of open ranges, and additionally erase any
491/// fragments that may overlap it.
492void LiveDebugValues::OpenRangesSet::erase(DebugVariable Var) {
493 // Erasure helper.
494 auto DoErase = [this](DebugVariable VarToErase) {
495 auto It = Vars.find(VarToErase);
496 if (It != Vars.end()) {
497 unsigned ID = It->second;
498 VarLocs.reset(ID);
499 Vars.erase(It);
500 }
501 };
502
503 // Erase the variable/fragment that ends here.
504 DoErase(Var);
505
506 // Extract the fragment. Interpret an empty fragment as one that covers all
507 // possible bits.
508 FragmentInfo ThisFragment = Var.getFragmentDefault();
509
510 // There may be fragments that overlap the designated fragment. Look them up
511 // in the pre-computed overlap map, and erase them too.
512 auto MapIt = OverlappingFragments.find({Var.getVar(), ThisFragment});
513 if (MapIt != OverlappingFragments.end()) {
514 for (auto Fragment : MapIt->second) {
515 LiveDebugValues::OptFragmentInfo FragmentHolder;
516 if (!DebugVariable::isFragmentDefault(Fragment))
517 FragmentHolder = LiveDebugValues::OptFragmentInfo(Fragment);
518 DoErase({Var.getVar(), FragmentHolder, Var.getInlinedAt()});
519 }
520 }
521}
522
Vikram TV859ad292015-12-16 11:09:48 +0000523//===----------------------------------------------------------------------===//
524// Debug Range Extension Implementation
525//===----------------------------------------------------------------------===//
526
Matthias Braun194ded52017-01-28 06:53:55 +0000527#ifndef NDEBUG
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000528void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
529 const VarLocInMBB &V,
530 const VarLocMap &VarLocIDs,
531 const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000532 raw_ostream &Out) const {
Keith Walkerf83a19f2016-09-20 16:04:31 +0000533 Out << '\n' << msg << '\n';
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000534 for (const MachineBasicBlock &BB : MF) {
Vedant Kumar9b558382018-10-05 21:44:00 +0000535 const VarLocSet &L = V.lookup(&BB);
536 if (L.empty())
537 continue;
538 Out << "MBB: " << BB.getNumber() << ":\n";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000539 for (unsigned VLL : L) {
540 const VarLoc &VL = VarLocIDs[VLL];
Adrian Prantl7509d542016-05-26 21:42:47 +0000541 Out << " Var: " << VL.Var.getVar()->getName();
Vikram TV859ad292015-12-16 11:09:48 +0000542 Out << " MI: ";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000543 VL.dump();
Vikram TV859ad292015-12-16 11:09:48 +0000544 }
545 }
546 Out << "\n";
547}
Matthias Braun194ded52017-01-28 06:53:55 +0000548#endif
Vikram TV859ad292015-12-16 11:09:48 +0000549
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000550LiveDebugValues::VarLoc::SpillLoc
551LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000552 assert(MI.hasOneMemOperand() &&
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000553 "Spill instruction does not have exactly one memory operand?");
554 auto MMOI = MI.memoperands_begin();
555 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
556 assert(PVal->kind() == PseudoSourceValue::FixedStack &&
557 "Inconsistent memory operand in spill instruction");
558 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
559 const MachineBasicBlock *MBB = MI.getParent();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000560 unsigned Reg;
561 int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
562 return {Reg, Offset};
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000563}
564
Vikram TV859ad292015-12-16 11:09:48 +0000565/// End all previous ranges related to @MI and start a new range from @MI
566/// if it is a DBG_VALUE instr.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000567void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000568 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000569 VarLocMap &VarLocIDs) {
Vikram TV859ad292015-12-16 11:09:48 +0000570 if (!MI.isDebugValue())
571 return;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000572 const DILocalVariable *Var = MI.getDebugVariable();
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000573 const DIExpression *Expr = MI.getDebugExpression();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000574 const DILocation *DebugLoc = MI.getDebugLoc();
575 const DILocation *InlinedAt = DebugLoc->getInlinedAt();
576 assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
Vikram TV859ad292015-12-16 11:09:48 +0000577 "Expected inlined-at fields to agree");
Vikram TV859ad292015-12-16 11:09:48 +0000578
579 // End all previous ranges of Var.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000580 DebugVariable V(Var, Expr, InlinedAt);
Adrian Prantl7509d542016-05-26 21:42:47 +0000581 OpenRanges.erase(V);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000582
583 // Add the VarLoc to OpenRanges from this DBG_VALUE.
Jeremy Morsebcff4172019-06-10 15:23:46 +0000584 unsigned ID;
Djordje Todorovic774eabd2019-06-27 18:12:04 +0000585 if (isDbgValueDescribedByReg(MI) || MI.getOperand(0).isImm() ||
586 MI.getOperand(0).isFPImm() || MI.getOperand(0).isCImm()) {
Jeremy Morsebcff4172019-06-10 15:23:46 +0000587 // Use normal VarLoc constructor for registers and immediates.
Djordje Todorovic774eabd2019-06-27 18:12:04 +0000588 VarLoc VL(MI, LS);
Jeremy Morsebcff4172019-06-10 15:23:46 +0000589 ID = VarLocIDs.insert(VL);
Adrian Prantl7509d542016-05-26 21:42:47 +0000590 OpenRanges.insert(ID, VL.Var);
Jeremy Morsebcff4172019-06-10 15:23:46 +0000591 } else if (MI.hasOneMemOperand()) {
Jeremy Morse8b593482019-08-16 10:04:17 +0000592 llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?");
Jeremy Morsebcff4172019-06-10 15:23:46 +0000593 } else {
594 // This must be an undefined location. We should leave OpenRanges closed.
595 assert(MI.getOperand(0).isReg() && MI.getOperand(0).getReg() == 0 &&
596 "Unexpected non-undef DBG_VALUE encountered");
Adrian Prantl7509d542016-05-26 21:42:47 +0000597 }
Vikram TV859ad292015-12-16 11:09:48 +0000598}
599
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000600void LiveDebugValues::emitEntryValues(MachineInstr &MI,
601 OpenRangesSet &OpenRanges,
602 VarLocMap &VarLocIDs,
603 TransferMap &Transfers,
604 DebugParamMap &DebugEntryVals,
605 SparseBitVector<> &KillSet) {
606 MachineFunction *MF = MI.getParent()->getParent();
607 for (unsigned ID : KillSet) {
608 if (!VarLocIDs[ID].Var.getVar()->isParameter())
609 continue;
610
611 const MachineInstr *CurrDebugInstr = &VarLocIDs[ID].MI;
612
613 // If parameter's DBG_VALUE is not in the map that means we can't
614 // generate parameter's entry value.
615 if (!DebugEntryVals.count(CurrDebugInstr->getDebugVariable()))
616 continue;
617
618 auto ParamDebugInstr = DebugEntryVals[CurrDebugInstr->getDebugVariable()];
619 DIExpression *NewExpr = DIExpression::prepend(
620 ParamDebugInstr->getDebugExpression(), DIExpression::EntryValue);
621 MachineInstr *EntryValDbgMI =
622 BuildMI(*MF, ParamDebugInstr->getDebugLoc(), ParamDebugInstr->getDesc(),
623 ParamDebugInstr->isIndirectDebugValue(),
624 ParamDebugInstr->getOperand(0).getReg(),
625 ParamDebugInstr->getDebugVariable(), NewExpr);
626
627 if (ParamDebugInstr->isIndirectDebugValue())
628 EntryValDbgMI->getOperand(1).setImm(
629 ParamDebugInstr->getOperand(1).getImm());
630
631 Transfers.push_back({&MI, EntryValDbgMI});
632 VarLoc VL(*EntryValDbgMI, LS);
633 unsigned EntryValLocID = VarLocIDs.insert(VL);
634 OpenRanges.insert(EntryValLocID, VL.Var);
635 }
636}
637
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000638/// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
639/// with \p OldVarID should be deleted form \p OpenRanges and replaced with
640/// new VarLoc. If \p NewReg is different than default zero value then the
641/// new location will be register location created by the copy like instruction,
642/// otherwise it is variable's location on the stack.
643void LiveDebugValues::insertTransferDebugPair(
644 MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000645 VarLocMap &VarLocIDs, unsigned OldVarID, TransferKind Kind,
646 unsigned NewReg) {
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000647 const MachineInstr *DebugInstr = &VarLocIDs[OldVarID].MI;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000648 MachineFunction *MF = MI.getParent()->getParent();
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000649 MachineInstr *NewDebugInstr;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000650
Nikola Prica2d0106a2019-06-03 09:48:29 +0000651 auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &DebugInstr,
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000652 &VarLocIDs](VarLoc &VL, MachineInstr *NewDebugInstr) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000653 unsigned LocId = VarLocIDs.insert(VL);
Nikola Prica2d0106a2019-06-03 09:48:29 +0000654
655 // Close this variable's previous location range.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000656 DebugVariable V(*DebugInstr);
Nikola Prica2d0106a2019-06-03 09:48:29 +0000657 OpenRanges.erase(V);
658
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000659 OpenRanges.insert(LocId, VL.Var);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000660 // The newly created DBG_VALUE instruction NewDebugInstr must be inserted
661 // after MI. Keep track of the pairing.
662 TransferDebugPair MIP = {&MI, NewDebugInstr};
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000663 Transfers.push_back(MIP);
664 };
665
666 // End all previous ranges of Var.
667 OpenRanges.erase(VarLocIDs[OldVarID].Var);
668 switch (Kind) {
669 case TransferKind::TransferCopy: {
670 assert(NewReg &&
671 "No register supplied when handling a copy of a debug value");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000672 // Create a DBG_VALUE instruction to describe the Var in its new
673 // register location.
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000674 NewDebugInstr = BuildMI(
675 *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(),
676 DebugInstr->isIndirectDebugValue(), NewReg,
677 DebugInstr->getDebugVariable(), DebugInstr->getDebugExpression());
678 if (DebugInstr->isIndirectDebugValue())
679 NewDebugInstr->getOperand(1).setImm(DebugInstr->getOperand(1).getImm());
680 VarLoc VL(*NewDebugInstr, LS);
681 ProcessVarLoc(VL, NewDebugInstr);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000682 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register copy: ";
Craig Topper78c794a2019-06-02 01:36:48 +0000683 NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
684 /*SkipOpers*/false, /*SkipDebugLoc*/false,
685 /*AddNewLine*/true, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000686 return;
687 }
688 case TransferKind::TransferSpill: {
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000689 // Create a DBG_VALUE instruction to describe the Var in its spilled
690 // location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000691 VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000692 auto *SpillExpr = DIExpression::prepend(DebugInstr->getDebugExpression(),
Petar Jovanovice85bbf52019-05-20 10:35:57 +0000693 DIExpression::ApplyOffset,
694 SpillLocation.SpillOffset);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000695 NewDebugInstr = BuildMI(
696 *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(), true,
697 SpillLocation.SpillBase, DebugInstr->getDebugVariable(), SpillExpr);
698 VarLoc VL(*NewDebugInstr, SpillLocation.SpillBase,
Jeremy Morse8b593482019-08-16 10:04:17 +0000699 SpillLocation.SpillOffset, LS, *DebugInstr);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000700 ProcessVarLoc(VL, NewDebugInstr);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000701 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
Craig Topper78c794a2019-06-02 01:36:48 +0000702 NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
703 /*SkipOpers*/false, /*SkipDebugLoc*/false,
704 /*AddNewLine*/true, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000705 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000706 }
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000707 case TransferKind::TransferRestore: {
708 assert(NewReg &&
709 "No register supplied when handling a restore of a debug value");
710 MachineFunction *MF = MI.getMF();
711 DIBuilder DIB(*const_cast<Function &>(MF->getFunction()).getParent());
Jeremy Morse8b593482019-08-16 10:04:17 +0000712 // DebugInstr refers to the pre-spill location, therefore we can reuse
713 // its expression.
714 NewDebugInstr = BuildMI(
715 *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(), false, NewReg,
716 DebugInstr->getDebugVariable(), DebugInstr->getDebugExpression());
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000717 VarLoc VL(*NewDebugInstr, LS);
718 ProcessVarLoc(VL, NewDebugInstr);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000719 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register restore: ";
Craig Topper78c794a2019-06-02 01:36:48 +0000720 NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
721 /*SkipOpers*/false, /*SkipDebugLoc*/false,
722 /*AddNewLine*/true, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000723 return;
724 }
725 }
726 llvm_unreachable("Invalid transfer kind");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000727}
728
Vikram TV859ad292015-12-16 11:09:48 +0000729/// A definition of a register may mark the end of a range.
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000730void LiveDebugValues::transferRegisterDef(
731 MachineInstr &MI, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
732 TransferMap &Transfers, DebugParamMap &DebugEntryVals) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +0000733 MachineFunction *MF = MI.getMF();
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000734 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
735 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000736 SparseBitVector<> KillSet;
Vikram TV859ad292015-12-16 11:09:48 +0000737 for (const MachineOperand &MO : MI.operands()) {
Adrian Prantlea8880b2017-03-03 01:08:25 +0000738 // Determine whether the operand is a register def. Assume that call
739 // instructions never clobber SP, because some backends (e.g., AArch64)
740 // never list SP in the regmask.
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000741 if (MO.isReg() && MO.isDef() && MO.getReg() &&
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000742 Register::isPhysicalRegister(MO.getReg()) &&
Adrian Prantlea8880b2017-03-03 01:08:25 +0000743 !(MI.isCall() && MO.getReg() == SP)) {
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000744 // Remove ranges of all aliased registers.
745 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
Adrian Prantl7509d542016-05-26 21:42:47 +0000746 for (unsigned ID : OpenRanges.getVarLocs())
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000747 if (VarLocIDs[ID].isDescribedByReg() == *RAI)
748 KillSet.set(ID);
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000749 } else if (MO.isRegMask()) {
750 // Remove ranges of all clobbered registers. Register masks don't usually
751 // list SP as preserved. While the debug info may be off for an
752 // instruction or two around callee-cleanup calls, transferring the
753 // DEBUG_VALUE across the call is still a better user experience.
Adrian Prantl7509d542016-05-26 21:42:47 +0000754 for (unsigned ID : OpenRanges.getVarLocs()) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000755 unsigned Reg = VarLocIDs[ID].isDescribedByReg();
756 if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
757 KillSet.set(ID);
758 }
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000759 }
Vikram TV859ad292015-12-16 11:09:48 +0000760 }
Adrian Prantl7509d542016-05-26 21:42:47 +0000761 OpenRanges.erase(KillSet, VarLocIDs);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000762
763 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
764 auto &TM = TPC->getTM<TargetMachine>();
765 if (TM.Options.EnableDebugEntryValues)
766 emitEntryValues(MI, OpenRanges, VarLocIDs, Transfers, DebugEntryVals,
767 KillSet);
768 }
Vikram TV859ad292015-12-16 11:09:48 +0000769}
770
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000771/// Decide if @MI is a spill instruction and return true if it is. We use 2
772/// criteria to make this decision:
773/// - Is this instruction a store to a spill slot?
774/// - Is there a register operand that is both used and killed?
775/// TODO: Store optimization can fold spills into other stores (including
776/// other spills). We do not handle this yet (more than one memory operand).
777bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
778 MachineFunction *MF, unsigned &Reg) {
Sander de Smalenc91b27d2018-09-05 08:59:50 +0000779 SmallVector<const MachineMemOperand*, 1> Accesses;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000780
Fangrui Songf78650a2018-07-30 19:41:25 +0000781 // TODO: Handle multiple stores folded into one.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000782 if (!MI.hasOneMemOperand())
783 return false;
784
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000785 if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
786 return false; // This is not a spill instruction, since no valid size was
787 // returned from either function.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000788
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000789 auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
790 if (!MO.isReg() || !MO.isUse()) {
791 Reg = 0;
792 return false;
793 }
794 Reg = MO.getReg();
795 return MO.isKill();
796 };
797
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000798 for (const MachineOperand &MO : MI.operands()) {
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000799 // In a spill instruction generated by the InlineSpiller the spilled
800 // register has its kill flag set.
801 if (isKilledReg(MO, Reg))
802 return true;
803 if (Reg != 0) {
804 // Check whether next instruction kills the spilled register.
805 // FIXME: Current solution does not cover search for killed register in
806 // bundles and instructions further down the chain.
807 auto NextI = std::next(MI.getIterator());
808 // Skip next instruction that points to basic block end iterator.
809 if (MI.getParent()->end() == NextI)
810 continue;
811 unsigned RegNext;
812 for (const MachineOperand &MONext : NextI->operands()) {
813 // Return true if we came across the register from the
814 // previous spill instruction that is killed in NextI.
815 if (isKilledReg(MONext, RegNext) && RegNext == Reg)
816 return true;
817 }
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000818 }
819 }
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000820 // Return false if we didn't find spilled register.
821 return false;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000822}
823
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000824Optional<LiveDebugValues::VarLoc::SpillLoc>
825LiveDebugValues::isRestoreInstruction(const MachineInstr &MI,
826 MachineFunction *MF, unsigned &Reg) {
827 if (!MI.hasOneMemOperand())
828 return None;
829
830 // FIXME: Handle folded restore instructions with more than one memory
831 // operand.
832 if (MI.getRestoreSize(TII)) {
833 Reg = MI.getOperand(0).getReg();
834 return extractSpillBaseRegAndOffset(MI);
835 }
836 return None;
837}
838
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000839/// A spilled register may indicate that we have to end the current range of
840/// a variable and create a new one for the spill location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000841/// A restored register may indicate the reverse situation.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000842/// We don't want to insert any instructions in process(), so we just create
843/// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000844/// It will be inserted into the BB when we're done iterating over the
845/// instructions.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000846void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr &MI,
847 OpenRangesSet &OpenRanges,
848 VarLocMap &VarLocIDs,
849 TransferMap &Transfers) {
Wolfgang Piebfacd0522019-01-30 20:37:14 +0000850 MachineFunction *MF = MI.getMF();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000851 TransferKind TKind;
852 unsigned Reg;
853 Optional<VarLoc::SpillLoc> Loc;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000854
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000855 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
856
857 if (isSpillInstruction(MI, MF, Reg)) {
858 TKind = TransferKind::TransferSpill;
859 LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
860 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
861 << "\n");
862 } else {
863 if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
864 return;
865 TKind = TransferKind::TransferRestore;
866 LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
867 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
868 << "\n");
869 }
870 // Check if the register or spill location is the location of a debug value.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000871 for (unsigned ID : OpenRanges.getVarLocs()) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000872 if (TKind == TransferKind::TransferSpill &&
Jeremy Morse8b593482019-08-16 10:04:17 +0000873 VarLocIDs[ID].isDescribedByReg() == Reg) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000874 LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
875 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000876 } else if (TKind == TransferKind::TransferRestore &&
877 VarLocIDs[ID].Loc.SpillLocation == *Loc) {
878 LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
879 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
880 } else
881 continue;
882 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID, TKind,
883 Reg);
884 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000885 }
886}
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000887
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000888/// If \p MI is a register copy instruction, that copies a previously tracked
889/// value from one register to another register that is callee saved, we
890/// create new DBG_VALUE instruction described with copy destination register.
891void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
892 OpenRangesSet &OpenRanges,
893 VarLocMap &VarLocIDs,
894 TransferMap &Transfers) {
895 const MachineOperand *SrcRegOp, *DestRegOp;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000896
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000897 if (!TII->isCopyInstr(MI, SrcRegOp, DestRegOp) || !SrcRegOp->isKill() ||
898 !DestRegOp->isDef())
899 return;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000900
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000901 auto isCalleSavedReg = [&](unsigned Reg) {
902 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
903 if (CalleeSavedRegs.test(*RAI))
904 return true;
905 return false;
906 };
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000907
Daniel Sanders0c476112019-08-15 19:22:08 +0000908 Register SrcReg = SrcRegOp->getReg();
909 Register DestReg = DestRegOp->getReg();
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000910
911 // We want to recognize instructions where destination register is callee
912 // saved register. If register that could be clobbered by the call is
913 // included, there would be a great chance that it is going to be clobbered
914 // soon. It is more likely that previous register location, which is callee
915 // saved, is going to stay unclobbered longer, even if it is killed.
916 if (!isCalleSavedReg(DestReg))
917 return;
918
919 for (unsigned ID : OpenRanges.getVarLocs()) {
920 if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
921 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000922 TransferKind::TransferCopy, DestReg);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000923 return;
924 }
925 }
926}
927
Vikram TV859ad292015-12-16 11:09:48 +0000928/// Terminate all open ranges at the end of the current basic block.
Jeremy Morse67443c32019-08-21 09:22:31 +0000929bool LiveDebugValues::transferTerminator(MachineBasicBlock *CurMBB,
930 OpenRangesSet &OpenRanges,
931 VarLocInMBB &OutLocs,
932 const VarLocMap &VarLocIDs) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000933 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000934
935 if (OpenRanges.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000936 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000937
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000938 LLVM_DEBUG(for (unsigned ID
939 : OpenRanges.getVarLocs()) {
940 // Copy OpenRanges to OutLocs, if not already present.
Vedant Kumar9b558382018-10-05 21:44:00 +0000941 dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000942 VarLocIDs[ID].dump();
943 });
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000944 VarLocSet &VLS = OutLocs[CurMBB];
Adrian Prantl7509d542016-05-26 21:42:47 +0000945 Changed = VLS |= OpenRanges.getVarLocs();
Nikola Prica2d0106a2019-06-03 09:48:29 +0000946 // New OutLocs set may be different due to spill, restore or register
947 // copy instruction processing.
948 if (Changed)
949 VLS = OpenRanges.getVarLocs();
Vikram TV859ad292015-12-16 11:09:48 +0000950 OpenRanges.clear();
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000951 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000952}
953
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000954/// Accumulate a mapping between each DILocalVariable fragment and other
955/// fragments of that DILocalVariable which overlap. This reduces work during
956/// the data-flow stage from "Find any overlapping fragments" to "Check if the
957/// known-to-overlap fragments are present".
958/// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
959/// fragment usage.
960/// \param SeenFragments Map from DILocalVariable to all fragments of that
961/// Variable which are known to exist.
962/// \param OverlappingFragments The overlap map being constructed, from one
963/// Var/Fragment pair to a vector of fragments known to overlap.
964void LiveDebugValues::accumulateFragmentMap(MachineInstr &MI,
965 VarToFragments &SeenFragments,
966 OverlapMap &OverlappingFragments) {
967 DebugVariable MIVar(MI);
968 FragmentInfo ThisFragment = MIVar.getFragmentDefault();
969
970 // If this is the first sighting of this variable, then we are guaranteed
971 // there are currently no overlapping fragments either. Initialize the set
972 // of seen fragments, record no overlaps for the current one, and return.
973 auto SeenIt = SeenFragments.find(MIVar.getVar());
974 if (SeenIt == SeenFragments.end()) {
975 SmallSet<FragmentInfo, 4> OneFragment;
976 OneFragment.insert(ThisFragment);
977 SeenFragments.insert({MIVar.getVar(), OneFragment});
978
979 OverlappingFragments.insert({{MIVar.getVar(), ThisFragment}, {}});
980 return;
981 }
982
983 // If this particular Variable/Fragment pair already exists in the overlap
984 // map, it has already been accounted for.
985 auto IsInOLapMap =
986 OverlappingFragments.insert({{MIVar.getVar(), ThisFragment}, {}});
987 if (!IsInOLapMap.second)
988 return;
989
990 auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
991 auto &AllSeenFragments = SeenIt->second;
992
993 // Otherwise, examine all other seen fragments for this variable, with "this"
994 // fragment being a previously unseen fragment. Record any pair of
995 // overlapping fragments.
996 for (auto &ASeenFragment : AllSeenFragments) {
997 // Does this previously seen fragment overlap?
998 if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
999 // Yes: Mark the current fragment as being overlapped.
1000 ThisFragmentsOverlaps.push_back(ASeenFragment);
1001 // Mark the previously seen fragment as being overlapped by the current
1002 // one.
1003 auto ASeenFragmentsOverlaps =
1004 OverlappingFragments.find({MIVar.getVar(), ASeenFragment});
1005 assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
1006 "Previously seen var fragment has no vector of overlaps");
1007 ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1008 }
1009 }
1010
1011 AllSeenFragments.insert(ThisFragment);
1012}
1013
Vikram TV859ad292015-12-16 11:09:48 +00001014/// This routine creates OpenRanges and OutLocs.
Jeremy Morse67443c32019-08-21 09:22:31 +00001015void LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001016 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001017 TransferMap &Transfers, DebugParamMap &DebugEntryVals,
1018 bool transferChanges,
Jeremy Morsed2cd9c22019-06-13 13:11:57 +00001019 OverlapMap &OverlapFragments,
1020 VarToFragments &SeenFragments) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001021 transferDebugValue(MI, OpenRanges, VarLocIDs);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001022 transferRegisterDef(MI, OpenRanges, VarLocIDs, Transfers,
1023 DebugEntryVals);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001024 if (transferChanges) {
1025 transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001026 transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
Jeremy Morsed2cd9c22019-06-13 13:11:57 +00001027 } else {
1028 // Build up a map of overlapping fragments on the first run through.
1029 if (MI.isDebugValue())
1030 accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001031 }
Vikram TV859ad292015-12-16 11:09:48 +00001032}
1033
1034/// This routine joins the analysis results of all incoming edges in @MBB by
1035/// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
1036/// source variable in all the predecessors of @MBB reside in the same location.
Vedant Kumar8c466682018-10-05 21:44:15 +00001037bool LiveDebugValues::join(
1038 MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1039 const VarLocMap &VarLocIDs,
1040 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
Jeremy Morse67443c32019-08-21 09:22:31 +00001041 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks,
1042 VarLocInMBB &PendingInLocs) {
Vedant Kumar9b558382018-10-05 21:44:00 +00001043 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001044 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +00001045
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001046 VarLocSet InLocsT; // Temporary incoming locations.
Vikram TV859ad292015-12-16 11:09:48 +00001047
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001048 // For all predecessors of this MBB, find the set of VarLocs that
1049 // can be joined.
Keith Walker83ebef52016-09-27 16:46:07 +00001050 int NumVisited = 0;
Vikram TV859ad292015-12-16 11:09:48 +00001051 for (auto p : MBB.predecessors()) {
Keith Walker83ebef52016-09-27 16:46:07 +00001052 // Ignore unvisited predecessor blocks. As we are processing
1053 // the blocks in reverse post-order any unvisited block can
1054 // be considered to not remove any incoming values.
Vedant Kumar9b558382018-10-05 21:44:00 +00001055 if (!Visited.count(p)) {
1056 LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
1057 << "\n");
Keith Walker83ebef52016-09-27 16:46:07 +00001058 continue;
Vedant Kumar9b558382018-10-05 21:44:00 +00001059 }
Vikram TV859ad292015-12-16 11:09:48 +00001060 auto OL = OutLocs.find(p);
1061 // Join is null in case of empty OutLocs from any of the pred.
1062 if (OL == OutLocs.end())
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001063 return false;
Vikram TV859ad292015-12-16 11:09:48 +00001064
Keith Walker83ebef52016-09-27 16:46:07 +00001065 // Just copy over the Out locs to incoming locs for the first visited
1066 // predecessor, and for all other predecessors join the Out locs.
1067 if (!NumVisited)
Vikram TV859ad292015-12-16 11:09:48 +00001068 InLocsT = OL->second;
Keith Walker83ebef52016-09-27 16:46:07 +00001069 else
1070 InLocsT &= OL->second;
Vedant Kumar9b558382018-10-05 21:44:00 +00001071
1072 LLVM_DEBUG({
1073 if (!InLocsT.empty()) {
1074 for (auto ID : InLocsT)
1075 dbgs() << " gathered candidate incoming var: "
1076 << VarLocIDs[ID].Var.getVar()->getName() << "\n";
1077 }
1078 });
1079
Keith Walker83ebef52016-09-27 16:46:07 +00001080 NumVisited++;
Vikram TV859ad292015-12-16 11:09:48 +00001081 }
1082
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001083 // Filter out DBG_VALUES that are out of scope.
1084 VarLocSet KillSet;
Vedant Kumar8c466682018-10-05 21:44:15 +00001085 bool IsArtificial = ArtificialBlocks.count(&MBB);
1086 if (!IsArtificial) {
1087 for (auto ID : InLocsT) {
1088 if (!VarLocIDs[ID].dominates(MBB)) {
1089 KillSet.set(ID);
1090 LLVM_DEBUG({
1091 auto Name = VarLocIDs[ID].Var.getVar()->getName();
1092 dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
1093 });
1094 }
Vedant Kumar9b558382018-10-05 21:44:00 +00001095 }
1096 }
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001097 InLocsT.intersectWithComplement(KillSet);
1098
Keith Walker83ebef52016-09-27 16:46:07 +00001099 // As we are processing blocks in reverse post-order we
1100 // should have processed at least one predecessor, unless it
1101 // is the entry block which has no predecessor.
1102 assert((NumVisited || MBB.pred_empty()) &&
1103 "Should have processed at least one predecessor");
Vikram TV859ad292015-12-16 11:09:48 +00001104 if (InLocsT.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001105 return false;
Vikram TV859ad292015-12-16 11:09:48 +00001106
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001107 VarLocSet &ILS = InLocs[&MBB];
Jeremy Morse67443c32019-08-21 09:22:31 +00001108 VarLocSet &Pending = PendingInLocs[&MBB];
Vikram TV859ad292015-12-16 11:09:48 +00001109
Jeremy Morse67443c32019-08-21 09:22:31 +00001110 // New locations will have DBG_VALUE insts inserted at the start of the
1111 // block, after location propagation has finished. Record the insertions
1112 // that we need to perform in the Pending set.
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001113 VarLocSet Diff = InLocsT;
1114 Diff.intersectWithComplement(ILS);
1115 for (auto ID : Diff) {
Jeremy Morse67443c32019-08-21 09:22:31 +00001116 Pending.set(ID);
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001117 ILS.set(ID);
1118 ++NumInserted;
1119 Changed = true;
Vikram TV859ad292015-12-16 11:09:48 +00001120 }
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001121 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +00001122}
1123
Jeremy Morse67443c32019-08-21 09:22:31 +00001124void LiveDebugValues::flushPendingLocs(VarLocInMBB &PendingInLocs,
1125 VarLocMap &VarLocIDs) {
1126 // PendingInLocs records all locations propagated into blocks, which have
1127 // not had DBG_VALUE insts created. Go through and create those insts now.
1128 for (auto &Iter : PendingInLocs) {
1129 // Map is keyed on a constant pointer, unwrap it so we can insert insts.
1130 auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first);
1131 VarLocSet &Pending = Iter.second;
1132
1133 for (unsigned ID : Pending) {
1134 // The ID location is live-in to MBB -- work out what kind of machine
1135 // location it is and create a DBG_VALUE.
1136 const VarLoc &DiffIt = VarLocIDs[ID];
1137 const MachineInstr *DebugInstr = &DiffIt.MI;
1138 MachineInstr *MI = nullptr;
1139
1140 if (DiffIt.isConstant()) {
1141 MachineOperand MO(DebugInstr->getOperand(0));
1142 MI = BuildMI(MBB, MBB.instr_begin(), DebugInstr->getDebugLoc(),
1143 DebugInstr->getDesc(), false, MO,
1144 DebugInstr->getDebugVariable(),
1145 DebugInstr->getDebugExpression());
1146 } else {
1147 auto *DebugExpr = DebugInstr->getDebugExpression();
1148 Register Reg = DebugInstr->getOperand(0).getReg();
1149 bool IsIndirect = DebugInstr->isIndirectDebugValue();
1150
1151 if (DiffIt.Kind == VarLoc::SpillLocKind) {
1152 // This is is a spilt location; DebugInstr refers to the unspilt
1153 // location. We need to rebuild the spilt location expression and
1154 // point the DBG_VALUE at the frame register.
1155 DebugExpr = DIExpression::prepend(
1156 DebugInstr->getDebugExpression(), DIExpression::ApplyOffset,
1157 DiffIt.Loc.SpillLocation.SpillOffset);
1158 Reg = TRI->getFrameRegister(*DebugInstr->getMF());
1159 IsIndirect = true;
1160 }
1161
1162 MI = BuildMI(MBB, MBB.instr_begin(), DebugInstr->getDebugLoc(),
1163 DebugInstr->getDesc(), IsIndirect, Reg,
1164 DebugInstr->getDebugVariable(), DebugExpr);
1165 }
1166 LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
1167 }
1168 }
1169}
1170
Vikram TV859ad292015-12-16 11:09:48 +00001171/// Calculate the liveness information for the given machine function and
1172/// extend ranges across basic blocks.
1173bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001174 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
Vikram TV859ad292015-12-16 11:09:48 +00001175
1176 bool Changed = false;
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001177 bool OLChanged = false;
1178 bool MBBJoined = false;
Vikram TV859ad292015-12-16 11:09:48 +00001179
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001180 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
1181 OverlapMap OverlapFragments; // Map of overlapping variable fragments
1182 OpenRangesSet OpenRanges(OverlapFragments);
1183 // Ranges that are open until end of bb.
1184 VarLocInMBB OutLocs; // Ranges that exist beyond bb.
1185 VarLocInMBB InLocs; // Ranges that are incoming after joining.
1186 TransferMap Transfers; // DBG_VALUEs associated with spills.
Jeremy Morse67443c32019-08-21 09:22:31 +00001187 VarLocInMBB PendingInLocs; // Ranges that are incoming after joining, but
1188 // that we have deferred creating DBG_VALUE insts
1189 // for immediately.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001190
1191 VarToFragments SeenFragments;
Vikram TV859ad292015-12-16 11:09:48 +00001192
Vedant Kumar8c466682018-10-05 21:44:15 +00001193 // Blocks which are artificial, i.e. blocks which exclusively contain
1194 // instructions without locations, or with line 0 locations.
1195 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
1196
Daniel Berlin72560592016-01-10 18:08:32 +00001197 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
1198 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
1199 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001200 std::greater<unsigned int>>
1201 Worklist;
Daniel Berlin72560592016-01-10 18:08:32 +00001202 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001203 std::greater<unsigned int>>
1204 Pending;
1205
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001206 enum : bool { dontTransferChanges = false, transferChanges = true };
1207
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001208 // Besides parameter's modification, check whether a DBG_VALUE is inlined
1209 // in order to deduce whether the variable that it tracks comes from
1210 // a different function. If that is the case we can't track its entry value.
1211 auto IsUnmodifiedFuncParam = [&](const MachineInstr &MI) {
1212 auto *DIVar = MI.getDebugVariable();
1213 return DIVar->isParameter() && DIVar->isNotModified() &&
1214 !MI.getDebugLoc()->getInlinedAt();
1215 };
1216
1217 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
1218 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Daniel Sanders0c476112019-08-15 19:22:08 +00001219 Register FP = TRI->getFrameRegister(MF);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001220 auto IsRegOtherThanSPAndFP = [&](const MachineOperand &Op) -> bool {
1221 return Op.isReg() && Op.getReg() != SP && Op.getReg() != FP;
1222 };
1223
1224 // Working set of currently collected debug variables mapped to DBG_VALUEs
1225 // representing candidates for production of debug entry values.
1226 DebugParamMap DebugEntryVals;
1227
1228 MachineBasicBlock &First_MBB = *(MF.begin());
1229 // Only in the case of entry MBB collect DBG_VALUEs representing
1230 // function parameters in order to generate debug entry values for them.
1231 // Currently, we generate debug entry values only for parameters that are
1232 // unmodified throughout the function and located in a register.
1233 // TODO: Add support for parameters that are described as fragments.
1234 // TODO: Add support for modified arguments that can be expressed
1235 // by using its entry value.
1236 // TODO: Add support for local variables that are expressed in terms of
1237 // parameters entry values.
1238 for (auto &MI : First_MBB)
1239 if (MI.isDebugValue() && IsUnmodifiedFuncParam(MI) &&
1240 !MI.isIndirectDebugValue() && IsRegOtherThanSPAndFP(MI.getOperand(0)) &&
1241 !DebugEntryVals.count(MI.getDebugVariable()) &&
1242 !MI.getDebugExpression()->isFragment())
1243 DebugEntryVals[MI.getDebugVariable()] = &MI;
1244
Vikram TV859ad292015-12-16 11:09:48 +00001245 // Initialize every mbb with OutLocs.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001246 // We are not looking at any spill instructions during the initial pass
1247 // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
1248 // instructions for spills of registers that are known to be user variables
1249 // within the BB in which the spill occurs.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001250 for (auto &MBB : MF) {
1251 for (auto &MI : MBB) {
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001252 process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers, DebugEntryVals,
Jeremy Morsed2cd9c22019-06-13 13:11:57 +00001253 dontTransferChanges, OverlapFragments, SeenFragments);
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001254 }
Jeremy Morse67443c32019-08-21 09:22:31 +00001255 transferTerminator(&MBB, OpenRanges, OutLocs, VarLocIDs);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001256 // Add any entry DBG_VALUE instructions necessitated by parameter
1257 // clobbering.
1258 for (auto &TR : Transfers) {
1259 MBB.insertAfter(MachineBasicBlock::iterator(*TR.TransferInst),
1260 TR.DebugInst);
1261 }
1262 Transfers.clear();
Jeremy Morse67443c32019-08-21 09:22:31 +00001263
1264 // Initialize pending inlocs.
1265 PendingInLocs[&MBB] = VarLocSet();
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001266 }
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001267
Vedant Kumar8c466682018-10-05 21:44:15 +00001268 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
1269 if (const DebugLoc &DL = MI.getDebugLoc())
1270 return DL.getLine() != 0;
1271 return false;
1272 };
1273 for (auto &MBB : MF)
1274 if (none_of(MBB.instrs(), hasNonArtificialLocation))
1275 ArtificialBlocks.insert(&MBB);
1276
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001277 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1278 "OutLocs after initialization", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001279
Daniel Berlin72560592016-01-10 18:08:32 +00001280 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
1281 unsigned int RPONumber = 0;
1282 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
1283 OrderToBB[RPONumber] = *RI;
1284 BBToOrder[*RI] = RPONumber;
1285 Worklist.push(RPONumber);
1286 ++RPONumber;
1287 }
Daniel Berlin72560592016-01-10 18:08:32 +00001288 // This is a standard "union of predecessor outs" dataflow problem.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001289 // To solve it, we perform join() and process() using the two worklist method
Daniel Berlin72560592016-01-10 18:08:32 +00001290 // until the ranges converge.
1291 // Ranges have converged when both worklists are empty.
Keith Walker83ebef52016-09-27 16:46:07 +00001292 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
Daniel Berlin72560592016-01-10 18:08:32 +00001293 while (!Worklist.empty() || !Pending.empty()) {
1294 // We track what is on the pending worklist to avoid inserting the same
1295 // thing twice. We could avoid this with a custom priority queue, but this
1296 // is probably not worth it.
1297 SmallPtrSet<MachineBasicBlock *, 16> OnPending;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001298 LLVM_DEBUG(dbgs() << "Processing Worklist\n");
Daniel Berlin72560592016-01-10 18:08:32 +00001299 while (!Worklist.empty()) {
1300 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
1301 Worklist.pop();
Jeremy Morse67443c32019-08-21 09:22:31 +00001302 MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited,
1303 ArtificialBlocks, PendingInLocs);
Keith Walker83ebef52016-09-27 16:46:07 +00001304 Visited.insert(MBB);
Daniel Berlin72560592016-01-10 18:08:32 +00001305 if (MBBJoined) {
1306 MBBJoined = false;
1307 Changed = true;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001308 // Now that we have started to extend ranges across BBs we need to
1309 // examine spill instructions to see whether they spill registers that
1310 // correspond to user variables.
Jeremy Morse67443c32019-08-21 09:22:31 +00001311 // First load any pending inlocs.
1312 OpenRanges.insertFromLocSet(PendingInLocs[MBB], VarLocIDs);
Daniel Berlin72560592016-01-10 18:08:32 +00001313 for (auto &MI : *MBB)
Jeremy Morsed2cd9c22019-06-13 13:11:57 +00001314 process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001315 DebugEntryVals, transferChanges, OverlapFragments,
1316 SeenFragments);
Jeremy Morse67443c32019-08-21 09:22:31 +00001317 OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001318
1319 // Add any DBG_VALUE instructions necessitated by spills.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001320 for (auto &TR : Transfers)
1321 MBB->insertAfter(MachineBasicBlock::iterator(*TR.TransferInst),
1322 TR.DebugInst);
1323 Transfers.clear();
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001324
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001325 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1326 "OutLocs after propagating", dbgs()));
1327 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
1328 "InLocs after propagating", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001329
Daniel Berlin72560592016-01-10 18:08:32 +00001330 if (OLChanged) {
1331 OLChanged = false;
1332 for (auto s : MBB->successors())
Benjamin Kramer4dea8f52016-06-17 18:59:41 +00001333 if (OnPending.insert(s).second) {
Daniel Berlin72560592016-01-10 18:08:32 +00001334 Pending.push(BBToOrder[s]);
1335 }
1336 }
Vikram TV859ad292015-12-16 11:09:48 +00001337 }
1338 }
Daniel Berlin72560592016-01-10 18:08:32 +00001339 Worklist.swap(Pending);
1340 // At this point, pending must be empty, since it was just the empty
1341 // worklist
1342 assert(Pending.empty() && "Pending should be empty");
Vikram TV859ad292015-12-16 11:09:48 +00001343 }
Daniel Berlin72560592016-01-10 18:08:32 +00001344
Jeremy Morse67443c32019-08-21 09:22:31 +00001345 // Deferred inlocs will not have had any DBG_VALUE insts created; do
1346 // that now.
1347 flushPendingLocs(PendingInLocs, VarLocIDs);
1348
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001349 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
1350 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001351 return Changed;
1352}
1353
1354bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001355 if (!MF.getFunction().getSubprogram())
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001356 // LiveDebugValues will already have removed all DBG_VALUEs.
1357 return false;
1358
Wolfgang Piebe018bbd2017-07-19 19:36:40 +00001359 // Skip functions from NoDebug compilation units.
Matthias Braunf1caa282017-12-15 22:22:58 +00001360 if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
Wolfgang Piebe018bbd2017-07-19 19:36:40 +00001361 DICompileUnit::NoDebug)
1362 return false;
1363
Vikram TV859ad292015-12-16 11:09:48 +00001364 TRI = MF.getSubtarget().getRegisterInfo();
1365 TII = MF.getSubtarget().getInstrInfo();
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001366 TFI = MF.getSubtarget().getFrameLowering();
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001367 TFI->determineCalleeSaves(MF, CalleeSavedRegs,
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001368 std::make_unique<RegScavenger>().get());
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001369 LS.initialize(MF);
Vikram TV859ad292015-12-16 11:09:48 +00001370
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001371 bool Changed = ExtendRanges(MF);
Vikram TV859ad292015-12-16 11:09:48 +00001372 return Changed;
1373}