blob: 21791a92e7413c19afe292e4e1e9d9dd27fdb014 [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"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000023#include "llvm/ADT/SmallVector.h"
Adrian Prantl6ee02c72016-05-25 22:21:12 +000024#include "llvm/ADT/SparseBitVector.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000025#include "llvm/ADT/Statistic.h"
Adrian Prantl6ee02c72016-05-25 22:21:12 +000026#include "llvm/ADT/UniqueVector.h"
Adrian Prantl7f5866c2016-09-28 17:51:14 +000027#include "llvm/CodeGen/LexicalScopes.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000028#include "llvm/CodeGen/MachineBasicBlock.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000029#include "llvm/CodeGen/MachineFrameInfo.h"
Vikram TV859ad292015-12-16 11:09:48 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000032#include "llvm/CodeGen/MachineInstr.h"
Vikram TV859ad292015-12-16 11:09:48 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000034#include "llvm/CodeGen/MachineMemOperand.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000035#include "llvm/CodeGen/MachineOperand.h"
36#include "llvm/CodeGen/PseudoSourceValue.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000037#include "llvm/CodeGen/TargetFrameLowering.h"
38#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000039#include "llvm/CodeGen/TargetLowering.h"
40#include "llvm/CodeGen/TargetRegisterInfo.h"
41#include "llvm/CodeGen/TargetSubtargetInfo.h"
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +000042#include "llvm/CodeGen/RegisterScavenging.h"
Nico Weber432a3882018-04-30 14:59:11 +000043#include "llvm/Config/llvm-config.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000044#include "llvm/IR/DebugInfoMetadata.h"
45#include "llvm/IR/DebugLoc.h"
46#include "llvm/IR/Function.h"
47#include "llvm/IR/Module.h"
48#include "llvm/MC/MCRegisterInfo.h"
49#include "llvm/Pass.h"
50#include "llvm/Support/Casting.h"
51#include "llvm/Support/Compiler.h"
Vikram TV859ad292015-12-16 11:09:48 +000052#include "llvm/Support/Debug.h"
53#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000054#include <algorithm>
55#include <cassert>
56#include <cstdint>
57#include <functional>
Mehdi Aminib550cb12016-04-18 09:17:29 +000058#include <queue>
Eugene Zelenko5df3d892017-08-24 21:21:39 +000059#include <utility>
60#include <vector>
Vikram TV859ad292015-12-16 11:09:48 +000061
62using namespace llvm;
63
Matthias Braun1527baa2017-05-25 21:26:32 +000064#define DEBUG_TYPE "livedebugvalues"
Vikram TV859ad292015-12-16 11:09:48 +000065
66STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
67
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000068// If @MI is a DBG_VALUE with debug value described by a defined
Adrian Prantl6ee02c72016-05-25 22:21:12 +000069// register, returns the number of this register. In the other case, returns 0.
Adrian Prantl00698732016-05-25 22:37:29 +000070static unsigned isDbgValueDescribedByReg(const MachineInstr &MI) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +000071 assert(MI.isDebugValue() && "expected a DBG_VALUE");
72 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
73 // If location of variable is described using a register (directly
74 // or indirectly), this register is always a first operand.
75 return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0;
76}
77
Eugene Zelenko5df3d892017-08-24 21:21:39 +000078namespace {
Vikram TV859ad292015-12-16 11:09:48 +000079
Eugene Zelenko5df3d892017-08-24 21:21:39 +000080class LiveDebugValues : public MachineFunctionPass {
Vikram TV859ad292015-12-16 11:09:48 +000081private:
82 const TargetRegisterInfo *TRI;
83 const TargetInstrInfo *TII;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000084 const TargetFrameLowering *TFI;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +000085 BitVector CalleeSavedRegs;
Adrian Prantl7f5866c2016-09-28 17:51:14 +000086 LexicalScopes LS;
87
88 /// Keeps track of lexical scopes associated with a user value's source
89 /// location.
90 class UserValueScopes {
91 DebugLoc DL;
92 LexicalScopes &LS;
93 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
94
95 public:
96 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
97
98 /// Return true if current scope dominates at least one machine
99 /// instruction in a given machine basic block.
100 bool dominates(MachineBasicBlock *MBB) {
101 if (LBlocks.empty())
102 LS.getMachineBasicBlocks(DL, LBlocks);
103 return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
104 }
105 };
Vikram TV859ad292015-12-16 11:09:48 +0000106
Adrian Prantl7509d542016-05-26 21:42:47 +0000107 /// Based on std::pair so it can be used as an index into a DenseMap.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000108 using DebugVariableBase =
109 std::pair<const DILocalVariable *, const DILocation *>;
Vikram TV859ad292015-12-16 11:09:48 +0000110 /// A potentially inlined instance of a variable.
Adrian Prantl7509d542016-05-26 21:42:47 +0000111 struct DebugVariable : public DebugVariableBase {
112 DebugVariable(const DILocalVariable *Var, const DILocation *InlinedAt)
113 : DebugVariableBase(Var, InlinedAt) {}
Vikram TV859ad292015-12-16 11:09:48 +0000114
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000115 const DILocalVariable *getVar() const { return this->first; }
116 const DILocation *getInlinedAt() const { return this->second; }
Vikram TV859ad292015-12-16 11:09:48 +0000117
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000118 bool operator<(const DebugVariable &DV) const {
Adrian Prantl7509d542016-05-26 21:42:47 +0000119 if (getVar() == DV.getVar())
120 return getInlinedAt() < DV.getInlinedAt();
121 return getVar() < DV.getVar();
Vikram TV859ad292015-12-16 11:09:48 +0000122 }
123 };
124
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000125 /// A pair of debug variable and value location.
Vikram TV859ad292015-12-16 11:09:48 +0000126 struct VarLoc {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000127 const DebugVariable Var;
128 const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000129 mutable UserValueScopes UVS;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000130 enum { InvalidKind = 0, RegisterKind } Kind = InvalidKind;
Vikram TV859ad292015-12-16 11:09:48 +0000131
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000132 /// The value location. Stored separately to avoid repeatedly
133 /// extracting it from MI.
134 union {
Adrian Prantl359846f2017-07-28 23:25:51 +0000135 uint64_t RegNo;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000136 uint64_t Hash;
137 } Loc;
138
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000139 VarLoc(const MachineInstr &MI, LexicalScopes &LS)
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000140 : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000141 UVS(MI.getDebugLoc(), LS) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000142 static_assert((sizeof(Loc) == sizeof(uint64_t)),
143 "hash does not cover all members of Loc");
144 assert(MI.isDebugValue() && "not a DBG_VALUE");
145 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
Adrian Prantl00698732016-05-25 22:37:29 +0000146 if (int RegNo = isDbgValueDescribedByReg(MI)) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000147 Kind = RegisterKind;
Adrian Prantl359846f2017-07-28 23:25:51 +0000148 Loc.RegNo = RegNo;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000149 }
150 }
151
152 /// If this variable is described by a register, return it,
153 /// otherwise return 0.
154 unsigned isDescribedByReg() const {
155 if (Kind == RegisterKind)
Adrian Prantl359846f2017-07-28 23:25:51 +0000156 return Loc.RegNo;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000157 return 0;
158 }
159
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000160 /// Determine whether the lexical scope of this value's debug location
161 /// dominates MBB.
162 bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
163
Aaron Ballman615eb472017-10-15 14:32:27 +0000164#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun194ded52017-01-28 06:53:55 +0000165 LLVM_DUMP_METHOD void dump() const { MI.dump(); }
166#endif
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000167
168 bool operator==(const VarLoc &Other) const {
169 return Var == Other.Var && Loc.Hash == Other.Loc.Hash;
170 }
171
Adrian Prantl7509d542016-05-26 21:42:47 +0000172 /// This operator guarantees that VarLocs are sorted by Variable first.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000173 bool operator<(const VarLoc &Other) const {
174 if (Var == Other.Var)
175 return Loc.Hash < Other.Loc.Hash;
176 return Var < Other.Var;
177 }
Vikram TV859ad292015-12-16 11:09:48 +0000178 };
179
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000180 using VarLocMap = UniqueVector<VarLoc>;
181 using VarLocSet = SparseBitVector<>;
182 using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000183 struct TransferDebugPair {
184 MachineInstr *TransferInst;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000185 MachineInstr *DebugInst;
186 };
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000187 using TransferMap = SmallVector<TransferDebugPair, 4>;
Vikram TV859ad292015-12-16 11:09:48 +0000188
Adrian Prantl7509d542016-05-26 21:42:47 +0000189 /// This holds the working set of currently open ranges. For fast
190 /// access, this is done both as a set of VarLocIDs, and a map of
191 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
192 /// previous open ranges for the same variable.
193 class OpenRangesSet {
194 VarLocSet VarLocs;
195 SmallDenseMap<DebugVariableBase, unsigned, 8> Vars;
196
197 public:
198 const VarLocSet &getVarLocs() const { return VarLocs; }
199
200 /// Terminate all open ranges for Var by removing it from the set.
201 void erase(DebugVariable Var) {
202 auto It = Vars.find(Var);
203 if (It != Vars.end()) {
204 unsigned ID = It->second;
205 VarLocs.reset(ID);
206 Vars.erase(It);
207 }
208 }
209
210 /// Terminate all open ranges listed in \c KillSet by removing
211 /// them from the set.
212 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
213 VarLocs.intersectWithComplement(KillSet);
214 for (unsigned ID : KillSet)
215 Vars.erase(VarLocIDs[ID].Var);
216 }
217
218 /// Insert a new range into the set.
219 void insert(unsigned VarLocID, DebugVariableBase Var) {
220 VarLocs.set(VarLocID);
221 Vars.insert({Var, VarLocID});
222 }
223
224 /// Empty the set.
225 void clear() {
226 VarLocs.clear();
227 Vars.clear();
228 }
229
230 /// Return whether the set is empty or not.
231 bool empty() const {
232 assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
233 return VarLocs.empty();
234 }
235 };
236
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000237 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
238 unsigned &Reg);
239 int extractSpillBaseRegAndOffset(const MachineInstr &MI, unsigned &Reg);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000240 void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
241 TransferMap &Transfers, VarLocMap &VarLocIDs,
242 unsigned OldVarID, unsigned NewReg = 0);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000243
Adrian Prantl7509d542016-05-26 21:42:47 +0000244 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000245 VarLocMap &VarLocIDs);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000246 void transferSpillInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000247 VarLocMap &VarLocIDs, TransferMap &Transfers);
248 void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
249 VarLocMap &VarLocIDs, TransferMap &Transfers);
Adrian Prantl7509d542016-05-26 21:42:47 +0000250 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000251 const VarLocMap &VarLocIDs);
Adrian Prantl7509d542016-05-26 21:42:47 +0000252 bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000253 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000254 bool process(MachineInstr &MI, OpenRangesSet &OpenRanges,
255 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
256 TransferMap &Transfers, bool transferChanges);
Vikram TV859ad292015-12-16 11:09:48 +0000257
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000258 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
Keith Walker83ebef52016-09-27 16:46:07 +0000259 const VarLocMap &VarLocIDs,
Vedant Kumar8c466682018-10-05 21:44:15 +0000260 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
261 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
Vikram TV859ad292015-12-16 11:09:48 +0000262
263 bool ExtendRanges(MachineFunction &MF);
264
265public:
266 static char ID;
267
268 /// Default construct and initialize the pass.
269 LiveDebugValues();
270
271 /// Tell the pass manager which passes we depend on and what
272 /// information we preserve.
273 void getAnalysisUsage(AnalysisUsage &AU) const override;
274
Derek Schuffad154c82016-03-28 17:05:30 +0000275 MachineFunctionProperties getRequiredProperties() const override {
276 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000277 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000278 }
279
Vikram TV859ad292015-12-16 11:09:48 +0000280 /// Print to ostream with a message.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000281 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
282 const VarLocMap &VarLocIDs, const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000283 raw_ostream &Out) const;
284
285 /// Calculate the liveness information for the given machine function.
286 bool runOnMachineFunction(MachineFunction &MF) override;
287};
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000288
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000289} // end anonymous namespace
Vikram TV859ad292015-12-16 11:09:48 +0000290
291//===----------------------------------------------------------------------===//
292// Implementation
293//===----------------------------------------------------------------------===//
294
295char LiveDebugValues::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000296
Vikram TV859ad292015-12-16 11:09:48 +0000297char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000298
Matthias Braun1527baa2017-05-25 21:26:32 +0000299INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
Vikram TV859ad292015-12-16 11:09:48 +0000300 false, false)
301
302/// Default construct and initialize the pass.
303LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
304 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
305}
306
307/// Tell the pass manager which passes we depend on and what information we
308/// preserve.
309void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
Matt Arsenaultb1630a12016-06-08 05:18:01 +0000310 AU.setPreservesCFG();
Vikram TV859ad292015-12-16 11:09:48 +0000311 MachineFunctionPass::getAnalysisUsage(AU);
312}
313
Vikram TV859ad292015-12-16 11:09:48 +0000314//===----------------------------------------------------------------------===//
315// Debug Range Extension Implementation
316//===----------------------------------------------------------------------===//
317
Matthias Braun194ded52017-01-28 06:53:55 +0000318#ifndef NDEBUG
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000319void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
320 const VarLocInMBB &V,
321 const VarLocMap &VarLocIDs,
322 const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000323 raw_ostream &Out) const {
Keith Walkerf83a19f2016-09-20 16:04:31 +0000324 Out << '\n' << msg << '\n';
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000325 for (const MachineBasicBlock &BB : MF) {
Vedant Kumar9b558382018-10-05 21:44:00 +0000326 const VarLocSet &L = V.lookup(&BB);
327 if (L.empty())
328 continue;
329 Out << "MBB: " << BB.getNumber() << ":\n";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000330 for (unsigned VLL : L) {
331 const VarLoc &VL = VarLocIDs[VLL];
Adrian Prantl7509d542016-05-26 21:42:47 +0000332 Out << " Var: " << VL.Var.getVar()->getName();
Vikram TV859ad292015-12-16 11:09:48 +0000333 Out << " MI: ";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000334 VL.dump();
Vikram TV859ad292015-12-16 11:09:48 +0000335 }
336 }
337 Out << "\n";
338}
Matthias Braun194ded52017-01-28 06:53:55 +0000339#endif
Vikram TV859ad292015-12-16 11:09:48 +0000340
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000341/// Given a spill instruction, extract the register and offset used to
342/// address the spill location in a target independent way.
343int LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI,
344 unsigned &Reg) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000345 assert(MI.hasOneMemOperand() &&
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000346 "Spill instruction does not have exactly one memory operand?");
347 auto MMOI = MI.memoperands_begin();
348 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
349 assert(PVal->kind() == PseudoSourceValue::FixedStack &&
350 "Inconsistent memory operand in spill instruction");
351 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
352 const MachineBasicBlock *MBB = MI.getParent();
353 return TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
354}
355
Vikram TV859ad292015-12-16 11:09:48 +0000356/// End all previous ranges related to @MI and start a new range from @MI
357/// if it is a DBG_VALUE instr.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000358void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000359 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000360 VarLocMap &VarLocIDs) {
Vikram TV859ad292015-12-16 11:09:48 +0000361 if (!MI.isDebugValue())
362 return;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000363 const DILocalVariable *Var = MI.getDebugVariable();
364 const DILocation *DebugLoc = MI.getDebugLoc();
365 const DILocation *InlinedAt = DebugLoc->getInlinedAt();
366 assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
Vikram TV859ad292015-12-16 11:09:48 +0000367 "Expected inlined-at fields to agree");
Vikram TV859ad292015-12-16 11:09:48 +0000368
369 // End all previous ranges of Var.
Adrian Prantl7509d542016-05-26 21:42:47 +0000370 DebugVariable V(Var, InlinedAt);
371 OpenRanges.erase(V);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000372
373 // Add the VarLoc to OpenRanges from this DBG_VALUE.
374 // TODO: Currently handles DBG_VALUE which has only reg as location.
Adrian Prantl7509d542016-05-26 21:42:47 +0000375 if (isDbgValueDescribedByReg(MI)) {
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000376 VarLoc VL(MI, LS);
Adrian Prantl7509d542016-05-26 21:42:47 +0000377 unsigned ID = VarLocIDs.insert(VL);
378 OpenRanges.insert(ID, VL.Var);
379 }
Vikram TV859ad292015-12-16 11:09:48 +0000380}
381
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000382/// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
383/// with \p OldVarID should be deleted form \p OpenRanges and replaced with
384/// new VarLoc. If \p NewReg is different than default zero value then the
385/// new location will be register location created by the copy like instruction,
386/// otherwise it is variable's location on the stack.
387void LiveDebugValues::insertTransferDebugPair(
388 MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
389 VarLocMap &VarLocIDs, unsigned OldVarID, unsigned NewReg) {
390 const MachineInstr *DMI = &VarLocIDs[OldVarID].MI;
391 MachineFunction *MF = MI.getParent()->getParent();
392 MachineInstr *NewDMI;
393 if (NewReg) {
394 // Create a DBG_VALUE instruction to describe the Var in its new
395 // register location.
396 NewDMI = BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(),
397 DMI->isIndirectDebugValue(), NewReg,
398 DMI->getDebugVariable(), DMI->getDebugExpression());
399 if (DMI->isIndirectDebugValue())
400 NewDMI->getOperand(1).setImm(DMI->getOperand(1).getImm());
401 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register copy: ";
402 NewDMI->print(dbgs(), false, false, false, TII));
403 } else {
404 // Create a DBG_VALUE instruction to describe the Var in its spilled
405 // location.
406 unsigned SpillBase;
407 int SpillOffset = extractSpillBaseRegAndOffset(MI, SpillBase);
408 auto *SpillExpr = DIExpression::prepend(DMI->getDebugExpression(),
409 DIExpression::NoDeref, SpillOffset);
410 NewDMI = BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(), true, SpillBase,
411 DMI->getDebugVariable(), SpillExpr);
412 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
413 NewDMI->print(dbgs(), false, false, false, TII));
414 }
415
416 // The newly created DBG_VALUE instruction NewDMI must be inserted after
417 // MI. Keep track of the pairing.
418 TransferDebugPair MIP = {&MI, NewDMI};
419 Transfers.push_back(MIP);
420
421 // End all previous ranges of Var.
422 OpenRanges.erase(VarLocIDs[OldVarID].Var);
423
424 // Add the VarLoc to OpenRanges.
425 VarLoc VL(*NewDMI, LS);
426 unsigned LocID = VarLocIDs.insert(VL);
427 OpenRanges.insert(LocID, VL.Var);
428}
429
Vikram TV859ad292015-12-16 11:09:48 +0000430/// A definition of a register may mark the end of a range.
431void LiveDebugValues::transferRegisterDef(MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000432 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000433 const VarLocMap &VarLocIDs) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +0000434 MachineFunction *MF = MI.getMF();
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000435 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
436 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000437 SparseBitVector<> KillSet;
Vikram TV859ad292015-12-16 11:09:48 +0000438 for (const MachineOperand &MO : MI.operands()) {
Adrian Prantlea8880b2017-03-03 01:08:25 +0000439 // Determine whether the operand is a register def. Assume that call
440 // instructions never clobber SP, because some backends (e.g., AArch64)
441 // never list SP in the regmask.
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000442 if (MO.isReg() && MO.isDef() && MO.getReg() &&
Adrian Prantlea8880b2017-03-03 01:08:25 +0000443 TRI->isPhysicalRegister(MO.getReg()) &&
444 !(MI.isCall() && MO.getReg() == SP)) {
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000445 // Remove ranges of all aliased registers.
446 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
Adrian Prantl7509d542016-05-26 21:42:47 +0000447 for (unsigned ID : OpenRanges.getVarLocs())
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000448 if (VarLocIDs[ID].isDescribedByReg() == *RAI)
449 KillSet.set(ID);
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000450 } else if (MO.isRegMask()) {
451 // Remove ranges of all clobbered registers. Register masks don't usually
452 // list SP as preserved. While the debug info may be off for an
453 // instruction or two around callee-cleanup calls, transferring the
454 // DEBUG_VALUE across the call is still a better user experience.
Adrian Prantl7509d542016-05-26 21:42:47 +0000455 for (unsigned ID : OpenRanges.getVarLocs()) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000456 unsigned Reg = VarLocIDs[ID].isDescribedByReg();
457 if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
458 KillSet.set(ID);
459 }
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000460 }
Vikram TV859ad292015-12-16 11:09:48 +0000461 }
Adrian Prantl7509d542016-05-26 21:42:47 +0000462 OpenRanges.erase(KillSet, VarLocIDs);
Vikram TV859ad292015-12-16 11:09:48 +0000463}
464
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000465/// Decide if @MI is a spill instruction and return true if it is. We use 2
466/// criteria to make this decision:
467/// - Is this instruction a store to a spill slot?
468/// - Is there a register operand that is both used and killed?
469/// TODO: Store optimization can fold spills into other stores (including
470/// other spills). We do not handle this yet (more than one memory operand).
471bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
472 MachineFunction *MF, unsigned &Reg) {
473 const MachineFrameInfo &FrameInfo = MF->getFrameInfo();
474 int FI;
Sander de Smalenc91b27d2018-09-05 08:59:50 +0000475 SmallVector<const MachineMemOperand*, 1> Accesses;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000476
Fangrui Songf78650a2018-07-30 19:41:25 +0000477 // TODO: Handle multiple stores folded into one.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000478 if (!MI.hasOneMemOperand())
479 return false;
480
481 // To identify a spill instruction, use the same criteria as in AsmPrinter.
Sander de Smalen0c78da52018-09-03 10:23:34 +0000482 if (!((TII->isStoreToStackSlotPostFE(MI, FI) &&
483 FrameInfo.isSpillSlotObjectIndex(FI)) ||
484 (TII->hasStoreToStackSlot(MI, Accesses) &&
Sander de Smalenc91b27d2018-09-05 08:59:50 +0000485 llvm::any_of(Accesses, [&FrameInfo](const MachineMemOperand *MMO) {
486 return FrameInfo.isSpillSlotObjectIndex(
487 cast<FixedStackPseudoSourceValue>(MMO->getPseudoValue())
488 ->getFrameIndex());
Sander de Smalen0c78da52018-09-03 10:23:34 +0000489 }))))
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000490 return false;
491
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000492 auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
493 if (!MO.isReg() || !MO.isUse()) {
494 Reg = 0;
495 return false;
496 }
497 Reg = MO.getReg();
498 return MO.isKill();
499 };
500
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000501 for (const MachineOperand &MO : MI.operands()) {
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000502 // In a spill instruction generated by the InlineSpiller the spilled
503 // register has its kill flag set.
504 if (isKilledReg(MO, Reg))
505 return true;
506 if (Reg != 0) {
507 // Check whether next instruction kills the spilled register.
508 // FIXME: Current solution does not cover search for killed register in
509 // bundles and instructions further down the chain.
510 auto NextI = std::next(MI.getIterator());
511 // Skip next instruction that points to basic block end iterator.
512 if (MI.getParent()->end() == NextI)
513 continue;
514 unsigned RegNext;
515 for (const MachineOperand &MONext : NextI->operands()) {
516 // Return true if we came across the register from the
517 // previous spill instruction that is killed in NextI.
518 if (isKilledReg(MONext, RegNext) && RegNext == Reg)
519 return true;
520 }
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000521 }
522 }
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000523 // Return false if we didn't find spilled register.
524 return false;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000525}
526
527/// A spilled register may indicate that we have to end the current range of
528/// a variable and create a new one for the spill location.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000529/// We don't want to insert any instructions in process(), so we just create
530/// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000531/// It will be inserted into the BB when we're done iterating over the
532/// instructions.
533void LiveDebugValues::transferSpillInst(MachineInstr &MI,
534 OpenRangesSet &OpenRanges,
535 VarLocMap &VarLocIDs,
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000536 TransferMap &Transfers) {
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000537 unsigned Reg;
Justin Bognerfdf9bf42017-10-10 23:50:49 +0000538 MachineFunction *MF = MI.getMF();
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000539 if (!isSpillInstruction(MI, MF, Reg))
540 return;
541
542 // Check if the register is the location of a debug value.
543 for (unsigned ID : OpenRanges.getVarLocs()) {
544 if (VarLocIDs[ID].isDescribedByReg() == Reg) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000545 LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
546 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000547 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID);
548 return;
549 }
550 }
551}
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000552
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000553/// If \p MI is a register copy instruction, that copies a previously tracked
554/// value from one register to another register that is callee saved, we
555/// create new DBG_VALUE instruction described with copy destination register.
556void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
557 OpenRangesSet &OpenRanges,
558 VarLocMap &VarLocIDs,
559 TransferMap &Transfers) {
560 const MachineOperand *SrcRegOp, *DestRegOp;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000561
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000562 if (!TII->isCopyInstr(MI, SrcRegOp, DestRegOp) || !SrcRegOp->isKill() ||
563 !DestRegOp->isDef())
564 return;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000565
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000566 auto isCalleSavedReg = [&](unsigned Reg) {
567 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
568 if (CalleeSavedRegs.test(*RAI))
569 return true;
570 return false;
571 };
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000572
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000573 unsigned SrcReg = SrcRegOp->getReg();
574 unsigned DestReg = DestRegOp->getReg();
575
576 // We want to recognize instructions where destination register is callee
577 // saved register. If register that could be clobbered by the call is
578 // included, there would be a great chance that it is going to be clobbered
579 // soon. It is more likely that previous register location, which is callee
580 // saved, is going to stay unclobbered longer, even if it is killed.
581 if (!isCalleSavedReg(DestReg))
582 return;
583
584 for (unsigned ID : OpenRanges.getVarLocs()) {
585 if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
586 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
587 DestReg);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000588 return;
589 }
590 }
591}
592
Vikram TV859ad292015-12-16 11:09:48 +0000593/// Terminate all open ranges at the end of the current basic block.
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000594bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000595 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000596 VarLocInMBB &OutLocs,
597 const VarLocMap &VarLocIDs) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000598 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000599 const MachineBasicBlock *CurMBB = MI.getParent();
Petar Jovanovice9500ba2018-01-08 18:21:15 +0000600 if (!(MI.isTerminator() || (&MI == &CurMBB->back())))
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000601 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000602
603 if (OpenRanges.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000604 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000605
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000606 LLVM_DEBUG(for (unsigned ID
607 : OpenRanges.getVarLocs()) {
608 // Copy OpenRanges to OutLocs, if not already present.
Vedant Kumar9b558382018-10-05 21:44:00 +0000609 dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000610 VarLocIDs[ID].dump();
611 });
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000612 VarLocSet &VLS = OutLocs[CurMBB];
Adrian Prantl7509d542016-05-26 21:42:47 +0000613 Changed = VLS |= OpenRanges.getVarLocs();
Vikram TV859ad292015-12-16 11:09:48 +0000614 OpenRanges.clear();
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000615 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000616}
617
618/// This routine creates OpenRanges and OutLocs.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000619bool LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
620 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
621 TransferMap &Transfers, bool transferChanges) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000622 bool Changed = false;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000623 transferDebugValue(MI, OpenRanges, VarLocIDs);
624 transferRegisterDef(MI, OpenRanges, VarLocIDs);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000625 if (transferChanges) {
626 transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
627 transferSpillInst(MI, OpenRanges, VarLocIDs, Transfers);
628 }
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000629 Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000630 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000631}
632
633/// This routine joins the analysis results of all incoming edges in @MBB by
634/// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
635/// source variable in all the predecessors of @MBB reside in the same location.
Vedant Kumar8c466682018-10-05 21:44:15 +0000636bool LiveDebugValues::join(
637 MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
638 const VarLocMap &VarLocIDs,
639 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
640 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
Vedant Kumar9b558382018-10-05 21:44:00 +0000641 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000642 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000643
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000644 VarLocSet InLocsT; // Temporary incoming locations.
Vikram TV859ad292015-12-16 11:09:48 +0000645
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000646 // For all predecessors of this MBB, find the set of VarLocs that
647 // can be joined.
Keith Walker83ebef52016-09-27 16:46:07 +0000648 int NumVisited = 0;
Vikram TV859ad292015-12-16 11:09:48 +0000649 for (auto p : MBB.predecessors()) {
Keith Walker83ebef52016-09-27 16:46:07 +0000650 // Ignore unvisited predecessor blocks. As we are processing
651 // the blocks in reverse post-order any unvisited block can
652 // be considered to not remove any incoming values.
Vedant Kumar9b558382018-10-05 21:44:00 +0000653 if (!Visited.count(p)) {
654 LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
655 << "\n");
Keith Walker83ebef52016-09-27 16:46:07 +0000656 continue;
Vedant Kumar9b558382018-10-05 21:44:00 +0000657 }
Vikram TV859ad292015-12-16 11:09:48 +0000658 auto OL = OutLocs.find(p);
659 // Join is null in case of empty OutLocs from any of the pred.
660 if (OL == OutLocs.end())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000661 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000662
Keith Walker83ebef52016-09-27 16:46:07 +0000663 // Just copy over the Out locs to incoming locs for the first visited
664 // predecessor, and for all other predecessors join the Out locs.
665 if (!NumVisited)
Vikram TV859ad292015-12-16 11:09:48 +0000666 InLocsT = OL->second;
Keith Walker83ebef52016-09-27 16:46:07 +0000667 else
668 InLocsT &= OL->second;
Vedant Kumar9b558382018-10-05 21:44:00 +0000669
670 LLVM_DEBUG({
671 if (!InLocsT.empty()) {
672 for (auto ID : InLocsT)
673 dbgs() << " gathered candidate incoming var: "
674 << VarLocIDs[ID].Var.getVar()->getName() << "\n";
675 }
676 });
677
Keith Walker83ebef52016-09-27 16:46:07 +0000678 NumVisited++;
Vikram TV859ad292015-12-16 11:09:48 +0000679 }
680
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000681 // Filter out DBG_VALUES that are out of scope.
682 VarLocSet KillSet;
Vedant Kumar8c466682018-10-05 21:44:15 +0000683 bool IsArtificial = ArtificialBlocks.count(&MBB);
684 if (!IsArtificial) {
685 for (auto ID : InLocsT) {
686 if (!VarLocIDs[ID].dominates(MBB)) {
687 KillSet.set(ID);
688 LLVM_DEBUG({
689 auto Name = VarLocIDs[ID].Var.getVar()->getName();
690 dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
691 });
692 }
Vedant Kumar9b558382018-10-05 21:44:00 +0000693 }
694 }
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000695 InLocsT.intersectWithComplement(KillSet);
696
Keith Walker83ebef52016-09-27 16:46:07 +0000697 // As we are processing blocks in reverse post-order we
698 // should have processed at least one predecessor, unless it
699 // is the entry block which has no predecessor.
700 assert((NumVisited || MBB.pred_empty()) &&
701 "Should have processed at least one predecessor");
Vikram TV859ad292015-12-16 11:09:48 +0000702 if (InLocsT.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000703 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000704
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000705 VarLocSet &ILS = InLocs[&MBB];
Vikram TV859ad292015-12-16 11:09:48 +0000706
707 // Insert DBG_VALUE instructions, if not already inserted.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000708 VarLocSet Diff = InLocsT;
709 Diff.intersectWithComplement(ILS);
710 for (auto ID : Diff) {
711 // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
712 // new range is started for the var from the mbb's beginning by inserting
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000713 // a new DBG_VALUE. process() will end this range however appropriate.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000714 const VarLoc &DiffIt = VarLocIDs[ID];
715 const MachineInstr *DMI = &DiffIt.MI;
716 MachineInstr *MI =
717 BuildMI(MBB, MBB.instr_begin(), DMI->getDebugLoc(), DMI->getDesc(),
Adrian Prantl8b9bb532017-07-28 23:00:45 +0000718 DMI->isIndirectDebugValue(), DMI->getOperand(0).getReg(),
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000719 DMI->getDebugVariable(), DMI->getDebugExpression());
720 if (DMI->isIndirectDebugValue())
721 MI->getOperand(1).setImm(DMI->getOperand(1).getImm());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000722 LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000723 ILS.set(ID);
724 ++NumInserted;
725 Changed = true;
Vikram TV859ad292015-12-16 11:09:48 +0000726 }
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000727 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000728}
729
730/// Calculate the liveness information for the given machine function and
731/// extend ranges across basic blocks.
732bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000733 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
Vikram TV859ad292015-12-16 11:09:48 +0000734
735 bool Changed = false;
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000736 bool OLChanged = false;
737 bool MBBJoined = false;
Vikram TV859ad292015-12-16 11:09:48 +0000738
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000739 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
Adrian Prantl7509d542016-05-26 21:42:47 +0000740 OpenRangesSet OpenRanges; // Ranges that are open until end of bb.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000741 VarLocInMBB OutLocs; // Ranges that exist beyond bb.
742 VarLocInMBB InLocs; // Ranges that are incoming after joining.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000743 TransferMap Transfers; // DBG_VALUEs associated with spills.
Vikram TV859ad292015-12-16 11:09:48 +0000744
Vedant Kumar8c466682018-10-05 21:44:15 +0000745 // Blocks which are artificial, i.e. blocks which exclusively contain
746 // instructions without locations, or with line 0 locations.
747 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
748
Daniel Berlin72560592016-01-10 18:08:32 +0000749 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
750 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
751 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000752 std::greater<unsigned int>>
753 Worklist;
Daniel Berlin72560592016-01-10 18:08:32 +0000754 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000755 std::greater<unsigned int>>
756 Pending;
757
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000758 enum : bool { dontTransferChanges = false, transferChanges = true };
759
Vikram TV859ad292015-12-16 11:09:48 +0000760 // Initialize every mbb with OutLocs.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000761 // We are not looking at any spill instructions during the initial pass
762 // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
763 // instructions for spills of registers that are known to be user variables
764 // within the BB in which the spill occurs.
Vikram TV859ad292015-12-16 11:09:48 +0000765 for (auto &MBB : MF)
766 for (auto &MI : MBB)
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000767 process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
768 dontTransferChanges);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000769
Vedant Kumar8c466682018-10-05 21:44:15 +0000770 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
771 if (const DebugLoc &DL = MI.getDebugLoc())
772 return DL.getLine() != 0;
773 return false;
774 };
775 for (auto &MBB : MF)
776 if (none_of(MBB.instrs(), hasNonArtificialLocation))
777 ArtificialBlocks.insert(&MBB);
778
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000779 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
780 "OutLocs after initialization", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000781
Daniel Berlin72560592016-01-10 18:08:32 +0000782 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
783 unsigned int RPONumber = 0;
784 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
785 OrderToBB[RPONumber] = *RI;
786 BBToOrder[*RI] = RPONumber;
787 Worklist.push(RPONumber);
788 ++RPONumber;
789 }
Daniel Berlin72560592016-01-10 18:08:32 +0000790 // This is a standard "union of predecessor outs" dataflow problem.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000791 // To solve it, we perform join() and process() using the two worklist method
Daniel Berlin72560592016-01-10 18:08:32 +0000792 // until the ranges converge.
793 // Ranges have converged when both worklists are empty.
Keith Walker83ebef52016-09-27 16:46:07 +0000794 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
Daniel Berlin72560592016-01-10 18:08:32 +0000795 while (!Worklist.empty() || !Pending.empty()) {
796 // We track what is on the pending worklist to avoid inserting the same
797 // thing twice. We could avoid this with a custom priority queue, but this
798 // is probably not worth it.
799 SmallPtrSet<MachineBasicBlock *, 16> OnPending;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000800 LLVM_DEBUG(dbgs() << "Processing Worklist\n");
Daniel Berlin72560592016-01-10 18:08:32 +0000801 while (!Worklist.empty()) {
802 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
803 Worklist.pop();
Vedant Kumar8c466682018-10-05 21:44:15 +0000804 MBBJoined =
805 join(*MBB, OutLocs, InLocs, VarLocIDs, Visited, ArtificialBlocks);
Keith Walker83ebef52016-09-27 16:46:07 +0000806 Visited.insert(MBB);
Daniel Berlin72560592016-01-10 18:08:32 +0000807 if (MBBJoined) {
808 MBBJoined = false;
809 Changed = true;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000810 // Now that we have started to extend ranges across BBs we need to
811 // examine spill instructions to see whether they spill registers that
812 // correspond to user variables.
Daniel Berlin72560592016-01-10 18:08:32 +0000813 for (auto &MI : *MBB)
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000814 OLChanged |= process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
815 transferChanges);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000816
817 // Add any DBG_VALUE instructions necessitated by spills.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000818 for (auto &TR : Transfers)
819 MBB->insertAfter(MachineBasicBlock::iterator(*TR.TransferInst),
820 TR.DebugInst);
821 Transfers.clear();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000822
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000823 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
824 "OutLocs after propagating", dbgs()));
825 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
826 "InLocs after propagating", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000827
Daniel Berlin72560592016-01-10 18:08:32 +0000828 if (OLChanged) {
829 OLChanged = false;
830 for (auto s : MBB->successors())
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000831 if (OnPending.insert(s).second) {
Daniel Berlin72560592016-01-10 18:08:32 +0000832 Pending.push(BBToOrder[s]);
833 }
834 }
Vikram TV859ad292015-12-16 11:09:48 +0000835 }
836 }
Daniel Berlin72560592016-01-10 18:08:32 +0000837 Worklist.swap(Pending);
838 // At this point, pending must be empty, since it was just the empty
839 // worklist
840 assert(Pending.empty() && "Pending should be empty");
Vikram TV859ad292015-12-16 11:09:48 +0000841 }
Daniel Berlin72560592016-01-10 18:08:32 +0000842
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000843 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
844 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000845 return Changed;
846}
847
848bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000849 if (!MF.getFunction().getSubprogram())
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000850 // LiveDebugValues will already have removed all DBG_VALUEs.
851 return false;
852
Wolfgang Piebe018bbd2017-07-19 19:36:40 +0000853 // Skip functions from NoDebug compilation units.
Matthias Braunf1caa282017-12-15 22:22:58 +0000854 if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
Wolfgang Piebe018bbd2017-07-19 19:36:40 +0000855 DICompileUnit::NoDebug)
856 return false;
857
Vikram TV859ad292015-12-16 11:09:48 +0000858 TRI = MF.getSubtarget().getRegisterInfo();
859 TII = MF.getSubtarget().getInstrInfo();
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000860 TFI = MF.getSubtarget().getFrameLowering();
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000861 TFI->determineCalleeSaves(MF, CalleeSavedRegs,
862 make_unique<RegScavenger>().get());
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000863 LS.initialize(MF);
Vikram TV859ad292015-12-16 11:09:48 +0000864
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000865 bool Changed = ExtendRanges(MF);
Vikram TV859ad292015-12-16 11:09:48 +0000866 return Changed;
867}