blob: 5eb244080f14f83a9cd105d0fc261a07f9709a9d [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
10/// information by inserting additional DBG_VALUE instructions into the machine
11/// instruction stream. The pass internally builds debug location liveness
12/// ranges to determine the points where additional DBG_VALUEs need to be
13/// inserted.
14///
15/// This is a separate pass from DbgValueHistoryCalculator to facilitate
16/// testing and improve modularity.
17///
18//===----------------------------------------------------------------------===//
19
Eugene Zelenko5df3d892017-08-24 21:21:39 +000020#include "llvm/ADT/DenseMap.h"
Daniel Berlin72560592016-01-10 18:08:32 +000021#include "llvm/ADT/PostOrderIterator.h"
22#include "llvm/ADT/SmallPtrSet.h"
Jeremy Morsebf2b2f02019-06-13 12:51:57 +000023#include "llvm/ADT/SmallSet.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000024#include "llvm/ADT/SmallVector.h"
Adrian Prantl6ee02c72016-05-25 22:21:12 +000025#include "llvm/ADT/SparseBitVector.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000026#include "llvm/ADT/Statistic.h"
Adrian Prantl6ee02c72016-05-25 22:21:12 +000027#include "llvm/ADT/UniqueVector.h"
Adrian Prantl7f5866c2016-09-28 17:51:14 +000028#include "llvm/CodeGen/LexicalScopes.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000029#include "llvm/CodeGen/MachineBasicBlock.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000030#include "llvm/CodeGen/MachineFrameInfo.h"
Vikram TV859ad292015-12-16 11:09:48 +000031#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000033#include "llvm/CodeGen/MachineInstr.h"
Vikram TV859ad292015-12-16 11:09:48 +000034#include "llvm/CodeGen/MachineInstrBuilder.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000035#include "llvm/CodeGen/MachineMemOperand.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000036#include "llvm/CodeGen/MachineOperand.h"
37#include "llvm/CodeGen/PseudoSourceValue.h"
Wolfgang Pieb90d856c2019-02-04 20:42:45 +000038#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000039#include "llvm/CodeGen/TargetFrameLowering.h"
40#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000041#include "llvm/CodeGen/TargetLowering.h"
42#include "llvm/CodeGen/TargetRegisterInfo.h"
43#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000044#include "llvm/Config/llvm-config.h"
Wolfgang Pieb90d856c2019-02-04 20:42:45 +000045#include "llvm/IR/DIBuilder.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000046#include "llvm/IR/DebugInfoMetadata.h"
47#include "llvm/IR/DebugLoc.h"
48#include "llvm/IR/Function.h"
49#include "llvm/IR/Module.h"
50#include "llvm/MC/MCRegisterInfo.h"
51#include "llvm/Pass.h"
52#include "llvm/Support/Casting.h"
53#include "llvm/Support/Compiler.h"
Vikram TV859ad292015-12-16 11:09:48 +000054#include "llvm/Support/Debug.h"
55#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000056#include <algorithm>
57#include <cassert>
58#include <cstdint>
59#include <functional>
Mehdi Aminib550cb12016-04-18 09:17:29 +000060#include <queue>
Jeremy Morsebf2b2f02019-06-13 12:51:57 +000061#include <tuple>
Eugene Zelenko5df3d892017-08-24 21:21:39 +000062#include <utility>
63#include <vector>
Vikram TV859ad292015-12-16 11:09:48 +000064
65using namespace llvm;
66
Matthias Braun1527baa2017-05-25 21:26:32 +000067#define DEBUG_TYPE "livedebugvalues"
Vikram TV859ad292015-12-16 11:09:48 +000068
69STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
70
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000071// If @MI is a DBG_VALUE with debug value described by a defined
Adrian Prantl6ee02c72016-05-25 22:21:12 +000072// register, returns the number of this register. In the other case, returns 0.
Adrian Prantl00698732016-05-25 22:37:29 +000073static unsigned isDbgValueDescribedByReg(const MachineInstr &MI) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +000074 assert(MI.isDebugValue() && "expected a DBG_VALUE");
75 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
76 // If location of variable is described using a register (directly
77 // or indirectly), this register is always a first operand.
78 return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0;
79}
80
Eugene Zelenko5df3d892017-08-24 21:21:39 +000081namespace {
Vikram TV859ad292015-12-16 11:09:48 +000082
Eugene Zelenko5df3d892017-08-24 21:21:39 +000083class LiveDebugValues : public MachineFunctionPass {
Vikram TV859ad292015-12-16 11:09:48 +000084private:
85 const TargetRegisterInfo *TRI;
86 const TargetInstrInfo *TII;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000087 const TargetFrameLowering *TFI;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +000088 BitVector CalleeSavedRegs;
Adrian Prantl7f5866c2016-09-28 17:51:14 +000089 LexicalScopes LS;
90
Wolfgang Pieb90d856c2019-02-04 20:42:45 +000091 enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
92
Adrian Prantl7f5866c2016-09-28 17:51:14 +000093 /// Keeps track of lexical scopes associated with a user value's source
94 /// location.
95 class UserValueScopes {
96 DebugLoc DL;
97 LexicalScopes &LS;
98 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
99
100 public:
101 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
102
103 /// Return true if current scope dominates at least one machine
104 /// instruction in a given machine basic block.
105 bool dominates(MachineBasicBlock *MBB) {
106 if (LBlocks.empty())
107 LS.getMachineBasicBlocks(DL, LBlocks);
108 return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
109 }
110 };
Vikram TV859ad292015-12-16 11:09:48 +0000111
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000112 using FragmentInfo = DIExpression::FragmentInfo;
113 using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
Vikram TV859ad292015-12-16 11:09:48 +0000114
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000115 /// Storage for identifying a potentially inlined instance of a variable,
116 /// or a fragment thereof.
117 class DebugVariable {
118 const DILocalVariable *Variable;
119 OptFragmentInfo Fragment;
120 const DILocation *InlinedAt;
Vikram TV859ad292015-12-16 11:09:48 +0000121
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000122 /// Fragment that will overlap all other fragments. Used as default when
123 /// caller demands a fragment.
124 static const FragmentInfo DefaultFragment;
125
126 public:
127 DebugVariable(const DILocalVariable *Var, OptFragmentInfo &&FragmentInfo,
128 const DILocation *InlinedAt)
129 : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
130
131 DebugVariable(const DILocalVariable *Var, OptFragmentInfo &FragmentInfo,
132 const DILocation *InlinedAt)
133 : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
134
135 DebugVariable(const DILocalVariable *Var, const DIExpression *DIExpr,
136 const DILocation *InlinedAt)
137 : DebugVariable(Var, DIExpr->getFragmentInfo(), InlinedAt) {}
138
139 DebugVariable(const MachineInstr &MI)
140 : DebugVariable(MI.getDebugVariable(),
141 MI.getDebugExpression()->getFragmentInfo(),
142 MI.getDebugLoc()->getInlinedAt()) {}
143
144 const DILocalVariable *getVar() const { return Variable; }
145 const OptFragmentInfo &getFragment() const { return Fragment; }
146 const DILocation *getInlinedAt() const { return InlinedAt; }
147
148 const FragmentInfo getFragmentDefault() const {
149 return Fragment.getValueOr(DefaultFragment);
150 }
151
152 static bool isFragmentDefault(FragmentInfo &F) {
153 return F == DefaultFragment;
154 }
155
156 bool operator==(const DebugVariable &Other) const {
157 return std::tie(Variable, Fragment, InlinedAt) ==
158 std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
159 }
160
161 bool operator<(const DebugVariable &Other) const {
162 return std::tie(Variable, Fragment, InlinedAt) <
163 std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
Vikram TV859ad292015-12-16 11:09:48 +0000164 }
165 };
166
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000167 friend struct llvm::DenseMapInfo<DebugVariable>;
168
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000169 /// A pair of debug variable and value location.
Vikram TV859ad292015-12-16 11:09:48 +0000170 struct VarLoc {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000171 // The location at which a spilled variable resides. It consists of a
172 // register and an offset.
173 struct SpillLoc {
174 unsigned SpillBase;
175 int SpillOffset;
176 bool operator==(const SpillLoc &Other) const {
177 return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
178 }
179 };
180
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000181 const DebugVariable Var;
182 const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000183 mutable UserValueScopes UVS;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000184 enum VarLocKind {
185 InvalidKind = 0,
186 RegisterKind,
Jeremy Morsebcff4172019-06-10 15:23:46 +0000187 SpillLocKind,
188 ImmediateKind
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000189 } Kind = InvalidKind;
Vikram TV859ad292015-12-16 11:09:48 +0000190
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000191 /// The value location. Stored separately to avoid repeatedly
192 /// extracting it from MI.
193 union {
Adrian Prantl359846f2017-07-28 23:25:51 +0000194 uint64_t RegNo;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000195 SpillLoc SpillLocation;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000196 uint64_t Hash;
Jeremy Morsebcff4172019-06-10 15:23:46 +0000197 int64_t Immediate;
198 const ConstantFP *FPImm;
199 const ConstantInt *CImm;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000200 } Loc;
201
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000202 VarLoc(const MachineInstr &MI, LexicalScopes &LS)
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000203 : Var(MI), MI(MI), UVS(MI.getDebugLoc(), LS) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000204 static_assert((sizeof(Loc) == sizeof(uint64_t)),
205 "hash does not cover all members of Loc");
206 assert(MI.isDebugValue() && "not a DBG_VALUE");
207 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
Adrian Prantl00698732016-05-25 22:37:29 +0000208 if (int RegNo = isDbgValueDescribedByReg(MI)) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000209 Kind = RegisterKind;
Adrian Prantl359846f2017-07-28 23:25:51 +0000210 Loc.RegNo = RegNo;
Jeremy Morsebcff4172019-06-10 15:23:46 +0000211 } else if (MI.getOperand(0).isImm()) {
212 Kind = ImmediateKind;
213 Loc.Immediate = MI.getOperand(0).getImm();
214 } else if (MI.getOperand(0).isFPImm()) {
215 Kind = ImmediateKind;
216 Loc.FPImm = MI.getOperand(0).getFPImm();
217 } else if (MI.getOperand(0).isCImm()) {
218 Kind = ImmediateKind;
219 Loc.CImm = MI.getOperand(0).getCImm();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000220 }
221 }
222
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000223 /// The constructor for spill locations.
224 VarLoc(const MachineInstr &MI, unsigned SpillBase, int SpillOffset,
225 LexicalScopes &LS)
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000226 : Var(MI), MI(MI), UVS(MI.getDebugLoc(), LS) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000227 assert(MI.isDebugValue() && "not a DBG_VALUE");
228 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
229 Kind = SpillLocKind;
230 Loc.SpillLocation = {SpillBase, SpillOffset};
231 }
232
Jeremy Morsebcff4172019-06-10 15:23:46 +0000233 // Is the Loc field a constant or constant object?
234 bool isConstant() const { return Kind == ImmediateKind; }
235
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000236 /// If this variable is described by a register, return it,
237 /// otherwise return 0.
238 unsigned isDescribedByReg() const {
239 if (Kind == RegisterKind)
Adrian Prantl359846f2017-07-28 23:25:51 +0000240 return Loc.RegNo;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000241 return 0;
242 }
243
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000244 /// Determine whether the lexical scope of this value's debug location
245 /// dominates MBB.
246 bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
247
Aaron Ballman615eb472017-10-15 14:32:27 +0000248#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun194ded52017-01-28 06:53:55 +0000249 LLVM_DUMP_METHOD void dump() const { MI.dump(); }
250#endif
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000251
252 bool operator==(const VarLoc &Other) const {
Jeremy Morsebcff4172019-06-10 15:23:46 +0000253 return Kind == Other.Kind && Var == Other.Var &&
254 Loc.Hash == Other.Loc.Hash;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000255 }
256
Adrian Prantl7509d542016-05-26 21:42:47 +0000257 /// This operator guarantees that VarLocs are sorted by Variable first.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000258 bool operator<(const VarLoc &Other) const {
259 if (Var == Other.Var)
260 return Loc.Hash < Other.Loc.Hash;
261 return Var < Other.Var;
262 }
Vikram TV859ad292015-12-16 11:09:48 +0000263 };
264
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000265 using VarLocMap = UniqueVector<VarLoc>;
266 using VarLocSet = SparseBitVector<>;
267 using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000268 struct TransferDebugPair {
269 MachineInstr *TransferInst;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000270 MachineInstr *DebugInst;
271 };
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000272 using TransferMap = SmallVector<TransferDebugPair, 4>;
Vikram TV859ad292015-12-16 11:09:48 +0000273
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000274 // Types for recording sets of variable fragments that overlap. For a given
275 // local variable, we record all other fragments of that variable that could
276 // overlap it, to reduce search time.
277 using FragmentOfVar =
278 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
279 using OverlapMap =
280 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
281
282 // Helper while building OverlapMap, a map of all fragments seen for a given
283 // DILocalVariable.
284 using VarToFragments =
285 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
286
Adrian Prantl7509d542016-05-26 21:42:47 +0000287 /// This holds the working set of currently open ranges. For fast
288 /// access, this is done both as a set of VarLocIDs, and a map of
289 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
290 /// previous open ranges for the same variable.
291 class OpenRangesSet {
292 VarLocSet VarLocs;
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000293 SmallDenseMap<DebugVariable, unsigned, 8> Vars;
294 OverlapMap &OverlappingFragments;
Adrian Prantl7509d542016-05-26 21:42:47 +0000295
296 public:
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000297 OpenRangesSet(OverlapMap &_OLapMap) : OverlappingFragments(_OLapMap) {}
298
Adrian Prantl7509d542016-05-26 21:42:47 +0000299 const VarLocSet &getVarLocs() const { return VarLocs; }
300
301 /// Terminate all open ranges for Var by removing it from the set.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000302 void erase(DebugVariable Var);
Adrian Prantl7509d542016-05-26 21:42:47 +0000303
304 /// Terminate all open ranges listed in \c KillSet by removing
305 /// them from the set.
306 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
307 VarLocs.intersectWithComplement(KillSet);
308 for (unsigned ID : KillSet)
309 Vars.erase(VarLocIDs[ID].Var);
310 }
311
312 /// Insert a new range into the set.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000313 void insert(unsigned VarLocID, DebugVariable Var) {
Adrian Prantl7509d542016-05-26 21:42:47 +0000314 VarLocs.set(VarLocID);
315 Vars.insert({Var, VarLocID});
316 }
317
318 /// Empty the set.
319 void clear() {
320 VarLocs.clear();
321 Vars.clear();
322 }
323
324 /// Return whether the set is empty or not.
325 bool empty() const {
326 assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
327 return VarLocs.empty();
328 }
329 };
330
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000331 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
332 unsigned &Reg);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000333 /// If a given instruction is identified as a spill, return the spill location
334 /// and set \p Reg to the spilled register.
335 Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
336 MachineFunction *MF,
337 unsigned &Reg);
338 /// Given a spill instruction, extract the register and offset used to
339 /// address the spill location in a target independent way.
340 VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000341 void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
342 TransferMap &Transfers, VarLocMap &VarLocIDs,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000343 unsigned OldVarID, TransferKind Kind,
344 unsigned NewReg = 0);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000345
Adrian Prantl7509d542016-05-26 21:42:47 +0000346 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000347 VarLocMap &VarLocIDs);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000348 void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
349 VarLocMap &VarLocIDs, TransferMap &Transfers);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000350 void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
351 VarLocMap &VarLocIDs, TransferMap &Transfers);
Adrian Prantl7509d542016-05-26 21:42:47 +0000352 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000353 const VarLocMap &VarLocIDs);
Adrian Prantl7509d542016-05-26 21:42:47 +0000354 bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000355 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
Nikola Prica441ad622019-05-27 13:51:30 +0000356
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000357 bool process(MachineInstr &MI, OpenRangesSet &OpenRanges,
358 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
Jeremy Morsed2cd9c22019-06-13 13:11:57 +0000359 TransferMap &Transfers, bool transferChanges,
360 OverlapMap &OverlapFragments, VarToFragments &SeenFragments);
Vikram TV859ad292015-12-16 11:09:48 +0000361
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000362 void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
363 OverlapMap &OLapMap);
364
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000365 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
Keith Walker83ebef52016-09-27 16:46:07 +0000366 const VarLocMap &VarLocIDs,
Vedant Kumar8c466682018-10-05 21:44:15 +0000367 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
368 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
Vikram TV859ad292015-12-16 11:09:48 +0000369
370 bool ExtendRanges(MachineFunction &MF);
371
372public:
373 static char ID;
374
375 /// Default construct and initialize the pass.
376 LiveDebugValues();
377
378 /// Tell the pass manager which passes we depend on and what
379 /// information we preserve.
380 void getAnalysisUsage(AnalysisUsage &AU) const override;
381
Derek Schuffad154c82016-03-28 17:05:30 +0000382 MachineFunctionProperties getRequiredProperties() const override {
383 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000384 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000385 }
386
Vikram TV859ad292015-12-16 11:09:48 +0000387 /// Print to ostream with a message.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000388 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
389 const VarLocMap &VarLocIDs, const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000390 raw_ostream &Out) const;
391
392 /// Calculate the liveness information for the given machine function.
393 bool runOnMachineFunction(MachineFunction &MF) override;
394};
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000395
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000396} // end anonymous namespace
Vikram TV859ad292015-12-16 11:09:48 +0000397
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000398namespace llvm {
399
400template <> struct DenseMapInfo<LiveDebugValues::DebugVariable> {
401 using DV = LiveDebugValues::DebugVariable;
402 using OptFragmentInfo = LiveDebugValues::OptFragmentInfo;
403 using FragmentInfo = LiveDebugValues::FragmentInfo;
404
405 // Empty key: no key should be generated that has no DILocalVariable.
406 static inline DV getEmptyKey() {
407 return DV(nullptr, OptFragmentInfo(), nullptr);
408 }
409
410 // Difference in tombstone is that the Optional is meaningful
411 static inline DV getTombstoneKey() {
412 return DV(nullptr, OptFragmentInfo({0, 0}), nullptr);
413 }
414
415 static unsigned getHashValue(const DV &D) {
416 unsigned HV = 0;
417 const OptFragmentInfo &Fragment = D.getFragment();
418 if (Fragment)
419 HV = DenseMapInfo<FragmentInfo>::getHashValue(*Fragment);
420
421 return hash_combine(D.getVar(), HV, D.getInlinedAt());
422 }
423
424 static bool isEqual(const DV &A, const DV &B) { return A == B; }
425};
426
David Stenberg1278a192019-06-13 14:02:55 +0000427} // namespace llvm
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000428
Vikram TV859ad292015-12-16 11:09:48 +0000429//===----------------------------------------------------------------------===//
430// Implementation
431//===----------------------------------------------------------------------===//
432
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000433const DIExpression::FragmentInfo
434 LiveDebugValues::DebugVariable::DefaultFragment = {
435 std::numeric_limits<uint64_t>::max(),
436 std::numeric_limits<uint64_t>::min()};
437
Vikram TV859ad292015-12-16 11:09:48 +0000438char LiveDebugValues::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000439
Vikram TV859ad292015-12-16 11:09:48 +0000440char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000441
Matthias Braun1527baa2017-05-25 21:26:32 +0000442INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
Vikram TV859ad292015-12-16 11:09:48 +0000443 false, false)
444
445/// Default construct and initialize the pass.
446LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
447 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
448}
449
450/// Tell the pass manager which passes we depend on and what information we
451/// preserve.
452void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
Matt Arsenaultb1630a12016-06-08 05:18:01 +0000453 AU.setPreservesCFG();
Vikram TV859ad292015-12-16 11:09:48 +0000454 MachineFunctionPass::getAnalysisUsage(AU);
455}
456
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000457/// Erase a variable from the set of open ranges, and additionally erase any
458/// fragments that may overlap it.
459void LiveDebugValues::OpenRangesSet::erase(DebugVariable Var) {
460 // Erasure helper.
461 auto DoErase = [this](DebugVariable VarToErase) {
462 auto It = Vars.find(VarToErase);
463 if (It != Vars.end()) {
464 unsigned ID = It->second;
465 VarLocs.reset(ID);
466 Vars.erase(It);
467 }
468 };
469
470 // Erase the variable/fragment that ends here.
471 DoErase(Var);
472
473 // Extract the fragment. Interpret an empty fragment as one that covers all
474 // possible bits.
475 FragmentInfo ThisFragment = Var.getFragmentDefault();
476
477 // There may be fragments that overlap the designated fragment. Look them up
478 // in the pre-computed overlap map, and erase them too.
479 auto MapIt = OverlappingFragments.find({Var.getVar(), ThisFragment});
480 if (MapIt != OverlappingFragments.end()) {
481 for (auto Fragment : MapIt->second) {
482 LiveDebugValues::OptFragmentInfo FragmentHolder;
483 if (!DebugVariable::isFragmentDefault(Fragment))
484 FragmentHolder = LiveDebugValues::OptFragmentInfo(Fragment);
485 DoErase({Var.getVar(), FragmentHolder, Var.getInlinedAt()});
486 }
487 }
488}
489
Vikram TV859ad292015-12-16 11:09:48 +0000490//===----------------------------------------------------------------------===//
491// Debug Range Extension Implementation
492//===----------------------------------------------------------------------===//
493
Matthias Braun194ded52017-01-28 06:53:55 +0000494#ifndef NDEBUG
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000495void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
496 const VarLocInMBB &V,
497 const VarLocMap &VarLocIDs,
498 const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000499 raw_ostream &Out) const {
Keith Walkerf83a19f2016-09-20 16:04:31 +0000500 Out << '\n' << msg << '\n';
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000501 for (const MachineBasicBlock &BB : MF) {
Vedant Kumar9b558382018-10-05 21:44:00 +0000502 const VarLocSet &L = V.lookup(&BB);
503 if (L.empty())
504 continue;
505 Out << "MBB: " << BB.getNumber() << ":\n";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000506 for (unsigned VLL : L) {
507 const VarLoc &VL = VarLocIDs[VLL];
Adrian Prantl7509d542016-05-26 21:42:47 +0000508 Out << " Var: " << VL.Var.getVar()->getName();
Vikram TV859ad292015-12-16 11:09:48 +0000509 Out << " MI: ";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000510 VL.dump();
Vikram TV859ad292015-12-16 11:09:48 +0000511 }
512 }
513 Out << "\n";
514}
Matthias Braun194ded52017-01-28 06:53:55 +0000515#endif
Vikram TV859ad292015-12-16 11:09:48 +0000516
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000517LiveDebugValues::VarLoc::SpillLoc
518LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000519 assert(MI.hasOneMemOperand() &&
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000520 "Spill instruction does not have exactly one memory operand?");
521 auto MMOI = MI.memoperands_begin();
522 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
523 assert(PVal->kind() == PseudoSourceValue::FixedStack &&
524 "Inconsistent memory operand in spill instruction");
525 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
526 const MachineBasicBlock *MBB = MI.getParent();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000527 unsigned Reg;
528 int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
529 return {Reg, Offset};
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000530}
531
Vikram TV859ad292015-12-16 11:09:48 +0000532/// End all previous ranges related to @MI and start a new range from @MI
533/// if it is a DBG_VALUE instr.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000534void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000535 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000536 VarLocMap &VarLocIDs) {
Vikram TV859ad292015-12-16 11:09:48 +0000537 if (!MI.isDebugValue())
538 return;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000539 const DILocalVariable *Var = MI.getDebugVariable();
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000540 const DIExpression *Expr = MI.getDebugExpression();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000541 const DILocation *DebugLoc = MI.getDebugLoc();
542 const DILocation *InlinedAt = DebugLoc->getInlinedAt();
543 assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
Vikram TV859ad292015-12-16 11:09:48 +0000544 "Expected inlined-at fields to agree");
Vikram TV859ad292015-12-16 11:09:48 +0000545
546 // End all previous ranges of Var.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000547 DebugVariable V(Var, Expr, InlinedAt);
Adrian Prantl7509d542016-05-26 21:42:47 +0000548 OpenRanges.erase(V);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000549
550 // Add the VarLoc to OpenRanges from this DBG_VALUE.
Jeremy Morsebcff4172019-06-10 15:23:46 +0000551 unsigned ID;
552 if (isDbgValueDescribedByReg(MI) || MI.getOperand(0).isImm() ||
553 MI.getOperand(0).isFPImm() || MI.getOperand(0).isCImm()) {
554 // Use normal VarLoc constructor for registers and immediates.
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000555 VarLoc VL(MI, LS);
Jeremy Morsebcff4172019-06-10 15:23:46 +0000556 ID = VarLocIDs.insert(VL);
Adrian Prantl7509d542016-05-26 21:42:47 +0000557 OpenRanges.insert(ID, VL.Var);
Jeremy Morsebcff4172019-06-10 15:23:46 +0000558 } else if (MI.hasOneMemOperand()) {
559 // It's a stack spill -- fetch spill base and offset.
560 VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
561 VarLoc VL(MI, SpillLocation.SpillBase, SpillLocation.SpillOffset, LS);
562 ID = VarLocIDs.insert(VL);
563 OpenRanges.insert(ID, VL.Var);
564 } else {
565 // This must be an undefined location. We should leave OpenRanges closed.
566 assert(MI.getOperand(0).isReg() && MI.getOperand(0).getReg() == 0 &&
567 "Unexpected non-undef DBG_VALUE encountered");
Adrian Prantl7509d542016-05-26 21:42:47 +0000568 }
Vikram TV859ad292015-12-16 11:09:48 +0000569}
570
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000571/// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
572/// with \p OldVarID should be deleted form \p OpenRanges and replaced with
573/// new VarLoc. If \p NewReg is different than default zero value then the
574/// new location will be register location created by the copy like instruction,
575/// otherwise it is variable's location on the stack.
576void LiveDebugValues::insertTransferDebugPair(
577 MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000578 VarLocMap &VarLocIDs, unsigned OldVarID, TransferKind Kind,
579 unsigned NewReg) {
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000580 const MachineInstr *DebugInstr = &VarLocIDs[OldVarID].MI;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000581 MachineFunction *MF = MI.getParent()->getParent();
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000582 MachineInstr *NewDebugInstr;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000583
Nikola Prica2d0106a2019-06-03 09:48:29 +0000584 auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &DebugInstr,
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000585 &VarLocIDs](VarLoc &VL, MachineInstr *NewDebugInstr) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000586 unsigned LocId = VarLocIDs.insert(VL);
Nikola Prica2d0106a2019-06-03 09:48:29 +0000587
588 // Close this variable's previous location range.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000589 DebugVariable V(*DebugInstr);
Nikola Prica2d0106a2019-06-03 09:48:29 +0000590 OpenRanges.erase(V);
591
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000592 OpenRanges.insert(LocId, VL.Var);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000593 // The newly created DBG_VALUE instruction NewDebugInstr must be inserted
594 // after MI. Keep track of the pairing.
595 TransferDebugPair MIP = {&MI, NewDebugInstr};
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000596 Transfers.push_back(MIP);
597 };
598
599 // End all previous ranges of Var.
600 OpenRanges.erase(VarLocIDs[OldVarID].Var);
601 switch (Kind) {
602 case TransferKind::TransferCopy: {
603 assert(NewReg &&
604 "No register supplied when handling a copy of a debug value");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000605 // Create a DBG_VALUE instruction to describe the Var in its new
606 // register location.
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000607 NewDebugInstr = BuildMI(
608 *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(),
609 DebugInstr->isIndirectDebugValue(), NewReg,
610 DebugInstr->getDebugVariable(), DebugInstr->getDebugExpression());
611 if (DebugInstr->isIndirectDebugValue())
612 NewDebugInstr->getOperand(1).setImm(DebugInstr->getOperand(1).getImm());
613 VarLoc VL(*NewDebugInstr, LS);
614 ProcessVarLoc(VL, NewDebugInstr);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000615 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register copy: ";
Craig Topper78c794a2019-06-02 01:36:48 +0000616 NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
617 /*SkipOpers*/false, /*SkipDebugLoc*/false,
618 /*AddNewLine*/true, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000619 return;
620 }
621 case TransferKind::TransferSpill: {
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000622 // Create a DBG_VALUE instruction to describe the Var in its spilled
623 // location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000624 VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000625 auto *SpillExpr = DIExpression::prepend(DebugInstr->getDebugExpression(),
Petar Jovanovice85bbf52019-05-20 10:35:57 +0000626 DIExpression::ApplyOffset,
627 SpillLocation.SpillOffset);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000628 NewDebugInstr = BuildMI(
629 *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(), true,
630 SpillLocation.SpillBase, DebugInstr->getDebugVariable(), SpillExpr);
631 VarLoc VL(*NewDebugInstr, SpillLocation.SpillBase,
632 SpillLocation.SpillOffset, LS);
633 ProcessVarLoc(VL, NewDebugInstr);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000634 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
Craig Topper78c794a2019-06-02 01:36:48 +0000635 NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
636 /*SkipOpers*/false, /*SkipDebugLoc*/false,
637 /*AddNewLine*/true, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000638 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000639 }
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000640 case TransferKind::TransferRestore: {
641 assert(NewReg &&
642 "No register supplied when handling a restore of a debug value");
643 MachineFunction *MF = MI.getMF();
644 DIBuilder DIB(*const_cast<Function &>(MF->getFunction()).getParent());
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000645 NewDebugInstr =
646 BuildMI(*MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(), false,
647 NewReg, DebugInstr->getDebugVariable(), DIB.createExpression());
648 VarLoc VL(*NewDebugInstr, LS);
649 ProcessVarLoc(VL, NewDebugInstr);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000650 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register restore: ";
Craig Topper78c794a2019-06-02 01:36:48 +0000651 NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
652 /*SkipOpers*/false, /*SkipDebugLoc*/false,
653 /*AddNewLine*/true, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000654 return;
655 }
656 }
657 llvm_unreachable("Invalid transfer kind");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000658}
659
Vikram TV859ad292015-12-16 11:09:48 +0000660/// A definition of a register may mark the end of a range.
661void LiveDebugValues::transferRegisterDef(MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000662 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000663 const VarLocMap &VarLocIDs) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +0000664 MachineFunction *MF = MI.getMF();
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000665 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
666 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000667 SparseBitVector<> KillSet;
Vikram TV859ad292015-12-16 11:09:48 +0000668 for (const MachineOperand &MO : MI.operands()) {
Adrian Prantlea8880b2017-03-03 01:08:25 +0000669 // Determine whether the operand is a register def. Assume that call
670 // instructions never clobber SP, because some backends (e.g., AArch64)
671 // never list SP in the regmask.
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000672 if (MO.isReg() && MO.isDef() && MO.getReg() &&
Adrian Prantlea8880b2017-03-03 01:08:25 +0000673 TRI->isPhysicalRegister(MO.getReg()) &&
674 !(MI.isCall() && MO.getReg() == SP)) {
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000675 // Remove ranges of all aliased registers.
676 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
Adrian Prantl7509d542016-05-26 21:42:47 +0000677 for (unsigned ID : OpenRanges.getVarLocs())
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000678 if (VarLocIDs[ID].isDescribedByReg() == *RAI)
679 KillSet.set(ID);
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000680 } else if (MO.isRegMask()) {
681 // Remove ranges of all clobbered registers. Register masks don't usually
682 // list SP as preserved. While the debug info may be off for an
683 // instruction or two around callee-cleanup calls, transferring the
684 // DEBUG_VALUE across the call is still a better user experience.
Adrian Prantl7509d542016-05-26 21:42:47 +0000685 for (unsigned ID : OpenRanges.getVarLocs()) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000686 unsigned Reg = VarLocIDs[ID].isDescribedByReg();
687 if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
688 KillSet.set(ID);
689 }
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000690 }
Vikram TV859ad292015-12-16 11:09:48 +0000691 }
Adrian Prantl7509d542016-05-26 21:42:47 +0000692 OpenRanges.erase(KillSet, VarLocIDs);
Vikram TV859ad292015-12-16 11:09:48 +0000693}
694
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000695/// Decide if @MI is a spill instruction and return true if it is. We use 2
696/// criteria to make this decision:
697/// - Is this instruction a store to a spill slot?
698/// - Is there a register operand that is both used and killed?
699/// TODO: Store optimization can fold spills into other stores (including
700/// other spills). We do not handle this yet (more than one memory operand).
701bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
702 MachineFunction *MF, unsigned &Reg) {
Sander de Smalenc91b27d2018-09-05 08:59:50 +0000703 SmallVector<const MachineMemOperand*, 1> Accesses;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000704
Fangrui Songf78650a2018-07-30 19:41:25 +0000705 // TODO: Handle multiple stores folded into one.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000706 if (!MI.hasOneMemOperand())
707 return false;
708
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000709 if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
710 return false; // This is not a spill instruction, since no valid size was
711 // returned from either function.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000712
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000713 auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
714 if (!MO.isReg() || !MO.isUse()) {
715 Reg = 0;
716 return false;
717 }
718 Reg = MO.getReg();
719 return MO.isKill();
720 };
721
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000722 for (const MachineOperand &MO : MI.operands()) {
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000723 // In a spill instruction generated by the InlineSpiller the spilled
724 // register has its kill flag set.
725 if (isKilledReg(MO, Reg))
726 return true;
727 if (Reg != 0) {
728 // Check whether next instruction kills the spilled register.
729 // FIXME: Current solution does not cover search for killed register in
730 // bundles and instructions further down the chain.
731 auto NextI = std::next(MI.getIterator());
732 // Skip next instruction that points to basic block end iterator.
733 if (MI.getParent()->end() == NextI)
734 continue;
735 unsigned RegNext;
736 for (const MachineOperand &MONext : NextI->operands()) {
737 // Return true if we came across the register from the
738 // previous spill instruction that is killed in NextI.
739 if (isKilledReg(MONext, RegNext) && RegNext == Reg)
740 return true;
741 }
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000742 }
743 }
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000744 // Return false if we didn't find spilled register.
745 return false;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000746}
747
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000748Optional<LiveDebugValues::VarLoc::SpillLoc>
749LiveDebugValues::isRestoreInstruction(const MachineInstr &MI,
750 MachineFunction *MF, unsigned &Reg) {
751 if (!MI.hasOneMemOperand())
752 return None;
753
754 // FIXME: Handle folded restore instructions with more than one memory
755 // operand.
756 if (MI.getRestoreSize(TII)) {
757 Reg = MI.getOperand(0).getReg();
758 return extractSpillBaseRegAndOffset(MI);
759 }
760 return None;
761}
762
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000763/// A spilled register may indicate that we have to end the current range of
764/// a variable and create a new one for the spill location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000765/// A restored register may indicate the reverse situation.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000766/// We don't want to insert any instructions in process(), so we just create
767/// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000768/// It will be inserted into the BB when we're done iterating over the
769/// instructions.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000770void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr &MI,
771 OpenRangesSet &OpenRanges,
772 VarLocMap &VarLocIDs,
773 TransferMap &Transfers) {
Wolfgang Piebfacd0522019-01-30 20:37:14 +0000774 MachineFunction *MF = MI.getMF();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000775 TransferKind TKind;
776 unsigned Reg;
777 Optional<VarLoc::SpillLoc> Loc;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000778
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000779 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
780
781 if (isSpillInstruction(MI, MF, Reg)) {
782 TKind = TransferKind::TransferSpill;
783 LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
784 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
785 << "\n");
786 } else {
787 if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
788 return;
789 TKind = TransferKind::TransferRestore;
790 LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
791 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
792 << "\n");
793 }
794 // Check if the register or spill location is the location of a debug value.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000795 for (unsigned ID : OpenRanges.getVarLocs()) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000796 if (TKind == TransferKind::TransferSpill &&
797 VarLocIDs[ID].isDescribedByReg() == Reg) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000798 LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
799 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000800 } else if (TKind == TransferKind::TransferRestore &&
801 VarLocIDs[ID].Loc.SpillLocation == *Loc) {
802 LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
803 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
804 } else
805 continue;
806 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID, TKind,
807 Reg);
808 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000809 }
810}
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000811
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000812/// If \p MI is a register copy instruction, that copies a previously tracked
813/// value from one register to another register that is callee saved, we
814/// create new DBG_VALUE instruction described with copy destination register.
815void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
816 OpenRangesSet &OpenRanges,
817 VarLocMap &VarLocIDs,
818 TransferMap &Transfers) {
819 const MachineOperand *SrcRegOp, *DestRegOp;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000820
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000821 if (!TII->isCopyInstr(MI, SrcRegOp, DestRegOp) || !SrcRegOp->isKill() ||
822 !DestRegOp->isDef())
823 return;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000824
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000825 auto isCalleSavedReg = [&](unsigned Reg) {
826 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
827 if (CalleeSavedRegs.test(*RAI))
828 return true;
829 return false;
830 };
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000831
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000832 unsigned SrcReg = SrcRegOp->getReg();
833 unsigned DestReg = DestRegOp->getReg();
834
835 // We want to recognize instructions where destination register is callee
836 // saved register. If register that could be clobbered by the call is
837 // included, there would be a great chance that it is going to be clobbered
838 // soon. It is more likely that previous register location, which is callee
839 // saved, is going to stay unclobbered longer, even if it is killed.
840 if (!isCalleSavedReg(DestReg))
841 return;
842
843 for (unsigned ID : OpenRanges.getVarLocs()) {
844 if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
845 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000846 TransferKind::TransferCopy, DestReg);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000847 return;
848 }
849 }
850}
851
Vikram TV859ad292015-12-16 11:09:48 +0000852/// Terminate all open ranges at the end of the current basic block.
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000853bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000854 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000855 VarLocInMBB &OutLocs,
856 const VarLocMap &VarLocIDs) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000857 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000858 const MachineBasicBlock *CurMBB = MI.getParent();
Petar Jovanovice9500ba2018-01-08 18:21:15 +0000859 if (!(MI.isTerminator() || (&MI == &CurMBB->back())))
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000860 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000861
862 if (OpenRanges.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000863 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000864
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000865 LLVM_DEBUG(for (unsigned ID
866 : OpenRanges.getVarLocs()) {
867 // Copy OpenRanges to OutLocs, if not already present.
Vedant Kumar9b558382018-10-05 21:44:00 +0000868 dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000869 VarLocIDs[ID].dump();
870 });
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000871 VarLocSet &VLS = OutLocs[CurMBB];
Adrian Prantl7509d542016-05-26 21:42:47 +0000872 Changed = VLS |= OpenRanges.getVarLocs();
Nikola Prica2d0106a2019-06-03 09:48:29 +0000873 // New OutLocs set may be different due to spill, restore or register
874 // copy instruction processing.
875 if (Changed)
876 VLS = OpenRanges.getVarLocs();
Vikram TV859ad292015-12-16 11:09:48 +0000877 OpenRanges.clear();
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000878 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000879}
880
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000881/// Accumulate a mapping between each DILocalVariable fragment and other
882/// fragments of that DILocalVariable which overlap. This reduces work during
883/// the data-flow stage from "Find any overlapping fragments" to "Check if the
884/// known-to-overlap fragments are present".
885/// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
886/// fragment usage.
887/// \param SeenFragments Map from DILocalVariable to all fragments of that
888/// Variable which are known to exist.
889/// \param OverlappingFragments The overlap map being constructed, from one
890/// Var/Fragment pair to a vector of fragments known to overlap.
891void LiveDebugValues::accumulateFragmentMap(MachineInstr &MI,
892 VarToFragments &SeenFragments,
893 OverlapMap &OverlappingFragments) {
894 DebugVariable MIVar(MI);
895 FragmentInfo ThisFragment = MIVar.getFragmentDefault();
896
897 // If this is the first sighting of this variable, then we are guaranteed
898 // there are currently no overlapping fragments either. Initialize the set
899 // of seen fragments, record no overlaps for the current one, and return.
900 auto SeenIt = SeenFragments.find(MIVar.getVar());
901 if (SeenIt == SeenFragments.end()) {
902 SmallSet<FragmentInfo, 4> OneFragment;
903 OneFragment.insert(ThisFragment);
904 SeenFragments.insert({MIVar.getVar(), OneFragment});
905
906 OverlappingFragments.insert({{MIVar.getVar(), ThisFragment}, {}});
907 return;
908 }
909
910 // If this particular Variable/Fragment pair already exists in the overlap
911 // map, it has already been accounted for.
912 auto IsInOLapMap =
913 OverlappingFragments.insert({{MIVar.getVar(), ThisFragment}, {}});
914 if (!IsInOLapMap.second)
915 return;
916
917 auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
918 auto &AllSeenFragments = SeenIt->second;
919
920 // Otherwise, examine all other seen fragments for this variable, with "this"
921 // fragment being a previously unseen fragment. Record any pair of
922 // overlapping fragments.
923 for (auto &ASeenFragment : AllSeenFragments) {
924 // Does this previously seen fragment overlap?
925 if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
926 // Yes: Mark the current fragment as being overlapped.
927 ThisFragmentsOverlaps.push_back(ASeenFragment);
928 // Mark the previously seen fragment as being overlapped by the current
929 // one.
930 auto ASeenFragmentsOverlaps =
931 OverlappingFragments.find({MIVar.getVar(), ASeenFragment});
932 assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
933 "Previously seen var fragment has no vector of overlaps");
934 ASeenFragmentsOverlaps->second.push_back(ThisFragment);
935 }
936 }
937
938 AllSeenFragments.insert(ThisFragment);
939}
940
Vikram TV859ad292015-12-16 11:09:48 +0000941/// This routine creates OpenRanges and OutLocs.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000942bool LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
943 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
Jeremy Morsed2cd9c22019-06-13 13:11:57 +0000944 TransferMap &Transfers, bool transferChanges,
945 OverlapMap &OverlapFragments,
946 VarToFragments &SeenFragments) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000947 bool Changed = false;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000948 transferDebugValue(MI, OpenRanges, VarLocIDs);
949 transferRegisterDef(MI, OpenRanges, VarLocIDs);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000950 if (transferChanges) {
951 transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000952 transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
Jeremy Morsed2cd9c22019-06-13 13:11:57 +0000953 } else {
954 // Build up a map of overlapping fragments on the first run through.
955 if (MI.isDebugValue())
956 accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000957 }
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000958 Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000959 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000960}
961
962/// This routine joins the analysis results of all incoming edges in @MBB by
963/// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
964/// source variable in all the predecessors of @MBB reside in the same location.
Vedant Kumar8c466682018-10-05 21:44:15 +0000965bool LiveDebugValues::join(
966 MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
967 const VarLocMap &VarLocIDs,
968 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
969 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
Vedant Kumar9b558382018-10-05 21:44:00 +0000970 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000971 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000972
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000973 VarLocSet InLocsT; // Temporary incoming locations.
Vikram TV859ad292015-12-16 11:09:48 +0000974
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000975 // For all predecessors of this MBB, find the set of VarLocs that
976 // can be joined.
Keith Walker83ebef52016-09-27 16:46:07 +0000977 int NumVisited = 0;
Vikram TV859ad292015-12-16 11:09:48 +0000978 for (auto p : MBB.predecessors()) {
Keith Walker83ebef52016-09-27 16:46:07 +0000979 // Ignore unvisited predecessor blocks. As we are processing
980 // the blocks in reverse post-order any unvisited block can
981 // be considered to not remove any incoming values.
Vedant Kumar9b558382018-10-05 21:44:00 +0000982 if (!Visited.count(p)) {
983 LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
984 << "\n");
Keith Walker83ebef52016-09-27 16:46:07 +0000985 continue;
Vedant Kumar9b558382018-10-05 21:44:00 +0000986 }
Vikram TV859ad292015-12-16 11:09:48 +0000987 auto OL = OutLocs.find(p);
988 // Join is null in case of empty OutLocs from any of the pred.
989 if (OL == OutLocs.end())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000990 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000991
Keith Walker83ebef52016-09-27 16:46:07 +0000992 // Just copy over the Out locs to incoming locs for the first visited
993 // predecessor, and for all other predecessors join the Out locs.
994 if (!NumVisited)
Vikram TV859ad292015-12-16 11:09:48 +0000995 InLocsT = OL->second;
Keith Walker83ebef52016-09-27 16:46:07 +0000996 else
997 InLocsT &= OL->second;
Vedant Kumar9b558382018-10-05 21:44:00 +0000998
999 LLVM_DEBUG({
1000 if (!InLocsT.empty()) {
1001 for (auto ID : InLocsT)
1002 dbgs() << " gathered candidate incoming var: "
1003 << VarLocIDs[ID].Var.getVar()->getName() << "\n";
1004 }
1005 });
1006
Keith Walker83ebef52016-09-27 16:46:07 +00001007 NumVisited++;
Vikram TV859ad292015-12-16 11:09:48 +00001008 }
1009
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001010 // Filter out DBG_VALUES that are out of scope.
1011 VarLocSet KillSet;
Vedant Kumar8c466682018-10-05 21:44:15 +00001012 bool IsArtificial = ArtificialBlocks.count(&MBB);
1013 if (!IsArtificial) {
1014 for (auto ID : InLocsT) {
1015 if (!VarLocIDs[ID].dominates(MBB)) {
1016 KillSet.set(ID);
1017 LLVM_DEBUG({
1018 auto Name = VarLocIDs[ID].Var.getVar()->getName();
1019 dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
1020 });
1021 }
Vedant Kumar9b558382018-10-05 21:44:00 +00001022 }
1023 }
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001024 InLocsT.intersectWithComplement(KillSet);
1025
Keith Walker83ebef52016-09-27 16:46:07 +00001026 // As we are processing blocks in reverse post-order we
1027 // should have processed at least one predecessor, unless it
1028 // is the entry block which has no predecessor.
1029 assert((NumVisited || MBB.pred_empty()) &&
1030 "Should have processed at least one predecessor");
Vikram TV859ad292015-12-16 11:09:48 +00001031 if (InLocsT.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001032 return false;
Vikram TV859ad292015-12-16 11:09:48 +00001033
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001034 VarLocSet &ILS = InLocs[&MBB];
Vikram TV859ad292015-12-16 11:09:48 +00001035
1036 // Insert DBG_VALUE instructions, if not already inserted.
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001037 VarLocSet Diff = InLocsT;
1038 Diff.intersectWithComplement(ILS);
1039 for (auto ID : Diff) {
1040 // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
1041 // new range is started for the var from the mbb's beginning by inserting
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001042 // a new DBG_VALUE. process() will end this range however appropriate.
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001043 const VarLoc &DiffIt = VarLocIDs[ID];
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +00001044 const MachineInstr *DebugInstr = &DiffIt.MI;
Jeremy Morsebcff4172019-06-10 15:23:46 +00001045 MachineInstr *MI = nullptr;
1046 if (DiffIt.isConstant()) {
1047 MachineOperand MO(DebugInstr->getOperand(0));
1048 MI = BuildMI(MBB, MBB.instr_begin(), DebugInstr->getDebugLoc(),
1049 DebugInstr->getDesc(), false, MO,
1050 DebugInstr->getDebugVariable(),
1051 DebugInstr->getDebugExpression());
1052 } else {
1053 MI = BuildMI(MBB, MBB.instr_begin(), DebugInstr->getDebugLoc(),
1054 DebugInstr->getDesc(), DebugInstr->isIndirectDebugValue(),
1055 DebugInstr->getOperand(0).getReg(),
1056 DebugInstr->getDebugVariable(),
1057 DebugInstr->getDebugExpression());
1058 if (DebugInstr->isIndirectDebugValue())
1059 MI->getOperand(1).setImm(DebugInstr->getOperand(1).getImm());
1060 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001061 LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001062 ILS.set(ID);
1063 ++NumInserted;
1064 Changed = true;
Vikram TV859ad292015-12-16 11:09:48 +00001065 }
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001066 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +00001067}
1068
1069/// Calculate the liveness information for the given machine function and
1070/// extend ranges across basic blocks.
1071bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001072 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
Vikram TV859ad292015-12-16 11:09:48 +00001073
1074 bool Changed = false;
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001075 bool OLChanged = false;
1076 bool MBBJoined = false;
Vikram TV859ad292015-12-16 11:09:48 +00001077
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001078 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
1079 OverlapMap OverlapFragments; // Map of overlapping variable fragments
1080 OpenRangesSet OpenRanges(OverlapFragments);
1081 // Ranges that are open until end of bb.
1082 VarLocInMBB OutLocs; // Ranges that exist beyond bb.
1083 VarLocInMBB InLocs; // Ranges that are incoming after joining.
1084 TransferMap Transfers; // DBG_VALUEs associated with spills.
1085
1086 VarToFragments SeenFragments;
Vikram TV859ad292015-12-16 11:09:48 +00001087
Vedant Kumar8c466682018-10-05 21:44:15 +00001088 // Blocks which are artificial, i.e. blocks which exclusively contain
1089 // instructions without locations, or with line 0 locations.
1090 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
1091
Daniel Berlin72560592016-01-10 18:08:32 +00001092 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
1093 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
1094 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001095 std::greater<unsigned int>>
1096 Worklist;
Daniel Berlin72560592016-01-10 18:08:32 +00001097 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001098 std::greater<unsigned int>>
1099 Pending;
1100
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001101 enum : bool { dontTransferChanges = false, transferChanges = true };
1102
Vikram TV859ad292015-12-16 11:09:48 +00001103 // Initialize every mbb with OutLocs.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001104 // We are not looking at any spill instructions during the initial pass
1105 // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
1106 // instructions for spills of registers that are known to be user variables
1107 // within the BB in which the spill occurs.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001108 for (auto &MBB : MF) {
1109 for (auto &MI : MBB) {
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001110 process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
Jeremy Morsed2cd9c22019-06-13 13:11:57 +00001111 dontTransferChanges, OverlapFragments, SeenFragments);
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001112 }
1113 }
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001114
Vedant Kumar8c466682018-10-05 21:44:15 +00001115 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
1116 if (const DebugLoc &DL = MI.getDebugLoc())
1117 return DL.getLine() != 0;
1118 return false;
1119 };
1120 for (auto &MBB : MF)
1121 if (none_of(MBB.instrs(), hasNonArtificialLocation))
1122 ArtificialBlocks.insert(&MBB);
1123
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001124 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1125 "OutLocs after initialization", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001126
Daniel Berlin72560592016-01-10 18:08:32 +00001127 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
1128 unsigned int RPONumber = 0;
1129 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
1130 OrderToBB[RPONumber] = *RI;
1131 BBToOrder[*RI] = RPONumber;
1132 Worklist.push(RPONumber);
1133 ++RPONumber;
1134 }
Daniel Berlin72560592016-01-10 18:08:32 +00001135 // This is a standard "union of predecessor outs" dataflow problem.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001136 // To solve it, we perform join() and process() using the two worklist method
Daniel Berlin72560592016-01-10 18:08:32 +00001137 // until the ranges converge.
1138 // Ranges have converged when both worklists are empty.
Keith Walker83ebef52016-09-27 16:46:07 +00001139 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
Daniel Berlin72560592016-01-10 18:08:32 +00001140 while (!Worklist.empty() || !Pending.empty()) {
1141 // We track what is on the pending worklist to avoid inserting the same
1142 // thing twice. We could avoid this with a custom priority queue, but this
1143 // is probably not worth it.
1144 SmallPtrSet<MachineBasicBlock *, 16> OnPending;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001145 LLVM_DEBUG(dbgs() << "Processing Worklist\n");
Daniel Berlin72560592016-01-10 18:08:32 +00001146 while (!Worklist.empty()) {
1147 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
1148 Worklist.pop();
Vedant Kumar8c466682018-10-05 21:44:15 +00001149 MBBJoined =
1150 join(*MBB, OutLocs, InLocs, VarLocIDs, Visited, ArtificialBlocks);
Keith Walker83ebef52016-09-27 16:46:07 +00001151 Visited.insert(MBB);
Daniel Berlin72560592016-01-10 18:08:32 +00001152 if (MBBJoined) {
1153 MBBJoined = false;
1154 Changed = true;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001155 // Now that we have started to extend ranges across BBs we need to
1156 // examine spill instructions to see whether they spill registers that
1157 // correspond to user variables.
Daniel Berlin72560592016-01-10 18:08:32 +00001158 for (auto &MI : *MBB)
Jeremy Morsed2cd9c22019-06-13 13:11:57 +00001159 OLChanged |=
1160 process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
1161 transferChanges, OverlapFragments, SeenFragments);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001162
1163 // Add any DBG_VALUE instructions necessitated by spills.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001164 for (auto &TR : Transfers)
1165 MBB->insertAfter(MachineBasicBlock::iterator(*TR.TransferInst),
1166 TR.DebugInst);
1167 Transfers.clear();
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001168
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001169 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1170 "OutLocs after propagating", dbgs()));
1171 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
1172 "InLocs after propagating", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001173
Daniel Berlin72560592016-01-10 18:08:32 +00001174 if (OLChanged) {
1175 OLChanged = false;
1176 for (auto s : MBB->successors())
Benjamin Kramer4dea8f52016-06-17 18:59:41 +00001177 if (OnPending.insert(s).second) {
Daniel Berlin72560592016-01-10 18:08:32 +00001178 Pending.push(BBToOrder[s]);
1179 }
1180 }
Vikram TV859ad292015-12-16 11:09:48 +00001181 }
1182 }
Daniel Berlin72560592016-01-10 18:08:32 +00001183 Worklist.swap(Pending);
1184 // At this point, pending must be empty, since it was just the empty
1185 // worklist
1186 assert(Pending.empty() && "Pending should be empty");
Vikram TV859ad292015-12-16 11:09:48 +00001187 }
Daniel Berlin72560592016-01-10 18:08:32 +00001188
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001189 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
1190 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001191 return Changed;
1192}
1193
1194bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001195 if (!MF.getFunction().getSubprogram())
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001196 // LiveDebugValues will already have removed all DBG_VALUEs.
1197 return false;
1198
Wolfgang Piebe018bbd2017-07-19 19:36:40 +00001199 // Skip functions from NoDebug compilation units.
Matthias Braunf1caa282017-12-15 22:22:58 +00001200 if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
Wolfgang Piebe018bbd2017-07-19 19:36:40 +00001201 DICompileUnit::NoDebug)
1202 return false;
1203
Vikram TV859ad292015-12-16 11:09:48 +00001204 TRI = MF.getSubtarget().getRegisterInfo();
1205 TII = MF.getSubtarget().getInstrInfo();
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001206 TFI = MF.getSubtarget().getFrameLowering();
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001207 TFI->determineCalleeSaves(MF, CalleeSavedRegs,
1208 make_unique<RegScavenger>().get());
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001209 LS.initialize(MF);
Vikram TV859ad292015-12-16 11:09:48 +00001210
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001211 bool Changed = ExtendRanges(MF);
Vikram TV859ad292015-12-16 11:09:48 +00001212 return Changed;
1213}