LiveDebugValues.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. //===- LiveDebugValues.cpp - Tracking Debug Value MIs ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// This pass implements a data flow analysis that propagates debug location
  11. /// information by inserting additional DBG_VALUE instructions into the machine
  12. /// instruction stream. The pass internally builds debug location liveness
  13. /// ranges to determine the points where additional DBG_VALUEs need to be
  14. /// inserted.
  15. ///
  16. /// This is a separate pass from DbgValueHistoryCalculator to facilitate
  17. /// testing and improve modularity.
  18. ///
  19. //===----------------------------------------------------------------------===//
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/PostOrderIterator.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/SparseBitVector.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/ADT/UniqueVector.h"
  27. #include "llvm/CodeGen/LexicalScopes.h"
  28. #include "llvm/CodeGen/MachineBasicBlock.h"
  29. #include "llvm/CodeGen/MachineFrameInfo.h"
  30. #include "llvm/CodeGen/MachineFunction.h"
  31. #include "llvm/CodeGen/MachineFunctionPass.h"
  32. #include "llvm/CodeGen/MachineInstr.h"
  33. #include "llvm/CodeGen/MachineInstrBuilder.h"
  34. #include "llvm/CodeGen/MachineMemOperand.h"
  35. #include "llvm/CodeGen/MachineModuleInfo.h"
  36. #include "llvm/CodeGen/MachineOperand.h"
  37. #include "llvm/CodeGen/PseudoSourceValue.h"
  38. #include "llvm/IR/DebugInfoMetadata.h"
  39. #include "llvm/IR/DebugLoc.h"
  40. #include "llvm/IR/Function.h"
  41. #include "llvm/IR/Module.h"
  42. #include "llvm/MC/MCRegisterInfo.h"
  43. #include "llvm/Pass.h"
  44. #include "llvm/Support/Casting.h"
  45. #include "llvm/Support/Compiler.h"
  46. #include "llvm/Support/Debug.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include "llvm/Target/TargetFrameLowering.h"
  49. #include "llvm/Target/TargetInstrInfo.h"
  50. #include "llvm/Target/TargetLowering.h"
  51. #include "llvm/Target/TargetRegisterInfo.h"
  52. #include "llvm/Target/TargetSubtargetInfo.h"
  53. #include <algorithm>
  54. #include <cassert>
  55. #include <cstdint>
  56. #include <functional>
  57. #include <queue>
  58. #include <utility>
  59. #include <vector>
  60. using namespace llvm;
  61. #define DEBUG_TYPE "livedebugvalues"
  62. STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
  63. // \brief If @MI is a DBG_VALUE with debug value described by a defined
  64. // register, returns the number of this register. In the other case, returns 0.
  65. static unsigned isDbgValueDescribedByReg(const MachineInstr &MI) {
  66. assert(MI.isDebugValue() && "expected a DBG_VALUE");
  67. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  68. // If location of variable is described using a register (directly
  69. // or indirectly), this register is always a first operand.
  70. return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0;
  71. }
  72. namespace {
  73. class LiveDebugValues : public MachineFunctionPass {
  74. private:
  75. const TargetRegisterInfo *TRI;
  76. const TargetInstrInfo *TII;
  77. const TargetFrameLowering *TFI;
  78. LexicalScopes LS;
  79. /// Keeps track of lexical scopes associated with a user value's source
  80. /// location.
  81. class UserValueScopes {
  82. DebugLoc DL;
  83. LexicalScopes &LS;
  84. SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
  85. public:
  86. UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
  87. /// Return true if current scope dominates at least one machine
  88. /// instruction in a given machine basic block.
  89. bool dominates(MachineBasicBlock *MBB) {
  90. if (LBlocks.empty())
  91. LS.getMachineBasicBlocks(DL, LBlocks);
  92. return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
  93. }
  94. };
  95. /// Based on std::pair so it can be used as an index into a DenseMap.
  96. using DebugVariableBase =
  97. std::pair<const DILocalVariable *, const DILocation *>;
  98. /// A potentially inlined instance of a variable.
  99. struct DebugVariable : public DebugVariableBase {
  100. DebugVariable(const DILocalVariable *Var, const DILocation *InlinedAt)
  101. : DebugVariableBase(Var, InlinedAt) {}
  102. const DILocalVariable *getVar() const { return this->first; }
  103. const DILocation *getInlinedAt() const { return this->second; }
  104. bool operator<(const DebugVariable &DV) const {
  105. if (getVar() == DV.getVar())
  106. return getInlinedAt() < DV.getInlinedAt();
  107. return getVar() < DV.getVar();
  108. }
  109. };
  110. /// A pair of debug variable and value location.
  111. struct VarLoc {
  112. const DebugVariable Var;
  113. const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
  114. mutable UserValueScopes UVS;
  115. enum { InvalidKind = 0, RegisterKind } Kind = InvalidKind;
  116. /// The value location. Stored separately to avoid repeatedly
  117. /// extracting it from MI.
  118. union {
  119. uint64_t RegNo;
  120. uint64_t Hash;
  121. } Loc;
  122. VarLoc(const MachineInstr &MI, LexicalScopes &LS)
  123. : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
  124. UVS(MI.getDebugLoc(), LS) {
  125. static_assert((sizeof(Loc) == sizeof(uint64_t)),
  126. "hash does not cover all members of Loc");
  127. assert(MI.isDebugValue() && "not a DBG_VALUE");
  128. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  129. if (int RegNo = isDbgValueDescribedByReg(MI)) {
  130. Kind = RegisterKind;
  131. Loc.RegNo = RegNo;
  132. }
  133. }
  134. /// If this variable is described by a register, return it,
  135. /// otherwise return 0.
  136. unsigned isDescribedByReg() const {
  137. if (Kind == RegisterKind)
  138. return Loc.RegNo;
  139. return 0;
  140. }
  141. /// Determine whether the lexical scope of this value's debug location
  142. /// dominates MBB.
  143. bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
  144. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  145. LLVM_DUMP_METHOD void dump() const { MI.dump(); }
  146. #endif
  147. bool operator==(const VarLoc &Other) const {
  148. return Var == Other.Var && Loc.Hash == Other.Loc.Hash;
  149. }
  150. /// This operator guarantees that VarLocs are sorted by Variable first.
  151. bool operator<(const VarLoc &Other) const {
  152. if (Var == Other.Var)
  153. return Loc.Hash < Other.Loc.Hash;
  154. return Var < Other.Var;
  155. }
  156. };
  157. using VarLocMap = UniqueVector<VarLoc>;
  158. using VarLocSet = SparseBitVector<>;
  159. using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
  160. struct SpillDebugPair {
  161. MachineInstr *SpillInst;
  162. MachineInstr *DebugInst;
  163. };
  164. using SpillMap = SmallVector<SpillDebugPair, 4>;
  165. /// This holds the working set of currently open ranges. For fast
  166. /// access, this is done both as a set of VarLocIDs, and a map of
  167. /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
  168. /// previous open ranges for the same variable.
  169. class OpenRangesSet {
  170. VarLocSet VarLocs;
  171. SmallDenseMap<DebugVariableBase, unsigned, 8> Vars;
  172. public:
  173. const VarLocSet &getVarLocs() const { return VarLocs; }
  174. /// Terminate all open ranges for Var by removing it from the set.
  175. void erase(DebugVariable Var) {
  176. auto It = Vars.find(Var);
  177. if (It != Vars.end()) {
  178. unsigned ID = It->second;
  179. VarLocs.reset(ID);
  180. Vars.erase(It);
  181. }
  182. }
  183. /// Terminate all open ranges listed in \c KillSet by removing
  184. /// them from the set.
  185. void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
  186. VarLocs.intersectWithComplement(KillSet);
  187. for (unsigned ID : KillSet)
  188. Vars.erase(VarLocIDs[ID].Var);
  189. }
  190. /// Insert a new range into the set.
  191. void insert(unsigned VarLocID, DebugVariableBase Var) {
  192. VarLocs.set(VarLocID);
  193. Vars.insert({Var, VarLocID});
  194. }
  195. /// Empty the set.
  196. void clear() {
  197. VarLocs.clear();
  198. Vars.clear();
  199. }
  200. /// Return whether the set is empty or not.
  201. bool empty() const {
  202. assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
  203. return VarLocs.empty();
  204. }
  205. };
  206. bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
  207. unsigned &Reg);
  208. int extractSpillBaseRegAndOffset(const MachineInstr &MI, unsigned &Reg);
  209. void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
  210. VarLocMap &VarLocIDs);
  211. void transferSpillInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
  212. VarLocMap &VarLocIDs, SpillMap &Spills);
  213. void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
  214. const VarLocMap &VarLocIDs);
  215. bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
  216. VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
  217. bool transfer(MachineInstr &MI, OpenRangesSet &OpenRanges,
  218. VarLocInMBB &OutLocs, VarLocMap &VarLocIDs, SpillMap &Spills,
  219. bool transferSpills);
  220. bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
  221. const VarLocMap &VarLocIDs,
  222. SmallPtrSet<const MachineBasicBlock *, 16> &Visited);
  223. bool ExtendRanges(MachineFunction &MF);
  224. public:
  225. static char ID;
  226. /// Default construct and initialize the pass.
  227. LiveDebugValues();
  228. /// Tell the pass manager which passes we depend on and what
  229. /// information we preserve.
  230. void getAnalysisUsage(AnalysisUsage &AU) const override;
  231. MachineFunctionProperties getRequiredProperties() const override {
  232. return MachineFunctionProperties().set(
  233. MachineFunctionProperties::Property::NoVRegs);
  234. }
  235. /// Print to ostream with a message.
  236. void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
  237. const VarLocMap &VarLocIDs, const char *msg,
  238. raw_ostream &Out) const;
  239. /// Calculate the liveness information for the given machine function.
  240. bool runOnMachineFunction(MachineFunction &MF) override;
  241. };
  242. } // end anonymous namespace
  243. //===----------------------------------------------------------------------===//
  244. // Implementation
  245. //===----------------------------------------------------------------------===//
  246. char LiveDebugValues::ID = 0;
  247. char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
  248. INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
  249. false, false)
  250. /// Default construct and initialize the pass.
  251. LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
  252. initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
  253. }
  254. /// Tell the pass manager which passes we depend on and what information we
  255. /// preserve.
  256. void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
  257. AU.setPreservesCFG();
  258. MachineFunctionPass::getAnalysisUsage(AU);
  259. }
  260. //===----------------------------------------------------------------------===//
  261. // Debug Range Extension Implementation
  262. //===----------------------------------------------------------------------===//
  263. #ifndef NDEBUG
  264. void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
  265. const VarLocInMBB &V,
  266. const VarLocMap &VarLocIDs,
  267. const char *msg,
  268. raw_ostream &Out) const {
  269. Out << '\n' << msg << '\n';
  270. for (const MachineBasicBlock &BB : MF) {
  271. const auto &L = V.lookup(&BB);
  272. Out << "MBB: " << BB.getName() << ":\n";
  273. for (unsigned VLL : L) {
  274. const VarLoc &VL = VarLocIDs[VLL];
  275. Out << " Var: " << VL.Var.getVar()->getName();
  276. Out << " MI: ";
  277. VL.dump();
  278. }
  279. }
  280. Out << "\n";
  281. }
  282. #endif
  283. /// Given a spill instruction, extract the register and offset used to
  284. /// address the spill location in a target independent way.
  285. int LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI,
  286. unsigned &Reg) {
  287. assert(MI.hasOneMemOperand() &&
  288. "Spill instruction does not have exactly one memory operand?");
  289. auto MMOI = MI.memoperands_begin();
  290. const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
  291. assert(PVal->kind() == PseudoSourceValue::FixedStack &&
  292. "Inconsistent memory operand in spill instruction");
  293. int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
  294. const MachineBasicBlock *MBB = MI.getParent();
  295. return TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
  296. }
  297. /// End all previous ranges related to @MI and start a new range from @MI
  298. /// if it is a DBG_VALUE instr.
  299. void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
  300. OpenRangesSet &OpenRanges,
  301. VarLocMap &VarLocIDs) {
  302. if (!MI.isDebugValue())
  303. return;
  304. const DILocalVariable *Var = MI.getDebugVariable();
  305. const DILocation *DebugLoc = MI.getDebugLoc();
  306. const DILocation *InlinedAt = DebugLoc->getInlinedAt();
  307. assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
  308. "Expected inlined-at fields to agree");
  309. // End all previous ranges of Var.
  310. DebugVariable V(Var, InlinedAt);
  311. OpenRanges.erase(V);
  312. // Add the VarLoc to OpenRanges from this DBG_VALUE.
  313. // TODO: Currently handles DBG_VALUE which has only reg as location.
  314. if (isDbgValueDescribedByReg(MI)) {
  315. VarLoc VL(MI, LS);
  316. unsigned ID = VarLocIDs.insert(VL);
  317. OpenRanges.insert(ID, VL.Var);
  318. }
  319. }
  320. /// A definition of a register may mark the end of a range.
  321. void LiveDebugValues::transferRegisterDef(MachineInstr &MI,
  322. OpenRangesSet &OpenRanges,
  323. const VarLocMap &VarLocIDs) {
  324. MachineFunction *MF = MI.getMF();
  325. const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
  326. unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
  327. SparseBitVector<> KillSet;
  328. for (const MachineOperand &MO : MI.operands()) {
  329. // Determine whether the operand is a register def. Assume that call
  330. // instructions never clobber SP, because some backends (e.g., AArch64)
  331. // never list SP in the regmask.
  332. if (MO.isReg() && MO.isDef() && MO.getReg() &&
  333. TRI->isPhysicalRegister(MO.getReg()) &&
  334. !(MI.isCall() && MO.getReg() == SP)) {
  335. // Remove ranges of all aliased registers.
  336. for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
  337. for (unsigned ID : OpenRanges.getVarLocs())
  338. if (VarLocIDs[ID].isDescribedByReg() == *RAI)
  339. KillSet.set(ID);
  340. } else if (MO.isRegMask()) {
  341. // Remove ranges of all clobbered registers. Register masks don't usually
  342. // list SP as preserved. While the debug info may be off for an
  343. // instruction or two around callee-cleanup calls, transferring the
  344. // DEBUG_VALUE across the call is still a better user experience.
  345. for (unsigned ID : OpenRanges.getVarLocs()) {
  346. unsigned Reg = VarLocIDs[ID].isDescribedByReg();
  347. if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
  348. KillSet.set(ID);
  349. }
  350. }
  351. }
  352. OpenRanges.erase(KillSet, VarLocIDs);
  353. }
  354. /// Decide if @MI is a spill instruction and return true if it is. We use 2
  355. /// criteria to make this decision:
  356. /// - Is this instruction a store to a spill slot?
  357. /// - Is there a register operand that is both used and killed?
  358. /// TODO: Store optimization can fold spills into other stores (including
  359. /// other spills). We do not handle this yet (more than one memory operand).
  360. bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
  361. MachineFunction *MF, unsigned &Reg) {
  362. const MachineFrameInfo &FrameInfo = MF->getFrameInfo();
  363. int FI;
  364. const MachineMemOperand *MMO;
  365. // TODO: Handle multiple stores folded into one.
  366. if (!MI.hasOneMemOperand())
  367. return false;
  368. // To identify a spill instruction, use the same criteria as in AsmPrinter.
  369. if (!((TII->isStoreToStackSlotPostFE(MI, FI) ||
  370. TII->hasStoreToStackSlot(MI, MMO, FI)) &&
  371. FrameInfo.isSpillSlotObjectIndex(FI)))
  372. return false;
  373. // In a spill instruction generated by the InlineSpiller the spilled register
  374. // has its kill flag set. Return false if we don't find such a register.
  375. Reg = 0;
  376. for (const MachineOperand &MO : MI.operands()) {
  377. if (MO.isReg() && MO.isUse() && MO.isKill()) {
  378. Reg = MO.getReg();
  379. break;
  380. }
  381. }
  382. return Reg != 0;
  383. }
  384. /// A spilled register may indicate that we have to end the current range of
  385. /// a variable and create a new one for the spill location.
  386. /// We don't want to insert any instructions in transfer(), so we just create
  387. /// the DBG_VALUE witout inserting it and keep track of it in @Spills.
  388. /// It will be inserted into the BB when we're done iterating over the
  389. /// instructions.
  390. void LiveDebugValues::transferSpillInst(MachineInstr &MI,
  391. OpenRangesSet &OpenRanges,
  392. VarLocMap &VarLocIDs,
  393. SpillMap &Spills) {
  394. unsigned Reg;
  395. MachineFunction *MF = MI.getMF();
  396. if (!isSpillInstruction(MI, MF, Reg))
  397. return;
  398. // Check if the register is the location of a debug value.
  399. for (unsigned ID : OpenRanges.getVarLocs()) {
  400. if (VarLocIDs[ID].isDescribedByReg() == Reg) {
  401. DEBUG(dbgs() << "Spilling Register " << PrintReg(Reg, TRI) << '('
  402. << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
  403. // Create a DBG_VALUE instruction to describe the Var in its spilled
  404. // location, but don't insert it yet to avoid invalidating the
  405. // iterator in our caller.
  406. unsigned SpillBase;
  407. int SpillOffset = extractSpillBaseRegAndOffset(MI, SpillBase);
  408. const MachineInstr *DMI = &VarLocIDs[ID].MI;
  409. auto *SpillExpr = DIExpression::prepend(
  410. DMI->getDebugExpression(), DIExpression::NoDeref, SpillOffset);
  411. MachineInstr *SpDMI =
  412. BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(), true, SpillBase,
  413. DMI->getDebugVariable(), SpillExpr);
  414. DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
  415. SpDMI->print(dbgs(), false, TII));
  416. // The newly created DBG_VALUE instruction SpDMI must be inserted after
  417. // MI. Keep track of the pairing.
  418. SpillDebugPair MIP = {&MI, SpDMI};
  419. Spills.push_back(MIP);
  420. // End all previous ranges of Var.
  421. OpenRanges.erase(VarLocIDs[ID].Var);
  422. // Add the VarLoc to OpenRanges.
  423. VarLoc VL(*SpDMI, LS);
  424. unsigned SpillLocID = VarLocIDs.insert(VL);
  425. OpenRanges.insert(SpillLocID, VL.Var);
  426. return;
  427. }
  428. }
  429. }
  430. /// Terminate all open ranges at the end of the current basic block.
  431. bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
  432. OpenRangesSet &OpenRanges,
  433. VarLocInMBB &OutLocs,
  434. const VarLocMap &VarLocIDs) {
  435. bool Changed = false;
  436. const MachineBasicBlock *CurMBB = MI.getParent();
  437. if (!(MI.isTerminator() || (&MI == &CurMBB->instr_back())))
  438. return false;
  439. if (OpenRanges.empty())
  440. return false;
  441. DEBUG(for (unsigned ID : OpenRanges.getVarLocs()) {
  442. // Copy OpenRanges to OutLocs, if not already present.
  443. dbgs() << "Add to OutLocs: "; VarLocIDs[ID].dump();
  444. });
  445. VarLocSet &VLS = OutLocs[CurMBB];
  446. Changed = VLS |= OpenRanges.getVarLocs();
  447. OpenRanges.clear();
  448. return Changed;
  449. }
  450. /// This routine creates OpenRanges and OutLocs.
  451. bool LiveDebugValues::transfer(MachineInstr &MI, OpenRangesSet &OpenRanges,
  452. VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
  453. SpillMap &Spills, bool transferSpills) {
  454. bool Changed = false;
  455. transferDebugValue(MI, OpenRanges, VarLocIDs);
  456. transferRegisterDef(MI, OpenRanges, VarLocIDs);
  457. if (transferSpills)
  458. transferSpillInst(MI, OpenRanges, VarLocIDs, Spills);
  459. Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
  460. return Changed;
  461. }
  462. /// This routine joins the analysis results of all incoming edges in @MBB by
  463. /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
  464. /// source variable in all the predecessors of @MBB reside in the same location.
  465. bool LiveDebugValues::join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs,
  466. VarLocInMBB &InLocs, const VarLocMap &VarLocIDs,
  467. SmallPtrSet<const MachineBasicBlock *, 16> &Visited) {
  468. DEBUG(dbgs() << "join MBB: " << MBB.getName() << "\n");
  469. bool Changed = false;
  470. VarLocSet InLocsT; // Temporary incoming locations.
  471. // For all predecessors of this MBB, find the set of VarLocs that
  472. // can be joined.
  473. int NumVisited = 0;
  474. for (auto p : MBB.predecessors()) {
  475. // Ignore unvisited predecessor blocks. As we are processing
  476. // the blocks in reverse post-order any unvisited block can
  477. // be considered to not remove any incoming values.
  478. if (!Visited.count(p))
  479. continue;
  480. auto OL = OutLocs.find(p);
  481. // Join is null in case of empty OutLocs from any of the pred.
  482. if (OL == OutLocs.end())
  483. return false;
  484. // Just copy over the Out locs to incoming locs for the first visited
  485. // predecessor, and for all other predecessors join the Out locs.
  486. if (!NumVisited)
  487. InLocsT = OL->second;
  488. else
  489. InLocsT &= OL->second;
  490. NumVisited++;
  491. }
  492. // Filter out DBG_VALUES that are out of scope.
  493. VarLocSet KillSet;
  494. for (auto ID : InLocsT)
  495. if (!VarLocIDs[ID].dominates(MBB))
  496. KillSet.set(ID);
  497. InLocsT.intersectWithComplement(KillSet);
  498. // As we are processing blocks in reverse post-order we
  499. // should have processed at least one predecessor, unless it
  500. // is the entry block which has no predecessor.
  501. assert((NumVisited || MBB.pred_empty()) &&
  502. "Should have processed at least one predecessor");
  503. if (InLocsT.empty())
  504. return false;
  505. VarLocSet &ILS = InLocs[&MBB];
  506. // Insert DBG_VALUE instructions, if not already inserted.
  507. VarLocSet Diff = InLocsT;
  508. Diff.intersectWithComplement(ILS);
  509. for (auto ID : Diff) {
  510. // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
  511. // new range is started for the var from the mbb's beginning by inserting
  512. // a new DBG_VALUE. transfer() will end this range however appropriate.
  513. const VarLoc &DiffIt = VarLocIDs[ID];
  514. const MachineInstr *DMI = &DiffIt.MI;
  515. MachineInstr *MI =
  516. BuildMI(MBB, MBB.instr_begin(), DMI->getDebugLoc(), DMI->getDesc(),
  517. DMI->isIndirectDebugValue(), DMI->getOperand(0).getReg(),
  518. DMI->getDebugVariable(), DMI->getDebugExpression());
  519. if (DMI->isIndirectDebugValue())
  520. MI->getOperand(1).setImm(DMI->getOperand(1).getImm());
  521. DEBUG(dbgs() << "Inserted: "; MI->dump(););
  522. ILS.set(ID);
  523. ++NumInserted;
  524. Changed = true;
  525. }
  526. return Changed;
  527. }
  528. /// Calculate the liveness information for the given machine function and
  529. /// extend ranges across basic blocks.
  530. bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
  531. DEBUG(dbgs() << "\nDebug Range Extension\n");
  532. bool Changed = false;
  533. bool OLChanged = false;
  534. bool MBBJoined = false;
  535. VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
  536. OpenRangesSet OpenRanges; // Ranges that are open until end of bb.
  537. VarLocInMBB OutLocs; // Ranges that exist beyond bb.
  538. VarLocInMBB InLocs; // Ranges that are incoming after joining.
  539. SpillMap Spills; // DBG_VALUEs associated with spills.
  540. DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
  541. DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
  542. std::priority_queue<unsigned int, std::vector<unsigned int>,
  543. std::greater<unsigned int>>
  544. Worklist;
  545. std::priority_queue<unsigned int, std::vector<unsigned int>,
  546. std::greater<unsigned int>>
  547. Pending;
  548. // Initialize every mbb with OutLocs.
  549. // We are not looking at any spill instructions during the initial pass
  550. // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
  551. // instructions for spills of registers that are known to be user variables
  552. // within the BB in which the spill occurs.
  553. for (auto &MBB : MF)
  554. for (auto &MI : MBB)
  555. transfer(MI, OpenRanges, OutLocs, VarLocIDs, Spills,
  556. /*transferSpills=*/false);
  557. DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "OutLocs after initialization",
  558. dbgs()));
  559. ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
  560. unsigned int RPONumber = 0;
  561. for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
  562. OrderToBB[RPONumber] = *RI;
  563. BBToOrder[*RI] = RPONumber;
  564. Worklist.push(RPONumber);
  565. ++RPONumber;
  566. }
  567. // This is a standard "union of predecessor outs" dataflow problem.
  568. // To solve it, we perform join() and transfer() using the two worklist method
  569. // until the ranges converge.
  570. // Ranges have converged when both worklists are empty.
  571. SmallPtrSet<const MachineBasicBlock *, 16> Visited;
  572. while (!Worklist.empty() || !Pending.empty()) {
  573. // We track what is on the pending worklist to avoid inserting the same
  574. // thing twice. We could avoid this with a custom priority queue, but this
  575. // is probably not worth it.
  576. SmallPtrSet<MachineBasicBlock *, 16> OnPending;
  577. DEBUG(dbgs() << "Processing Worklist\n");
  578. while (!Worklist.empty()) {
  579. MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
  580. Worklist.pop();
  581. MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited);
  582. Visited.insert(MBB);
  583. if (MBBJoined) {
  584. MBBJoined = false;
  585. Changed = true;
  586. // Now that we have started to extend ranges across BBs we need to
  587. // examine spill instructions to see whether they spill registers that
  588. // correspond to user variables.
  589. for (auto &MI : *MBB)
  590. OLChanged |= transfer(MI, OpenRanges, OutLocs, VarLocIDs, Spills,
  591. /*transferSpills=*/true);
  592. // Add any DBG_VALUE instructions necessitated by spills.
  593. for (auto &SP : Spills)
  594. MBB->insertAfter(MachineBasicBlock::iterator(*SP.SpillInst),
  595. SP.DebugInst);
  596. Spills.clear();
  597. DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
  598. "OutLocs after propagating", dbgs()));
  599. DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
  600. "InLocs after propagating", dbgs()));
  601. if (OLChanged) {
  602. OLChanged = false;
  603. for (auto s : MBB->successors())
  604. if (OnPending.insert(s).second) {
  605. Pending.push(BBToOrder[s]);
  606. }
  607. }
  608. }
  609. }
  610. Worklist.swap(Pending);
  611. // At this point, pending must be empty, since it was just the empty
  612. // worklist
  613. assert(Pending.empty() && "Pending should be empty");
  614. }
  615. DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
  616. DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
  617. return Changed;
  618. }
  619. bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
  620. if (!MF.getFunction()->getSubprogram())
  621. // LiveDebugValues will already have removed all DBG_VALUEs.
  622. return false;
  623. // Skip functions from NoDebug compilation units.
  624. if (MF.getFunction()->getSubprogram()->getUnit()->getEmissionKind() ==
  625. DICompileUnit::NoDebug)
  626. return false;
  627. TRI = MF.getSubtarget().getRegisterInfo();
  628. TII = MF.getSubtarget().getInstrInfo();
  629. TFI = MF.getSubtarget().getFrameLowering();
  630. LS.initialize(MF);
  631. bool Changed = ExtendRanges(MF);
  632. return Changed;
  633. }