LiveDebugValues.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. //===- LiveDebugValues.cpp - Tracking Debug Value MIs ---------------------===//
  2. //
  3. // 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
  6. //
  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. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/PostOrderIterator.h"
  21. #include "llvm/ADT/SmallPtrSet.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/SparseBitVector.h"
  24. #include "llvm/ADT/Statistic.h"
  25. #include "llvm/ADT/UniqueVector.h"
  26. #include "llvm/CodeGen/LexicalScopes.h"
  27. #include "llvm/CodeGen/MachineBasicBlock.h"
  28. #include "llvm/CodeGen/MachineFrameInfo.h"
  29. #include "llvm/CodeGen/MachineFunction.h"
  30. #include "llvm/CodeGen/MachineFunctionPass.h"
  31. #include "llvm/CodeGen/MachineInstr.h"
  32. #include "llvm/CodeGen/MachineInstrBuilder.h"
  33. #include "llvm/CodeGen/MachineMemOperand.h"
  34. #include "llvm/CodeGen/MachineOperand.h"
  35. #include "llvm/CodeGen/PseudoSourceValue.h"
  36. #include "llvm/CodeGen/TargetFrameLowering.h"
  37. #include "llvm/CodeGen/TargetInstrInfo.h"
  38. #include "llvm/CodeGen/TargetLowering.h"
  39. #include "llvm/CodeGen/TargetRegisterInfo.h"
  40. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  41. #include "llvm/CodeGen/RegisterScavenging.h"
  42. #include "llvm/Config/llvm-config.h"
  43. #include "llvm/IR/DebugInfoMetadata.h"
  44. #include "llvm/IR/DebugLoc.h"
  45. #include "llvm/IR/Function.h"
  46. #include "llvm/IR/Module.h"
  47. #include "llvm/MC/MCRegisterInfo.h"
  48. #include "llvm/Pass.h"
  49. #include "llvm/Support/Casting.h"
  50. #include "llvm/Support/Compiler.h"
  51. #include "llvm/Support/Debug.h"
  52. #include "llvm/Support/raw_ostream.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. // 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. BitVector CalleeSavedRegs;
  79. LexicalScopes LS;
  80. /// Keeps track of lexical scopes associated with a user value's source
  81. /// location.
  82. class UserValueScopes {
  83. DebugLoc DL;
  84. LexicalScopes &LS;
  85. SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
  86. public:
  87. UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
  88. /// Return true if current scope dominates at least one machine
  89. /// instruction in a given machine basic block.
  90. bool dominates(MachineBasicBlock *MBB) {
  91. if (LBlocks.empty())
  92. LS.getMachineBasicBlocks(DL, LBlocks);
  93. return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
  94. }
  95. };
  96. /// Based on std::pair so it can be used as an index into a DenseMap.
  97. using DebugVariableBase =
  98. std::pair<const DILocalVariable *, const DILocation *>;
  99. /// A potentially inlined instance of a variable.
  100. struct DebugVariable : public DebugVariableBase {
  101. DebugVariable(const DILocalVariable *Var, const DILocation *InlinedAt)
  102. : DebugVariableBase(Var, InlinedAt) {}
  103. const DILocalVariable *getVar() const { return this->first; }
  104. const DILocation *getInlinedAt() const { return this->second; }
  105. bool operator<(const DebugVariable &DV) const {
  106. if (getVar() == DV.getVar())
  107. return getInlinedAt() < DV.getInlinedAt();
  108. return getVar() < DV.getVar();
  109. }
  110. };
  111. /// A pair of debug variable and value location.
  112. struct VarLoc {
  113. const DebugVariable Var;
  114. const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
  115. mutable UserValueScopes UVS;
  116. enum { InvalidKind = 0, RegisterKind } Kind = InvalidKind;
  117. /// The value location. Stored separately to avoid repeatedly
  118. /// extracting it from MI.
  119. union {
  120. uint64_t RegNo;
  121. uint64_t Hash;
  122. } Loc;
  123. VarLoc(const MachineInstr &MI, LexicalScopes &LS)
  124. : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
  125. UVS(MI.getDebugLoc(), LS) {
  126. static_assert((sizeof(Loc) == sizeof(uint64_t)),
  127. "hash does not cover all members of Loc");
  128. assert(MI.isDebugValue() && "not a DBG_VALUE");
  129. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  130. if (int RegNo = isDbgValueDescribedByReg(MI)) {
  131. Kind = RegisterKind;
  132. Loc.RegNo = RegNo;
  133. }
  134. }
  135. /// If this variable is described by a register, return it,
  136. /// otherwise return 0.
  137. unsigned isDescribedByReg() const {
  138. if (Kind == RegisterKind)
  139. return Loc.RegNo;
  140. return 0;
  141. }
  142. /// Determine whether the lexical scope of this value's debug location
  143. /// dominates MBB.
  144. bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
  145. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  146. LLVM_DUMP_METHOD void dump() const { MI.dump(); }
  147. #endif
  148. bool operator==(const VarLoc &Other) const {
  149. return Var == Other.Var && Loc.Hash == Other.Loc.Hash;
  150. }
  151. /// This operator guarantees that VarLocs are sorted by Variable first.
  152. bool operator<(const VarLoc &Other) const {
  153. if (Var == Other.Var)
  154. return Loc.Hash < Other.Loc.Hash;
  155. return Var < Other.Var;
  156. }
  157. };
  158. using VarLocMap = UniqueVector<VarLoc>;
  159. using VarLocSet = SparseBitVector<>;
  160. using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
  161. struct TransferDebugPair {
  162. MachineInstr *TransferInst;
  163. MachineInstr *DebugInst;
  164. };
  165. using TransferMap = SmallVector<TransferDebugPair, 4>;
  166. /// This holds the working set of currently open ranges. For fast
  167. /// access, this is done both as a set of VarLocIDs, and a map of
  168. /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
  169. /// previous open ranges for the same variable.
  170. class OpenRangesSet {
  171. VarLocSet VarLocs;
  172. SmallDenseMap<DebugVariableBase, unsigned, 8> Vars;
  173. public:
  174. const VarLocSet &getVarLocs() const { return VarLocs; }
  175. /// Terminate all open ranges for Var by removing it from the set.
  176. void erase(DebugVariable Var) {
  177. auto It = Vars.find(Var);
  178. if (It != Vars.end()) {
  179. unsigned ID = It->second;
  180. VarLocs.reset(ID);
  181. Vars.erase(It);
  182. }
  183. }
  184. /// Terminate all open ranges listed in \c KillSet by removing
  185. /// them from the set.
  186. void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
  187. VarLocs.intersectWithComplement(KillSet);
  188. for (unsigned ID : KillSet)
  189. Vars.erase(VarLocIDs[ID].Var);
  190. }
  191. /// Insert a new range into the set.
  192. void insert(unsigned VarLocID, DebugVariableBase Var) {
  193. VarLocs.set(VarLocID);
  194. Vars.insert({Var, VarLocID});
  195. }
  196. /// Empty the set.
  197. void clear() {
  198. VarLocs.clear();
  199. Vars.clear();
  200. }
  201. /// Return whether the set is empty or not.
  202. bool empty() const {
  203. assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
  204. return VarLocs.empty();
  205. }
  206. };
  207. bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
  208. unsigned &Reg);
  209. int extractSpillBaseRegAndOffset(const MachineInstr &MI, unsigned &Reg);
  210. void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
  211. TransferMap &Transfers, VarLocMap &VarLocIDs,
  212. unsigned OldVarID, unsigned NewReg = 0);
  213. void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
  214. VarLocMap &VarLocIDs);
  215. void transferSpillInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
  216. VarLocMap &VarLocIDs, TransferMap &Transfers);
  217. void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
  218. VarLocMap &VarLocIDs, TransferMap &Transfers);
  219. void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
  220. const VarLocMap &VarLocIDs);
  221. bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
  222. VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
  223. bool process(MachineInstr &MI, OpenRangesSet &OpenRanges,
  224. VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
  225. TransferMap &Transfers, bool transferChanges);
  226. bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
  227. const VarLocMap &VarLocIDs,
  228. SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
  229. SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
  230. bool ExtendRanges(MachineFunction &MF);
  231. public:
  232. static char ID;
  233. /// Default construct and initialize the pass.
  234. LiveDebugValues();
  235. /// Tell the pass manager which passes we depend on and what
  236. /// information we preserve.
  237. void getAnalysisUsage(AnalysisUsage &AU) const override;
  238. MachineFunctionProperties getRequiredProperties() const override {
  239. return MachineFunctionProperties().set(
  240. MachineFunctionProperties::Property::NoVRegs);
  241. }
  242. /// Print to ostream with a message.
  243. void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
  244. const VarLocMap &VarLocIDs, const char *msg,
  245. raw_ostream &Out) const;
  246. /// Calculate the liveness information for the given machine function.
  247. bool runOnMachineFunction(MachineFunction &MF) override;
  248. };
  249. } // end anonymous namespace
  250. //===----------------------------------------------------------------------===//
  251. // Implementation
  252. //===----------------------------------------------------------------------===//
  253. char LiveDebugValues::ID = 0;
  254. char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
  255. INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
  256. false, false)
  257. /// Default construct and initialize the pass.
  258. LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
  259. initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
  260. }
  261. /// Tell the pass manager which passes we depend on and what information we
  262. /// preserve.
  263. void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
  264. AU.setPreservesCFG();
  265. MachineFunctionPass::getAnalysisUsage(AU);
  266. }
  267. //===----------------------------------------------------------------------===//
  268. // Debug Range Extension Implementation
  269. //===----------------------------------------------------------------------===//
  270. #ifndef NDEBUG
  271. void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
  272. const VarLocInMBB &V,
  273. const VarLocMap &VarLocIDs,
  274. const char *msg,
  275. raw_ostream &Out) const {
  276. Out << '\n' << msg << '\n';
  277. for (const MachineBasicBlock &BB : MF) {
  278. const VarLocSet &L = V.lookup(&BB);
  279. if (L.empty())
  280. continue;
  281. Out << "MBB: " << BB.getNumber() << ":\n";
  282. for (unsigned VLL : L) {
  283. const VarLoc &VL = VarLocIDs[VLL];
  284. Out << " Var: " << VL.Var.getVar()->getName();
  285. Out << " MI: ";
  286. VL.dump();
  287. }
  288. }
  289. Out << "\n";
  290. }
  291. #endif
  292. /// Given a spill instruction, extract the register and offset used to
  293. /// address the spill location in a target independent way.
  294. int LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI,
  295. unsigned &Reg) {
  296. assert(MI.hasOneMemOperand() &&
  297. "Spill instruction does not have exactly one memory operand?");
  298. auto MMOI = MI.memoperands_begin();
  299. const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
  300. assert(PVal->kind() == PseudoSourceValue::FixedStack &&
  301. "Inconsistent memory operand in spill instruction");
  302. int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
  303. const MachineBasicBlock *MBB = MI.getParent();
  304. return TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
  305. }
  306. /// End all previous ranges related to @MI and start a new range from @MI
  307. /// if it is a DBG_VALUE instr.
  308. void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
  309. OpenRangesSet &OpenRanges,
  310. VarLocMap &VarLocIDs) {
  311. if (!MI.isDebugValue())
  312. return;
  313. const DILocalVariable *Var = MI.getDebugVariable();
  314. const DILocation *DebugLoc = MI.getDebugLoc();
  315. const DILocation *InlinedAt = DebugLoc->getInlinedAt();
  316. assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
  317. "Expected inlined-at fields to agree");
  318. // End all previous ranges of Var.
  319. DebugVariable V(Var, InlinedAt);
  320. OpenRanges.erase(V);
  321. // Add the VarLoc to OpenRanges from this DBG_VALUE.
  322. // TODO: Currently handles DBG_VALUE which has only reg as location.
  323. if (isDbgValueDescribedByReg(MI)) {
  324. VarLoc VL(MI, LS);
  325. unsigned ID = VarLocIDs.insert(VL);
  326. OpenRanges.insert(ID, VL.Var);
  327. }
  328. }
  329. /// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
  330. /// with \p OldVarID should be deleted form \p OpenRanges and replaced with
  331. /// new VarLoc. If \p NewReg is different than default zero value then the
  332. /// new location will be register location created by the copy like instruction,
  333. /// otherwise it is variable's location on the stack.
  334. void LiveDebugValues::insertTransferDebugPair(
  335. MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
  336. VarLocMap &VarLocIDs, unsigned OldVarID, unsigned NewReg) {
  337. const MachineInstr *DMI = &VarLocIDs[OldVarID].MI;
  338. MachineFunction *MF = MI.getParent()->getParent();
  339. MachineInstr *NewDMI;
  340. if (NewReg) {
  341. // Create a DBG_VALUE instruction to describe the Var in its new
  342. // register location.
  343. NewDMI = BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(),
  344. DMI->isIndirectDebugValue(), NewReg,
  345. DMI->getDebugVariable(), DMI->getDebugExpression());
  346. if (DMI->isIndirectDebugValue())
  347. NewDMI->getOperand(1).setImm(DMI->getOperand(1).getImm());
  348. LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register copy: ";
  349. NewDMI->print(dbgs(), false, false, false, TII));
  350. } else {
  351. // Create a DBG_VALUE instruction to describe the Var in its spilled
  352. // location.
  353. unsigned SpillBase;
  354. int SpillOffset = extractSpillBaseRegAndOffset(MI, SpillBase);
  355. auto *SpillExpr = DIExpression::prepend(DMI->getDebugExpression(),
  356. DIExpression::NoDeref, SpillOffset);
  357. NewDMI = BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(), true, SpillBase,
  358. DMI->getDebugVariable(), SpillExpr);
  359. LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
  360. NewDMI->print(dbgs(), false, false, false, TII));
  361. }
  362. // The newly created DBG_VALUE instruction NewDMI must be inserted after
  363. // MI. Keep track of the pairing.
  364. TransferDebugPair MIP = {&MI, NewDMI};
  365. Transfers.push_back(MIP);
  366. // End all previous ranges of Var.
  367. OpenRanges.erase(VarLocIDs[OldVarID].Var);
  368. // Add the VarLoc to OpenRanges.
  369. VarLoc VL(*NewDMI, LS);
  370. unsigned LocID = VarLocIDs.insert(VL);
  371. OpenRanges.insert(LocID, VL.Var);
  372. }
  373. /// A definition of a register may mark the end of a range.
  374. void LiveDebugValues::transferRegisterDef(MachineInstr &MI,
  375. OpenRangesSet &OpenRanges,
  376. const VarLocMap &VarLocIDs) {
  377. MachineFunction *MF = MI.getMF();
  378. const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
  379. unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
  380. SparseBitVector<> KillSet;
  381. for (const MachineOperand &MO : MI.operands()) {
  382. // Determine whether the operand is a register def. Assume that call
  383. // instructions never clobber SP, because some backends (e.g., AArch64)
  384. // never list SP in the regmask.
  385. if (MO.isReg() && MO.isDef() && MO.getReg() &&
  386. TRI->isPhysicalRegister(MO.getReg()) &&
  387. !(MI.isCall() && MO.getReg() == SP)) {
  388. // Remove ranges of all aliased registers.
  389. for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
  390. for (unsigned ID : OpenRanges.getVarLocs())
  391. if (VarLocIDs[ID].isDescribedByReg() == *RAI)
  392. KillSet.set(ID);
  393. } else if (MO.isRegMask()) {
  394. // Remove ranges of all clobbered registers. Register masks don't usually
  395. // list SP as preserved. While the debug info may be off for an
  396. // instruction or two around callee-cleanup calls, transferring the
  397. // DEBUG_VALUE across the call is still a better user experience.
  398. for (unsigned ID : OpenRanges.getVarLocs()) {
  399. unsigned Reg = VarLocIDs[ID].isDescribedByReg();
  400. if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
  401. KillSet.set(ID);
  402. }
  403. }
  404. }
  405. OpenRanges.erase(KillSet, VarLocIDs);
  406. }
  407. /// Decide if @MI is a spill instruction and return true if it is. We use 2
  408. /// criteria to make this decision:
  409. /// - Is this instruction a store to a spill slot?
  410. /// - Is there a register operand that is both used and killed?
  411. /// TODO: Store optimization can fold spills into other stores (including
  412. /// other spills). We do not handle this yet (more than one memory operand).
  413. bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
  414. MachineFunction *MF, unsigned &Reg) {
  415. const MachineFrameInfo &FrameInfo = MF->getFrameInfo();
  416. int FI;
  417. SmallVector<const MachineMemOperand*, 1> Accesses;
  418. // TODO: Handle multiple stores folded into one.
  419. if (!MI.hasOneMemOperand())
  420. return false;
  421. // To identify a spill instruction, use the same criteria as in AsmPrinter.
  422. if (!((TII->isStoreToStackSlotPostFE(MI, FI) &&
  423. FrameInfo.isSpillSlotObjectIndex(FI)) ||
  424. (TII->hasStoreToStackSlot(MI, Accesses) &&
  425. llvm::any_of(Accesses, [&FrameInfo](const MachineMemOperand *MMO) {
  426. return FrameInfo.isSpillSlotObjectIndex(
  427. cast<FixedStackPseudoSourceValue>(MMO->getPseudoValue())
  428. ->getFrameIndex());
  429. }))))
  430. return false;
  431. auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
  432. if (!MO.isReg() || !MO.isUse()) {
  433. Reg = 0;
  434. return false;
  435. }
  436. Reg = MO.getReg();
  437. return MO.isKill();
  438. };
  439. for (const MachineOperand &MO : MI.operands()) {
  440. // In a spill instruction generated by the InlineSpiller the spilled
  441. // register has its kill flag set.
  442. if (isKilledReg(MO, Reg))
  443. return true;
  444. if (Reg != 0) {
  445. // Check whether next instruction kills the spilled register.
  446. // FIXME: Current solution does not cover search for killed register in
  447. // bundles and instructions further down the chain.
  448. auto NextI = std::next(MI.getIterator());
  449. // Skip next instruction that points to basic block end iterator.
  450. if (MI.getParent()->end() == NextI)
  451. continue;
  452. unsigned RegNext;
  453. for (const MachineOperand &MONext : NextI->operands()) {
  454. // Return true if we came across the register from the
  455. // previous spill instruction that is killed in NextI.
  456. if (isKilledReg(MONext, RegNext) && RegNext == Reg)
  457. return true;
  458. }
  459. }
  460. }
  461. // Return false if we didn't find spilled register.
  462. return false;
  463. }
  464. /// A spilled register may indicate that we have to end the current range of
  465. /// a variable and create a new one for the spill location.
  466. /// We don't want to insert any instructions in process(), so we just create
  467. /// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
  468. /// It will be inserted into the BB when we're done iterating over the
  469. /// instructions.
  470. void LiveDebugValues::transferSpillInst(MachineInstr &MI,
  471. OpenRangesSet &OpenRanges,
  472. VarLocMap &VarLocIDs,
  473. TransferMap &Transfers) {
  474. unsigned Reg;
  475. MachineFunction *MF = MI.getMF();
  476. if (!isSpillInstruction(MI, MF, Reg))
  477. return;
  478. // Check if the register is the location of a debug value.
  479. for (unsigned ID : OpenRanges.getVarLocs()) {
  480. if (VarLocIDs[ID].isDescribedByReg() == Reg) {
  481. LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
  482. << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
  483. insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID);
  484. return;
  485. }
  486. }
  487. }
  488. /// If \p MI is a register copy instruction, that copies a previously tracked
  489. /// value from one register to another register that is callee saved, we
  490. /// create new DBG_VALUE instruction described with copy destination register.
  491. void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
  492. OpenRangesSet &OpenRanges,
  493. VarLocMap &VarLocIDs,
  494. TransferMap &Transfers) {
  495. const MachineOperand *SrcRegOp, *DestRegOp;
  496. if (!TII->isCopyInstr(MI, SrcRegOp, DestRegOp) || !SrcRegOp->isKill() ||
  497. !DestRegOp->isDef())
  498. return;
  499. auto isCalleSavedReg = [&](unsigned Reg) {
  500. for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
  501. if (CalleeSavedRegs.test(*RAI))
  502. return true;
  503. return false;
  504. };
  505. unsigned SrcReg = SrcRegOp->getReg();
  506. unsigned DestReg = DestRegOp->getReg();
  507. // We want to recognize instructions where destination register is callee
  508. // saved register. If register that could be clobbered by the call is
  509. // included, there would be a great chance that it is going to be clobbered
  510. // soon. It is more likely that previous register location, which is callee
  511. // saved, is going to stay unclobbered longer, even if it is killed.
  512. if (!isCalleSavedReg(DestReg))
  513. return;
  514. for (unsigned ID : OpenRanges.getVarLocs()) {
  515. if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
  516. insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
  517. DestReg);
  518. return;
  519. }
  520. }
  521. }
  522. /// Terminate all open ranges at the end of the current basic block.
  523. bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
  524. OpenRangesSet &OpenRanges,
  525. VarLocInMBB &OutLocs,
  526. const VarLocMap &VarLocIDs) {
  527. bool Changed = false;
  528. const MachineBasicBlock *CurMBB = MI.getParent();
  529. if (!(MI.isTerminator() || (&MI == &CurMBB->back())))
  530. return false;
  531. if (OpenRanges.empty())
  532. return false;
  533. LLVM_DEBUG(for (unsigned ID
  534. : OpenRanges.getVarLocs()) {
  535. // Copy OpenRanges to OutLocs, if not already present.
  536. dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
  537. VarLocIDs[ID].dump();
  538. });
  539. VarLocSet &VLS = OutLocs[CurMBB];
  540. Changed = VLS |= OpenRanges.getVarLocs();
  541. OpenRanges.clear();
  542. return Changed;
  543. }
  544. /// This routine creates OpenRanges and OutLocs.
  545. bool LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
  546. VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
  547. TransferMap &Transfers, bool transferChanges) {
  548. bool Changed = false;
  549. transferDebugValue(MI, OpenRanges, VarLocIDs);
  550. transferRegisterDef(MI, OpenRanges, VarLocIDs);
  551. if (transferChanges) {
  552. transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
  553. transferSpillInst(MI, OpenRanges, VarLocIDs, Transfers);
  554. }
  555. Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
  556. return Changed;
  557. }
  558. /// This routine joins the analysis results of all incoming edges in @MBB by
  559. /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
  560. /// source variable in all the predecessors of @MBB reside in the same location.
  561. bool LiveDebugValues::join(
  562. MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
  563. const VarLocMap &VarLocIDs,
  564. SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
  565. SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
  566. LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
  567. bool Changed = false;
  568. VarLocSet InLocsT; // Temporary incoming locations.
  569. // For all predecessors of this MBB, find the set of VarLocs that
  570. // can be joined.
  571. int NumVisited = 0;
  572. for (auto p : MBB.predecessors()) {
  573. // Ignore unvisited predecessor blocks. As we are processing
  574. // the blocks in reverse post-order any unvisited block can
  575. // be considered to not remove any incoming values.
  576. if (!Visited.count(p)) {
  577. LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
  578. << "\n");
  579. continue;
  580. }
  581. auto OL = OutLocs.find(p);
  582. // Join is null in case of empty OutLocs from any of the pred.
  583. if (OL == OutLocs.end())
  584. return false;
  585. // Just copy over the Out locs to incoming locs for the first visited
  586. // predecessor, and for all other predecessors join the Out locs.
  587. if (!NumVisited)
  588. InLocsT = OL->second;
  589. else
  590. InLocsT &= OL->second;
  591. LLVM_DEBUG({
  592. if (!InLocsT.empty()) {
  593. for (auto ID : InLocsT)
  594. dbgs() << " gathered candidate incoming var: "
  595. << VarLocIDs[ID].Var.getVar()->getName() << "\n";
  596. }
  597. });
  598. NumVisited++;
  599. }
  600. // Filter out DBG_VALUES that are out of scope.
  601. VarLocSet KillSet;
  602. bool IsArtificial = ArtificialBlocks.count(&MBB);
  603. if (!IsArtificial) {
  604. for (auto ID : InLocsT) {
  605. if (!VarLocIDs[ID].dominates(MBB)) {
  606. KillSet.set(ID);
  607. LLVM_DEBUG({
  608. auto Name = VarLocIDs[ID].Var.getVar()->getName();
  609. dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
  610. });
  611. }
  612. }
  613. }
  614. InLocsT.intersectWithComplement(KillSet);
  615. // As we are processing blocks in reverse post-order we
  616. // should have processed at least one predecessor, unless it
  617. // is the entry block which has no predecessor.
  618. assert((NumVisited || MBB.pred_empty()) &&
  619. "Should have processed at least one predecessor");
  620. if (InLocsT.empty())
  621. return false;
  622. VarLocSet &ILS = InLocs[&MBB];
  623. // Insert DBG_VALUE instructions, if not already inserted.
  624. VarLocSet Diff = InLocsT;
  625. Diff.intersectWithComplement(ILS);
  626. for (auto ID : Diff) {
  627. // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
  628. // new range is started for the var from the mbb's beginning by inserting
  629. // a new DBG_VALUE. process() will end this range however appropriate.
  630. const VarLoc &DiffIt = VarLocIDs[ID];
  631. const MachineInstr *DMI = &DiffIt.MI;
  632. MachineInstr *MI =
  633. BuildMI(MBB, MBB.instr_begin(), DMI->getDebugLoc(), DMI->getDesc(),
  634. DMI->isIndirectDebugValue(), DMI->getOperand(0).getReg(),
  635. DMI->getDebugVariable(), DMI->getDebugExpression());
  636. if (DMI->isIndirectDebugValue())
  637. MI->getOperand(1).setImm(DMI->getOperand(1).getImm());
  638. LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
  639. ILS.set(ID);
  640. ++NumInserted;
  641. Changed = true;
  642. }
  643. return Changed;
  644. }
  645. /// Calculate the liveness information for the given machine function and
  646. /// extend ranges across basic blocks.
  647. bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
  648. LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
  649. bool Changed = false;
  650. bool OLChanged = false;
  651. bool MBBJoined = false;
  652. VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
  653. OpenRangesSet OpenRanges; // Ranges that are open until end of bb.
  654. VarLocInMBB OutLocs; // Ranges that exist beyond bb.
  655. VarLocInMBB InLocs; // Ranges that are incoming after joining.
  656. TransferMap Transfers; // DBG_VALUEs associated with spills.
  657. // Blocks which are artificial, i.e. blocks which exclusively contain
  658. // instructions without locations, or with line 0 locations.
  659. SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
  660. DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
  661. DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
  662. std::priority_queue<unsigned int, std::vector<unsigned int>,
  663. std::greater<unsigned int>>
  664. Worklist;
  665. std::priority_queue<unsigned int, std::vector<unsigned int>,
  666. std::greater<unsigned int>>
  667. Pending;
  668. enum : bool { dontTransferChanges = false, transferChanges = true };
  669. // Initialize every mbb with OutLocs.
  670. // We are not looking at any spill instructions during the initial pass
  671. // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
  672. // instructions for spills of registers that are known to be user variables
  673. // within the BB in which the spill occurs.
  674. for (auto &MBB : MF)
  675. for (auto &MI : MBB)
  676. process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
  677. dontTransferChanges);
  678. auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
  679. if (const DebugLoc &DL = MI.getDebugLoc())
  680. return DL.getLine() != 0;
  681. return false;
  682. };
  683. for (auto &MBB : MF)
  684. if (none_of(MBB.instrs(), hasNonArtificialLocation))
  685. ArtificialBlocks.insert(&MBB);
  686. LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
  687. "OutLocs after initialization", dbgs()));
  688. ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
  689. unsigned int RPONumber = 0;
  690. for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
  691. OrderToBB[RPONumber] = *RI;
  692. BBToOrder[*RI] = RPONumber;
  693. Worklist.push(RPONumber);
  694. ++RPONumber;
  695. }
  696. // This is a standard "union of predecessor outs" dataflow problem.
  697. // To solve it, we perform join() and process() using the two worklist method
  698. // until the ranges converge.
  699. // Ranges have converged when both worklists are empty.
  700. SmallPtrSet<const MachineBasicBlock *, 16> Visited;
  701. while (!Worklist.empty() || !Pending.empty()) {
  702. // We track what is on the pending worklist to avoid inserting the same
  703. // thing twice. We could avoid this with a custom priority queue, but this
  704. // is probably not worth it.
  705. SmallPtrSet<MachineBasicBlock *, 16> OnPending;
  706. LLVM_DEBUG(dbgs() << "Processing Worklist\n");
  707. while (!Worklist.empty()) {
  708. MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
  709. Worklist.pop();
  710. MBBJoined =
  711. join(*MBB, OutLocs, InLocs, VarLocIDs, Visited, ArtificialBlocks);
  712. Visited.insert(MBB);
  713. if (MBBJoined) {
  714. MBBJoined = false;
  715. Changed = true;
  716. // Now that we have started to extend ranges across BBs we need to
  717. // examine spill instructions to see whether they spill registers that
  718. // correspond to user variables.
  719. for (auto &MI : *MBB)
  720. OLChanged |= process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
  721. transferChanges);
  722. // Add any DBG_VALUE instructions necessitated by spills.
  723. for (auto &TR : Transfers)
  724. MBB->insertAfter(MachineBasicBlock::iterator(*TR.TransferInst),
  725. TR.DebugInst);
  726. Transfers.clear();
  727. LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
  728. "OutLocs after propagating", dbgs()));
  729. LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
  730. "InLocs after propagating", dbgs()));
  731. if (OLChanged) {
  732. OLChanged = false;
  733. for (auto s : MBB->successors())
  734. if (OnPending.insert(s).second) {
  735. Pending.push(BBToOrder[s]);
  736. }
  737. }
  738. }
  739. }
  740. Worklist.swap(Pending);
  741. // At this point, pending must be empty, since it was just the empty
  742. // worklist
  743. assert(Pending.empty() && "Pending should be empty");
  744. }
  745. LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
  746. LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
  747. return Changed;
  748. }
  749. bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
  750. if (!MF.getFunction().getSubprogram())
  751. // LiveDebugValues will already have removed all DBG_VALUEs.
  752. return false;
  753. // Skip functions from NoDebug compilation units.
  754. if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
  755. DICompileUnit::NoDebug)
  756. return false;
  757. TRI = MF.getSubtarget().getRegisterInfo();
  758. TII = MF.getSubtarget().getInstrInfo();
  759. TFI = MF.getSubtarget().getFrameLowering();
  760. TFI->determineCalleeSaves(MF, CalleeSavedRegs,
  761. make_unique<RegScavenger>().get());
  762. LS.initialize(MF);
  763. bool Changed = ExtendRanges(MF);
  764. return Changed;
  765. }