LiveDebugValues.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  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/SmallSet.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/MachineOperand.h"
  36. #include "llvm/CodeGen/PseudoSourceValue.h"
  37. #include "llvm/CodeGen/RegisterScavenging.h"
  38. #include "llvm/CodeGen/TargetFrameLowering.h"
  39. #include "llvm/CodeGen/TargetInstrInfo.h"
  40. #include "llvm/CodeGen/TargetLowering.h"
  41. #include "llvm/CodeGen/TargetPassConfig.h"
  42. #include "llvm/CodeGen/TargetRegisterInfo.h"
  43. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  44. #include "llvm/Config/llvm-config.h"
  45. #include "llvm/IR/DIBuilder.h"
  46. #include "llvm/IR/DebugInfoMetadata.h"
  47. #include "llvm/IR/DebugLoc.h"
  48. #include "llvm/IR/Function.h"
  49. #include "llvm/IR/Module.h"
  50. #include "llvm/MC/MCRegisterInfo.h"
  51. #include "llvm/Pass.h"
  52. #include "llvm/Support/Casting.h"
  53. #include "llvm/Support/Compiler.h"
  54. #include "llvm/Support/Debug.h"
  55. #include "llvm/Support/raw_ostream.h"
  56. #include <algorithm>
  57. #include <cassert>
  58. #include <cstdint>
  59. #include <functional>
  60. #include <queue>
  61. #include <tuple>
  62. #include <utility>
  63. #include <vector>
  64. using namespace llvm;
  65. #define DEBUG_TYPE "livedebugvalues"
  66. STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
  67. // If @MI is a DBG_VALUE with debug value described by a defined
  68. // register, returns the number of this register. In the other case, returns 0.
  69. static Register isDbgValueDescribedByReg(const MachineInstr &MI) {
  70. assert(MI.isDebugValue() && "expected a DBG_VALUE");
  71. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  72. // If location of variable is described using a register (directly
  73. // or indirectly), this register is always a first operand.
  74. return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : Register();
  75. }
  76. namespace {
  77. class LiveDebugValues : public MachineFunctionPass {
  78. private:
  79. const TargetRegisterInfo *TRI;
  80. const TargetInstrInfo *TII;
  81. const TargetFrameLowering *TFI;
  82. BitVector CalleeSavedRegs;
  83. LexicalScopes LS;
  84. enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
  85. /// Keeps track of lexical scopes associated with a user value's source
  86. /// location.
  87. class UserValueScopes {
  88. DebugLoc DL;
  89. LexicalScopes &LS;
  90. SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
  91. public:
  92. UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
  93. /// Return true if current scope dominates at least one machine
  94. /// instruction in a given machine basic block.
  95. bool dominates(MachineBasicBlock *MBB) {
  96. if (LBlocks.empty())
  97. LS.getMachineBasicBlocks(DL, LBlocks);
  98. return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
  99. }
  100. };
  101. using FragmentInfo = DIExpression::FragmentInfo;
  102. using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
  103. /// Storage for identifying a potentially inlined instance of a variable,
  104. /// or a fragment thereof.
  105. class DebugVariable {
  106. const DILocalVariable *Variable;
  107. OptFragmentInfo Fragment;
  108. const DILocation *InlinedAt;
  109. /// Fragment that will overlap all other fragments. Used as default when
  110. /// caller demands a fragment.
  111. static const FragmentInfo DefaultFragment;
  112. public:
  113. DebugVariable(const DILocalVariable *Var, OptFragmentInfo &&FragmentInfo,
  114. const DILocation *InlinedAt)
  115. : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
  116. DebugVariable(const DILocalVariable *Var, OptFragmentInfo &FragmentInfo,
  117. const DILocation *InlinedAt)
  118. : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
  119. DebugVariable(const DILocalVariable *Var, const DIExpression *DIExpr,
  120. const DILocation *InlinedAt)
  121. : DebugVariable(Var, DIExpr->getFragmentInfo(), InlinedAt) {}
  122. DebugVariable(const MachineInstr &MI)
  123. : DebugVariable(MI.getDebugVariable(),
  124. MI.getDebugExpression()->getFragmentInfo(),
  125. MI.getDebugLoc()->getInlinedAt()) {}
  126. const DILocalVariable *getVar() const { return Variable; }
  127. const OptFragmentInfo &getFragment() const { return Fragment; }
  128. const DILocation *getInlinedAt() const { return InlinedAt; }
  129. const FragmentInfo getFragmentDefault() const {
  130. return Fragment.getValueOr(DefaultFragment);
  131. }
  132. static bool isFragmentDefault(FragmentInfo &F) {
  133. return F == DefaultFragment;
  134. }
  135. bool operator==(const DebugVariable &Other) const {
  136. return std::tie(Variable, Fragment, InlinedAt) ==
  137. std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
  138. }
  139. bool operator<(const DebugVariable &Other) const {
  140. return std::tie(Variable, Fragment, InlinedAt) <
  141. std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
  142. }
  143. };
  144. friend struct llvm::DenseMapInfo<DebugVariable>;
  145. /// A pair of debug variable and value location.
  146. struct VarLoc {
  147. // The location at which a spilled variable resides. It consists of a
  148. // register and an offset.
  149. struct SpillLoc {
  150. unsigned SpillBase;
  151. int SpillOffset;
  152. bool operator==(const SpillLoc &Other) const {
  153. return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
  154. }
  155. };
  156. const DebugVariable Var;
  157. const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
  158. mutable UserValueScopes UVS;
  159. enum VarLocKind {
  160. InvalidKind = 0,
  161. RegisterKind,
  162. SpillLocKind,
  163. ImmediateKind,
  164. EntryValueKind
  165. } Kind = InvalidKind;
  166. /// The value location. Stored separately to avoid repeatedly
  167. /// extracting it from MI.
  168. union {
  169. uint64_t RegNo;
  170. SpillLoc SpillLocation;
  171. uint64_t Hash;
  172. int64_t Immediate;
  173. const ConstantFP *FPImm;
  174. const ConstantInt *CImm;
  175. } Loc;
  176. VarLoc(const MachineInstr &MI, LexicalScopes &LS,
  177. VarLocKind K = InvalidKind)
  178. : Var(MI), MI(MI), UVS(MI.getDebugLoc(), LS){
  179. static_assert((sizeof(Loc) == sizeof(uint64_t)),
  180. "hash does not cover all members of Loc");
  181. assert(MI.isDebugValue() && "not a DBG_VALUE");
  182. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  183. if (int RegNo = isDbgValueDescribedByReg(MI)) {
  184. Kind = MI.isDebugEntryValue() ? EntryValueKind : RegisterKind;
  185. Loc.RegNo = RegNo;
  186. } else if (MI.getOperand(0).isImm()) {
  187. Kind = ImmediateKind;
  188. Loc.Immediate = MI.getOperand(0).getImm();
  189. } else if (MI.getOperand(0).isFPImm()) {
  190. Kind = ImmediateKind;
  191. Loc.FPImm = MI.getOperand(0).getFPImm();
  192. } else if (MI.getOperand(0).isCImm()) {
  193. Kind = ImmediateKind;
  194. Loc.CImm = MI.getOperand(0).getCImm();
  195. }
  196. assert((Kind != ImmediateKind || !MI.isDebugEntryValue()) &&
  197. "entry values must be register locations");
  198. }
  199. /// The constructor for spill locations.
  200. VarLoc(const MachineInstr &MI, unsigned SpillBase, int SpillOffset,
  201. LexicalScopes &LS)
  202. : Var(MI), MI(MI), UVS(MI.getDebugLoc(), LS) {
  203. assert(MI.isDebugValue() && "not a DBG_VALUE");
  204. assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
  205. Kind = SpillLocKind;
  206. Loc.SpillLocation = {SpillBase, SpillOffset};
  207. }
  208. // Is the Loc field a constant or constant object?
  209. bool isConstant() const { return Kind == ImmediateKind; }
  210. /// If this variable is described by a register, return it,
  211. /// otherwise return 0.
  212. unsigned isDescribedByReg() const {
  213. if (Kind == RegisterKind)
  214. return Loc.RegNo;
  215. return 0;
  216. }
  217. /// Determine whether the lexical scope of this value's debug location
  218. /// dominates MBB.
  219. bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
  220. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  221. LLVM_DUMP_METHOD void dump() const { MI.dump(); }
  222. #endif
  223. bool operator==(const VarLoc &Other) const {
  224. return Kind == Other.Kind && Var == Other.Var &&
  225. Loc.Hash == Other.Loc.Hash;
  226. }
  227. /// This operator guarantees that VarLocs are sorted by Variable first.
  228. bool operator<(const VarLoc &Other) const {
  229. return std::tie(Var, Kind, Loc.Hash) <
  230. std::tie(Other.Var, Other.Kind, Other.Loc.Hash);
  231. }
  232. };
  233. using DebugParamMap = SmallDenseMap<const DILocalVariable *, MachineInstr *>;
  234. using VarLocMap = UniqueVector<VarLoc>;
  235. using VarLocSet = SparseBitVector<>;
  236. using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
  237. struct TransferDebugPair {
  238. MachineInstr *TransferInst;
  239. MachineInstr *DebugInst;
  240. };
  241. using TransferMap = SmallVector<TransferDebugPair, 4>;
  242. // Types for recording sets of variable fragments that overlap. For a given
  243. // local variable, we record all other fragments of that variable that could
  244. // overlap it, to reduce search time.
  245. using FragmentOfVar =
  246. std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
  247. using OverlapMap =
  248. DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
  249. // Helper while building OverlapMap, a map of all fragments seen for a given
  250. // DILocalVariable.
  251. using VarToFragments =
  252. DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
  253. /// This holds the working set of currently open ranges. For fast
  254. /// access, this is done both as a set of VarLocIDs, and a map of
  255. /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
  256. /// previous open ranges for the same variable.
  257. class OpenRangesSet {
  258. VarLocSet VarLocs;
  259. SmallDenseMap<DebugVariable, unsigned, 8> Vars;
  260. OverlapMap &OverlappingFragments;
  261. public:
  262. OpenRangesSet(OverlapMap &_OLapMap) : OverlappingFragments(_OLapMap) {}
  263. const VarLocSet &getVarLocs() const { return VarLocs; }
  264. /// Terminate all open ranges for Var by removing it from the set.
  265. void erase(DebugVariable Var);
  266. /// Terminate all open ranges listed in \c KillSet by removing
  267. /// them from the set.
  268. void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
  269. VarLocs.intersectWithComplement(KillSet);
  270. for (unsigned ID : KillSet)
  271. Vars.erase(VarLocIDs[ID].Var);
  272. }
  273. /// Insert a new range into the set.
  274. void insert(unsigned VarLocID, DebugVariable Var) {
  275. VarLocs.set(VarLocID);
  276. Vars.insert({Var, VarLocID});
  277. }
  278. /// Empty the set.
  279. void clear() {
  280. VarLocs.clear();
  281. Vars.clear();
  282. }
  283. /// Return whether the set is empty or not.
  284. bool empty() const {
  285. assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
  286. return VarLocs.empty();
  287. }
  288. };
  289. bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
  290. unsigned &Reg);
  291. /// If a given instruction is identified as a spill, return the spill location
  292. /// and set \p Reg to the spilled register.
  293. Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
  294. MachineFunction *MF,
  295. unsigned &Reg);
  296. /// Given a spill instruction, extract the register and offset used to
  297. /// address the spill location in a target independent way.
  298. VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
  299. void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
  300. TransferMap &Transfers, VarLocMap &VarLocIDs,
  301. unsigned OldVarID, TransferKind Kind,
  302. unsigned NewReg = 0);
  303. void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
  304. VarLocMap &VarLocIDs);
  305. void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
  306. VarLocMap &VarLocIDs, TransferMap &Transfers);
  307. void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
  308. VarLocMap &VarLocIDs, TransferMap &Transfers,
  309. DebugParamMap &DebugEntryVals,
  310. SparseBitVector<> &KillSet);
  311. void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
  312. VarLocMap &VarLocIDs, TransferMap &Transfers);
  313. void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
  314. VarLocMap &VarLocIDs, TransferMap &Transfers,
  315. DebugParamMap &DebugEntryVals);
  316. bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
  317. VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
  318. bool process(MachineInstr &MI, OpenRangesSet &OpenRanges,
  319. VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
  320. TransferMap &Transfers, DebugParamMap &DebugEntryVals,
  321. bool transferChanges, OverlapMap &OverlapFragments,
  322. VarToFragments &SeenFragments);
  323. void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
  324. OverlapMap &OLapMap);
  325. bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
  326. const VarLocMap &VarLocIDs,
  327. SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
  328. SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
  329. bool ExtendRanges(MachineFunction &MF);
  330. public:
  331. static char ID;
  332. /// Default construct and initialize the pass.
  333. LiveDebugValues();
  334. /// Tell the pass manager which passes we depend on and what
  335. /// information we preserve.
  336. void getAnalysisUsage(AnalysisUsage &AU) const override;
  337. MachineFunctionProperties getRequiredProperties() const override {
  338. return MachineFunctionProperties().set(
  339. MachineFunctionProperties::Property::NoVRegs);
  340. }
  341. /// Print to ostream with a message.
  342. void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
  343. const VarLocMap &VarLocIDs, const char *msg,
  344. raw_ostream &Out) const;
  345. /// Calculate the liveness information for the given machine function.
  346. bool runOnMachineFunction(MachineFunction &MF) override;
  347. };
  348. } // end anonymous namespace
  349. namespace llvm {
  350. template <> struct DenseMapInfo<LiveDebugValues::DebugVariable> {
  351. using DV = LiveDebugValues::DebugVariable;
  352. using OptFragmentInfo = LiveDebugValues::OptFragmentInfo;
  353. using FragmentInfo = LiveDebugValues::FragmentInfo;
  354. // Empty key: no key should be generated that has no DILocalVariable.
  355. static inline DV getEmptyKey() {
  356. return DV(nullptr, OptFragmentInfo(), nullptr);
  357. }
  358. // Difference in tombstone is that the Optional is meaningful
  359. static inline DV getTombstoneKey() {
  360. return DV(nullptr, OptFragmentInfo({0, 0}), nullptr);
  361. }
  362. static unsigned getHashValue(const DV &D) {
  363. unsigned HV = 0;
  364. const OptFragmentInfo &Fragment = D.getFragment();
  365. if (Fragment)
  366. HV = DenseMapInfo<FragmentInfo>::getHashValue(*Fragment);
  367. return hash_combine(D.getVar(), HV, D.getInlinedAt());
  368. }
  369. static bool isEqual(const DV &A, const DV &B) { return A == B; }
  370. };
  371. } // namespace llvm
  372. //===----------------------------------------------------------------------===//
  373. // Implementation
  374. //===----------------------------------------------------------------------===//
  375. const DIExpression::FragmentInfo
  376. LiveDebugValues::DebugVariable::DefaultFragment = {
  377. std::numeric_limits<uint64_t>::max(),
  378. std::numeric_limits<uint64_t>::min()};
  379. char LiveDebugValues::ID = 0;
  380. char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
  381. INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
  382. false, false)
  383. /// Default construct and initialize the pass.
  384. LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
  385. initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
  386. }
  387. /// Tell the pass manager which passes we depend on and what information we
  388. /// preserve.
  389. void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
  390. AU.setPreservesCFG();
  391. MachineFunctionPass::getAnalysisUsage(AU);
  392. }
  393. /// Erase a variable from the set of open ranges, and additionally erase any
  394. /// fragments that may overlap it.
  395. void LiveDebugValues::OpenRangesSet::erase(DebugVariable Var) {
  396. // Erasure helper.
  397. auto DoErase = [this](DebugVariable VarToErase) {
  398. auto It = Vars.find(VarToErase);
  399. if (It != Vars.end()) {
  400. unsigned ID = It->second;
  401. VarLocs.reset(ID);
  402. Vars.erase(It);
  403. }
  404. };
  405. // Erase the variable/fragment that ends here.
  406. DoErase(Var);
  407. // Extract the fragment. Interpret an empty fragment as one that covers all
  408. // possible bits.
  409. FragmentInfo ThisFragment = Var.getFragmentDefault();
  410. // There may be fragments that overlap the designated fragment. Look them up
  411. // in the pre-computed overlap map, and erase them too.
  412. auto MapIt = OverlappingFragments.find({Var.getVar(), ThisFragment});
  413. if (MapIt != OverlappingFragments.end()) {
  414. for (auto Fragment : MapIt->second) {
  415. LiveDebugValues::OptFragmentInfo FragmentHolder;
  416. if (!DebugVariable::isFragmentDefault(Fragment))
  417. FragmentHolder = LiveDebugValues::OptFragmentInfo(Fragment);
  418. DoErase({Var.getVar(), FragmentHolder, Var.getInlinedAt()});
  419. }
  420. }
  421. }
  422. //===----------------------------------------------------------------------===//
  423. // Debug Range Extension Implementation
  424. //===----------------------------------------------------------------------===//
  425. #ifndef NDEBUG
  426. void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
  427. const VarLocInMBB &V,
  428. const VarLocMap &VarLocIDs,
  429. const char *msg,
  430. raw_ostream &Out) const {
  431. Out << '\n' << msg << '\n';
  432. for (const MachineBasicBlock &BB : MF) {
  433. const VarLocSet &L = V.lookup(&BB);
  434. if (L.empty())
  435. continue;
  436. Out << "MBB: " << BB.getNumber() << ":\n";
  437. for (unsigned VLL : L) {
  438. const VarLoc &VL = VarLocIDs[VLL];
  439. Out << " Var: " << VL.Var.getVar()->getName();
  440. Out << " MI: ";
  441. VL.dump();
  442. }
  443. }
  444. Out << "\n";
  445. }
  446. #endif
  447. LiveDebugValues::VarLoc::SpillLoc
  448. LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
  449. assert(MI.hasOneMemOperand() &&
  450. "Spill instruction does not have exactly one memory operand?");
  451. auto MMOI = MI.memoperands_begin();
  452. const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
  453. assert(PVal->kind() == PseudoSourceValue::FixedStack &&
  454. "Inconsistent memory operand in spill instruction");
  455. int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
  456. const MachineBasicBlock *MBB = MI.getParent();
  457. unsigned Reg;
  458. int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
  459. return {Reg, Offset};
  460. }
  461. /// End all previous ranges related to @MI and start a new range from @MI
  462. /// if it is a DBG_VALUE instr.
  463. void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
  464. OpenRangesSet &OpenRanges,
  465. VarLocMap &VarLocIDs) {
  466. if (!MI.isDebugValue())
  467. return;
  468. const DILocalVariable *Var = MI.getDebugVariable();
  469. const DIExpression *Expr = MI.getDebugExpression();
  470. const DILocation *DebugLoc = MI.getDebugLoc();
  471. const DILocation *InlinedAt = DebugLoc->getInlinedAt();
  472. assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
  473. "Expected inlined-at fields to agree");
  474. // End all previous ranges of Var.
  475. DebugVariable V(Var, Expr, InlinedAt);
  476. OpenRanges.erase(V);
  477. // Add the VarLoc to OpenRanges from this DBG_VALUE.
  478. unsigned ID;
  479. if (isDbgValueDescribedByReg(MI) || MI.getOperand(0).isImm() ||
  480. MI.getOperand(0).isFPImm() || MI.getOperand(0).isCImm()) {
  481. // Use normal VarLoc constructor for registers and immediates.
  482. VarLoc VL(MI, LS);
  483. ID = VarLocIDs.insert(VL);
  484. OpenRanges.insert(ID, VL.Var);
  485. } else if (MI.hasOneMemOperand()) {
  486. // It's a stack spill -- fetch spill base and offset.
  487. VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
  488. VarLoc VL(MI, SpillLocation.SpillBase, SpillLocation.SpillOffset, LS);
  489. ID = VarLocIDs.insert(VL);
  490. OpenRanges.insert(ID, VL.Var);
  491. } else {
  492. // This must be an undefined location. We should leave OpenRanges closed.
  493. assert(MI.getOperand(0).isReg() && MI.getOperand(0).getReg() == 0 &&
  494. "Unexpected non-undef DBG_VALUE encountered");
  495. }
  496. }
  497. void LiveDebugValues::emitEntryValues(MachineInstr &MI,
  498. OpenRangesSet &OpenRanges,
  499. VarLocMap &VarLocIDs,
  500. TransferMap &Transfers,
  501. DebugParamMap &DebugEntryVals,
  502. SparseBitVector<> &KillSet) {
  503. MachineFunction *MF = MI.getParent()->getParent();
  504. for (unsigned ID : KillSet) {
  505. if (!VarLocIDs[ID].Var.getVar()->isParameter())
  506. continue;
  507. const MachineInstr *CurrDebugInstr = &VarLocIDs[ID].MI;
  508. // If parameter's DBG_VALUE is not in the map that means we can't
  509. // generate parameter's entry value.
  510. if (!DebugEntryVals.count(CurrDebugInstr->getDebugVariable()))
  511. continue;
  512. auto ParamDebugInstr = DebugEntryVals[CurrDebugInstr->getDebugVariable()];
  513. DIExpression *NewExpr = DIExpression::prepend(
  514. ParamDebugInstr->getDebugExpression(), DIExpression::EntryValue);
  515. MachineInstr *EntryValDbgMI =
  516. BuildMI(*MF, ParamDebugInstr->getDebugLoc(), ParamDebugInstr->getDesc(),
  517. ParamDebugInstr->isIndirectDebugValue(),
  518. ParamDebugInstr->getOperand(0).getReg(),
  519. ParamDebugInstr->getDebugVariable(), NewExpr);
  520. if (ParamDebugInstr->isIndirectDebugValue())
  521. EntryValDbgMI->getOperand(1).setImm(
  522. ParamDebugInstr->getOperand(1).getImm());
  523. Transfers.push_back({&MI, EntryValDbgMI});
  524. VarLoc VL(*EntryValDbgMI, LS);
  525. unsigned EntryValLocID = VarLocIDs.insert(VL);
  526. OpenRanges.insert(EntryValLocID, VL.Var);
  527. }
  528. }
  529. /// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
  530. /// with \p OldVarID should be deleted form \p OpenRanges and replaced with
  531. /// new VarLoc. If \p NewReg is different than default zero value then the
  532. /// new location will be register location created by the copy like instruction,
  533. /// otherwise it is variable's location on the stack.
  534. void LiveDebugValues::insertTransferDebugPair(
  535. MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
  536. VarLocMap &VarLocIDs, unsigned OldVarID, TransferKind Kind,
  537. unsigned NewReg) {
  538. const MachineInstr *DebugInstr = &VarLocIDs[OldVarID].MI;
  539. MachineFunction *MF = MI.getParent()->getParent();
  540. MachineInstr *NewDebugInstr;
  541. auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &DebugInstr,
  542. &VarLocIDs](VarLoc &VL, MachineInstr *NewDebugInstr) {
  543. unsigned LocId = VarLocIDs.insert(VL);
  544. // Close this variable's previous location range.
  545. DebugVariable V(*DebugInstr);
  546. OpenRanges.erase(V);
  547. OpenRanges.insert(LocId, VL.Var);
  548. // The newly created DBG_VALUE instruction NewDebugInstr must be inserted
  549. // after MI. Keep track of the pairing.
  550. TransferDebugPair MIP = {&MI, NewDebugInstr};
  551. Transfers.push_back(MIP);
  552. };
  553. // End all previous ranges of Var.
  554. OpenRanges.erase(VarLocIDs[OldVarID].Var);
  555. switch (Kind) {
  556. case TransferKind::TransferCopy: {
  557. assert(NewReg &&
  558. "No register supplied when handling a copy of a debug value");
  559. // Create a DBG_VALUE instruction to describe the Var in its new
  560. // register location.
  561. NewDebugInstr = BuildMI(
  562. *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(),
  563. DebugInstr->isIndirectDebugValue(), NewReg,
  564. DebugInstr->getDebugVariable(), DebugInstr->getDebugExpression());
  565. if (DebugInstr->isIndirectDebugValue())
  566. NewDebugInstr->getOperand(1).setImm(DebugInstr->getOperand(1).getImm());
  567. VarLoc VL(*NewDebugInstr, LS);
  568. ProcessVarLoc(VL, NewDebugInstr);
  569. LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register copy: ";
  570. NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
  571. /*SkipOpers*/false, /*SkipDebugLoc*/false,
  572. /*AddNewLine*/true, TII));
  573. return;
  574. }
  575. case TransferKind::TransferSpill: {
  576. // Create a DBG_VALUE instruction to describe the Var in its spilled
  577. // location.
  578. VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
  579. auto *SpillExpr = DIExpression::prepend(DebugInstr->getDebugExpression(),
  580. DIExpression::ApplyOffset,
  581. SpillLocation.SpillOffset);
  582. NewDebugInstr = BuildMI(
  583. *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(), true,
  584. SpillLocation.SpillBase, DebugInstr->getDebugVariable(), SpillExpr);
  585. VarLoc VL(*NewDebugInstr, SpillLocation.SpillBase,
  586. SpillLocation.SpillOffset, LS);
  587. ProcessVarLoc(VL, NewDebugInstr);
  588. LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
  589. NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
  590. /*SkipOpers*/false, /*SkipDebugLoc*/false,
  591. /*AddNewLine*/true, TII));
  592. return;
  593. }
  594. case TransferKind::TransferRestore: {
  595. assert(NewReg &&
  596. "No register supplied when handling a restore of a debug value");
  597. MachineFunction *MF = MI.getMF();
  598. DIBuilder DIB(*const_cast<Function &>(MF->getFunction()).getParent());
  599. NewDebugInstr =
  600. BuildMI(*MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(), false,
  601. NewReg, DebugInstr->getDebugVariable(), DIB.createExpression());
  602. VarLoc VL(*NewDebugInstr, LS);
  603. ProcessVarLoc(VL, NewDebugInstr);
  604. LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register restore: ";
  605. NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
  606. /*SkipOpers*/false, /*SkipDebugLoc*/false,
  607. /*AddNewLine*/true, TII));
  608. return;
  609. }
  610. }
  611. llvm_unreachable("Invalid transfer kind");
  612. }
  613. /// A definition of a register may mark the end of a range.
  614. void LiveDebugValues::transferRegisterDef(
  615. MachineInstr &MI, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
  616. TransferMap &Transfers, DebugParamMap &DebugEntryVals) {
  617. MachineFunction *MF = MI.getMF();
  618. const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
  619. unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
  620. SparseBitVector<> KillSet;
  621. for (const MachineOperand &MO : MI.operands()) {
  622. // Determine whether the operand is a register def. Assume that call
  623. // instructions never clobber SP, because some backends (e.g., AArch64)
  624. // never list SP in the regmask.
  625. if (MO.isReg() && MO.isDef() && MO.getReg() &&
  626. TRI->isPhysicalRegister(MO.getReg()) &&
  627. !(MI.isCall() && MO.getReg() == SP)) {
  628. // Remove ranges of all aliased registers.
  629. for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
  630. for (unsigned ID : OpenRanges.getVarLocs())
  631. if (VarLocIDs[ID].isDescribedByReg() == *RAI)
  632. KillSet.set(ID);
  633. } else if (MO.isRegMask()) {
  634. // Remove ranges of all clobbered registers. Register masks don't usually
  635. // list SP as preserved. While the debug info may be off for an
  636. // instruction or two around callee-cleanup calls, transferring the
  637. // DEBUG_VALUE across the call is still a better user experience.
  638. for (unsigned ID : OpenRanges.getVarLocs()) {
  639. unsigned Reg = VarLocIDs[ID].isDescribedByReg();
  640. if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
  641. KillSet.set(ID);
  642. }
  643. }
  644. }
  645. OpenRanges.erase(KillSet, VarLocIDs);
  646. if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
  647. auto &TM = TPC->getTM<TargetMachine>();
  648. if (TM.Options.EnableDebugEntryValues)
  649. emitEntryValues(MI, OpenRanges, VarLocIDs, Transfers, DebugEntryVals,
  650. KillSet);
  651. }
  652. }
  653. /// Decide if @MI is a spill instruction and return true if it is. We use 2
  654. /// criteria to make this decision:
  655. /// - Is this instruction a store to a spill slot?
  656. /// - Is there a register operand that is both used and killed?
  657. /// TODO: Store optimization can fold spills into other stores (including
  658. /// other spills). We do not handle this yet (more than one memory operand).
  659. bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
  660. MachineFunction *MF, unsigned &Reg) {
  661. SmallVector<const MachineMemOperand*, 1> Accesses;
  662. // TODO: Handle multiple stores folded into one.
  663. if (!MI.hasOneMemOperand())
  664. return false;
  665. if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
  666. return false; // This is not a spill instruction, since no valid size was
  667. // returned from either function.
  668. auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
  669. if (!MO.isReg() || !MO.isUse()) {
  670. Reg = 0;
  671. return false;
  672. }
  673. Reg = MO.getReg();
  674. return MO.isKill();
  675. };
  676. for (const MachineOperand &MO : MI.operands()) {
  677. // In a spill instruction generated by the InlineSpiller the spilled
  678. // register has its kill flag set.
  679. if (isKilledReg(MO, Reg))
  680. return true;
  681. if (Reg != 0) {
  682. // Check whether next instruction kills the spilled register.
  683. // FIXME: Current solution does not cover search for killed register in
  684. // bundles and instructions further down the chain.
  685. auto NextI = std::next(MI.getIterator());
  686. // Skip next instruction that points to basic block end iterator.
  687. if (MI.getParent()->end() == NextI)
  688. continue;
  689. unsigned RegNext;
  690. for (const MachineOperand &MONext : NextI->operands()) {
  691. // Return true if we came across the register from the
  692. // previous spill instruction that is killed in NextI.
  693. if (isKilledReg(MONext, RegNext) && RegNext == Reg)
  694. return true;
  695. }
  696. }
  697. }
  698. // Return false if we didn't find spilled register.
  699. return false;
  700. }
  701. Optional<LiveDebugValues::VarLoc::SpillLoc>
  702. LiveDebugValues::isRestoreInstruction(const MachineInstr &MI,
  703. MachineFunction *MF, unsigned &Reg) {
  704. if (!MI.hasOneMemOperand())
  705. return None;
  706. // FIXME: Handle folded restore instructions with more than one memory
  707. // operand.
  708. if (MI.getRestoreSize(TII)) {
  709. Reg = MI.getOperand(0).getReg();
  710. return extractSpillBaseRegAndOffset(MI);
  711. }
  712. return None;
  713. }
  714. /// A spilled register may indicate that we have to end the current range of
  715. /// a variable and create a new one for the spill location.
  716. /// A restored register may indicate the reverse situation.
  717. /// We don't want to insert any instructions in process(), so we just create
  718. /// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
  719. /// It will be inserted into the BB when we're done iterating over the
  720. /// instructions.
  721. void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr &MI,
  722. OpenRangesSet &OpenRanges,
  723. VarLocMap &VarLocIDs,
  724. TransferMap &Transfers) {
  725. MachineFunction *MF = MI.getMF();
  726. TransferKind TKind;
  727. unsigned Reg;
  728. Optional<VarLoc::SpillLoc> Loc;
  729. LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
  730. if (isSpillInstruction(MI, MF, Reg)) {
  731. TKind = TransferKind::TransferSpill;
  732. LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
  733. LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
  734. << "\n");
  735. } else {
  736. if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
  737. return;
  738. TKind = TransferKind::TransferRestore;
  739. LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
  740. LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
  741. << "\n");
  742. }
  743. // Check if the register or spill location is the location of a debug value.
  744. for (unsigned ID : OpenRanges.getVarLocs()) {
  745. if (TKind == TransferKind::TransferSpill &&
  746. VarLocIDs[ID].isDescribedByReg() == Reg) {
  747. LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
  748. << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
  749. } else if (TKind == TransferKind::TransferRestore &&
  750. VarLocIDs[ID].Loc.SpillLocation == *Loc) {
  751. LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
  752. << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
  753. } else
  754. continue;
  755. insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID, TKind,
  756. Reg);
  757. return;
  758. }
  759. }
  760. /// If \p MI is a register copy instruction, that copies a previously tracked
  761. /// value from one register to another register that is callee saved, we
  762. /// create new DBG_VALUE instruction described with copy destination register.
  763. void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
  764. OpenRangesSet &OpenRanges,
  765. VarLocMap &VarLocIDs,
  766. TransferMap &Transfers) {
  767. const MachineOperand *SrcRegOp, *DestRegOp;
  768. if (!TII->isCopyInstr(MI, SrcRegOp, DestRegOp) || !SrcRegOp->isKill() ||
  769. !DestRegOp->isDef())
  770. return;
  771. auto isCalleSavedReg = [&](unsigned Reg) {
  772. for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
  773. if (CalleeSavedRegs.test(*RAI))
  774. return true;
  775. return false;
  776. };
  777. unsigned SrcReg = SrcRegOp->getReg();
  778. unsigned DestReg = DestRegOp->getReg();
  779. // We want to recognize instructions where destination register is callee
  780. // saved register. If register that could be clobbered by the call is
  781. // included, there would be a great chance that it is going to be clobbered
  782. // soon. It is more likely that previous register location, which is callee
  783. // saved, is going to stay unclobbered longer, even if it is killed.
  784. if (!isCalleSavedReg(DestReg))
  785. return;
  786. for (unsigned ID : OpenRanges.getVarLocs()) {
  787. if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
  788. insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
  789. TransferKind::TransferCopy, DestReg);
  790. return;
  791. }
  792. }
  793. }
  794. /// Terminate all open ranges at the end of the current basic block.
  795. bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
  796. OpenRangesSet &OpenRanges,
  797. VarLocInMBB &OutLocs,
  798. const VarLocMap &VarLocIDs) {
  799. bool Changed = false;
  800. const MachineBasicBlock *CurMBB = MI.getParent();
  801. if (!(MI.isTerminator() || (&MI == &CurMBB->back())))
  802. return false;
  803. if (OpenRanges.empty())
  804. return false;
  805. LLVM_DEBUG(for (unsigned ID
  806. : OpenRanges.getVarLocs()) {
  807. // Copy OpenRanges to OutLocs, if not already present.
  808. dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
  809. VarLocIDs[ID].dump();
  810. });
  811. VarLocSet &VLS = OutLocs[CurMBB];
  812. Changed = VLS |= OpenRanges.getVarLocs();
  813. // New OutLocs set may be different due to spill, restore or register
  814. // copy instruction processing.
  815. if (Changed)
  816. VLS = OpenRanges.getVarLocs();
  817. OpenRanges.clear();
  818. return Changed;
  819. }
  820. /// Accumulate a mapping between each DILocalVariable fragment and other
  821. /// fragments of that DILocalVariable which overlap. This reduces work during
  822. /// the data-flow stage from "Find any overlapping fragments" to "Check if the
  823. /// known-to-overlap fragments are present".
  824. /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
  825. /// fragment usage.
  826. /// \param SeenFragments Map from DILocalVariable to all fragments of that
  827. /// Variable which are known to exist.
  828. /// \param OverlappingFragments The overlap map being constructed, from one
  829. /// Var/Fragment pair to a vector of fragments known to overlap.
  830. void LiveDebugValues::accumulateFragmentMap(MachineInstr &MI,
  831. VarToFragments &SeenFragments,
  832. OverlapMap &OverlappingFragments) {
  833. DebugVariable MIVar(MI);
  834. FragmentInfo ThisFragment = MIVar.getFragmentDefault();
  835. // If this is the first sighting of this variable, then we are guaranteed
  836. // there are currently no overlapping fragments either. Initialize the set
  837. // of seen fragments, record no overlaps for the current one, and return.
  838. auto SeenIt = SeenFragments.find(MIVar.getVar());
  839. if (SeenIt == SeenFragments.end()) {
  840. SmallSet<FragmentInfo, 4> OneFragment;
  841. OneFragment.insert(ThisFragment);
  842. SeenFragments.insert({MIVar.getVar(), OneFragment});
  843. OverlappingFragments.insert({{MIVar.getVar(), ThisFragment}, {}});
  844. return;
  845. }
  846. // If this particular Variable/Fragment pair already exists in the overlap
  847. // map, it has already been accounted for.
  848. auto IsInOLapMap =
  849. OverlappingFragments.insert({{MIVar.getVar(), ThisFragment}, {}});
  850. if (!IsInOLapMap.second)
  851. return;
  852. auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
  853. auto &AllSeenFragments = SeenIt->second;
  854. // Otherwise, examine all other seen fragments for this variable, with "this"
  855. // fragment being a previously unseen fragment. Record any pair of
  856. // overlapping fragments.
  857. for (auto &ASeenFragment : AllSeenFragments) {
  858. // Does this previously seen fragment overlap?
  859. if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
  860. // Yes: Mark the current fragment as being overlapped.
  861. ThisFragmentsOverlaps.push_back(ASeenFragment);
  862. // Mark the previously seen fragment as being overlapped by the current
  863. // one.
  864. auto ASeenFragmentsOverlaps =
  865. OverlappingFragments.find({MIVar.getVar(), ASeenFragment});
  866. assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
  867. "Previously seen var fragment has no vector of overlaps");
  868. ASeenFragmentsOverlaps->second.push_back(ThisFragment);
  869. }
  870. }
  871. AllSeenFragments.insert(ThisFragment);
  872. }
  873. /// This routine creates OpenRanges and OutLocs.
  874. bool LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
  875. VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
  876. TransferMap &Transfers, DebugParamMap &DebugEntryVals,
  877. bool transferChanges,
  878. OverlapMap &OverlapFragments,
  879. VarToFragments &SeenFragments) {
  880. bool Changed = false;
  881. transferDebugValue(MI, OpenRanges, VarLocIDs);
  882. transferRegisterDef(MI, OpenRanges, VarLocIDs, Transfers,
  883. DebugEntryVals);
  884. if (transferChanges) {
  885. transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
  886. transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
  887. } else {
  888. // Build up a map of overlapping fragments on the first run through.
  889. if (MI.isDebugValue())
  890. accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
  891. }
  892. Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
  893. return Changed;
  894. }
  895. /// This routine joins the analysis results of all incoming edges in @MBB by
  896. /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
  897. /// source variable in all the predecessors of @MBB reside in the same location.
  898. bool LiveDebugValues::join(
  899. MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
  900. const VarLocMap &VarLocIDs,
  901. SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
  902. SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
  903. LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
  904. bool Changed = false;
  905. VarLocSet InLocsT; // Temporary incoming locations.
  906. // For all predecessors of this MBB, find the set of VarLocs that
  907. // can be joined.
  908. int NumVisited = 0;
  909. for (auto p : MBB.predecessors()) {
  910. // Ignore unvisited predecessor blocks. As we are processing
  911. // the blocks in reverse post-order any unvisited block can
  912. // be considered to not remove any incoming values.
  913. if (!Visited.count(p)) {
  914. LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
  915. << "\n");
  916. continue;
  917. }
  918. auto OL = OutLocs.find(p);
  919. // Join is null in case of empty OutLocs from any of the pred.
  920. if (OL == OutLocs.end())
  921. return false;
  922. // Just copy over the Out locs to incoming locs for the first visited
  923. // predecessor, and for all other predecessors join the Out locs.
  924. if (!NumVisited)
  925. InLocsT = OL->second;
  926. else
  927. InLocsT &= OL->second;
  928. LLVM_DEBUG({
  929. if (!InLocsT.empty()) {
  930. for (auto ID : InLocsT)
  931. dbgs() << " gathered candidate incoming var: "
  932. << VarLocIDs[ID].Var.getVar()->getName() << "\n";
  933. }
  934. });
  935. NumVisited++;
  936. }
  937. // Filter out DBG_VALUES that are out of scope.
  938. VarLocSet KillSet;
  939. bool IsArtificial = ArtificialBlocks.count(&MBB);
  940. if (!IsArtificial) {
  941. for (auto ID : InLocsT) {
  942. if (!VarLocIDs[ID].dominates(MBB)) {
  943. KillSet.set(ID);
  944. LLVM_DEBUG({
  945. auto Name = VarLocIDs[ID].Var.getVar()->getName();
  946. dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
  947. });
  948. }
  949. }
  950. }
  951. InLocsT.intersectWithComplement(KillSet);
  952. // As we are processing blocks in reverse post-order we
  953. // should have processed at least one predecessor, unless it
  954. // is the entry block which has no predecessor.
  955. assert((NumVisited || MBB.pred_empty()) &&
  956. "Should have processed at least one predecessor");
  957. if (InLocsT.empty())
  958. return false;
  959. VarLocSet &ILS = InLocs[&MBB];
  960. // Insert DBG_VALUE instructions, if not already inserted.
  961. VarLocSet Diff = InLocsT;
  962. Diff.intersectWithComplement(ILS);
  963. for (auto ID : Diff) {
  964. // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
  965. // new range is started for the var from the mbb's beginning by inserting
  966. // a new DBG_VALUE. process() will end this range however appropriate.
  967. const VarLoc &DiffIt = VarLocIDs[ID];
  968. const MachineInstr *DebugInstr = &DiffIt.MI;
  969. MachineInstr *MI = nullptr;
  970. if (DiffIt.isConstant()) {
  971. MachineOperand MO(DebugInstr->getOperand(0));
  972. MI = BuildMI(MBB, MBB.instr_begin(), DebugInstr->getDebugLoc(),
  973. DebugInstr->getDesc(), false, MO,
  974. DebugInstr->getDebugVariable(),
  975. DebugInstr->getDebugExpression());
  976. } else {
  977. MI = BuildMI(MBB, MBB.instr_begin(), DebugInstr->getDebugLoc(),
  978. DebugInstr->getDesc(), DebugInstr->isIndirectDebugValue(),
  979. DebugInstr->getOperand(0).getReg(),
  980. DebugInstr->getDebugVariable(),
  981. DebugInstr->getDebugExpression());
  982. if (DebugInstr->isIndirectDebugValue())
  983. MI->getOperand(1).setImm(DebugInstr->getOperand(1).getImm());
  984. }
  985. LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
  986. ILS.set(ID);
  987. ++NumInserted;
  988. Changed = true;
  989. }
  990. return Changed;
  991. }
  992. /// Calculate the liveness information for the given machine function and
  993. /// extend ranges across basic blocks.
  994. bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
  995. LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
  996. bool Changed = false;
  997. bool OLChanged = false;
  998. bool MBBJoined = false;
  999. VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
  1000. OverlapMap OverlapFragments; // Map of overlapping variable fragments
  1001. OpenRangesSet OpenRanges(OverlapFragments);
  1002. // Ranges that are open until end of bb.
  1003. VarLocInMBB OutLocs; // Ranges that exist beyond bb.
  1004. VarLocInMBB InLocs; // Ranges that are incoming after joining.
  1005. TransferMap Transfers; // DBG_VALUEs associated with spills.
  1006. VarToFragments SeenFragments;
  1007. // Blocks which are artificial, i.e. blocks which exclusively contain
  1008. // instructions without locations, or with line 0 locations.
  1009. SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
  1010. DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
  1011. DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
  1012. std::priority_queue<unsigned int, std::vector<unsigned int>,
  1013. std::greater<unsigned int>>
  1014. Worklist;
  1015. std::priority_queue<unsigned int, std::vector<unsigned int>,
  1016. std::greater<unsigned int>>
  1017. Pending;
  1018. enum : bool { dontTransferChanges = false, transferChanges = true };
  1019. // Besides parameter's modification, check whether a DBG_VALUE is inlined
  1020. // in order to deduce whether the variable that it tracks comes from
  1021. // a different function. If that is the case we can't track its entry value.
  1022. auto IsUnmodifiedFuncParam = [&](const MachineInstr &MI) {
  1023. auto *DIVar = MI.getDebugVariable();
  1024. return DIVar->isParameter() && DIVar->isNotModified() &&
  1025. !MI.getDebugLoc()->getInlinedAt();
  1026. };
  1027. const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
  1028. unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
  1029. unsigned FP = TRI->getFrameRegister(MF);
  1030. auto IsRegOtherThanSPAndFP = [&](const MachineOperand &Op) -> bool {
  1031. return Op.isReg() && Op.getReg() != SP && Op.getReg() != FP;
  1032. };
  1033. // Working set of currently collected debug variables mapped to DBG_VALUEs
  1034. // representing candidates for production of debug entry values.
  1035. DebugParamMap DebugEntryVals;
  1036. MachineBasicBlock &First_MBB = *(MF.begin());
  1037. // Only in the case of entry MBB collect DBG_VALUEs representing
  1038. // function parameters in order to generate debug entry values for them.
  1039. // Currently, we generate debug entry values only for parameters that are
  1040. // unmodified throughout the function and located in a register.
  1041. // TODO: Add support for parameters that are described as fragments.
  1042. // TODO: Add support for modified arguments that can be expressed
  1043. // by using its entry value.
  1044. // TODO: Add support for local variables that are expressed in terms of
  1045. // parameters entry values.
  1046. for (auto &MI : First_MBB)
  1047. if (MI.isDebugValue() && IsUnmodifiedFuncParam(MI) &&
  1048. !MI.isIndirectDebugValue() && IsRegOtherThanSPAndFP(MI.getOperand(0)) &&
  1049. !DebugEntryVals.count(MI.getDebugVariable()) &&
  1050. !MI.getDebugExpression()->isFragment())
  1051. DebugEntryVals[MI.getDebugVariable()] = &MI;
  1052. // Initialize every mbb with OutLocs.
  1053. // We are not looking at any spill instructions during the initial pass
  1054. // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
  1055. // instructions for spills of registers that are known to be user variables
  1056. // within the BB in which the spill occurs.
  1057. for (auto &MBB : MF) {
  1058. for (auto &MI : MBB) {
  1059. process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers, DebugEntryVals,
  1060. dontTransferChanges, OverlapFragments, SeenFragments);
  1061. }
  1062. // Add any entry DBG_VALUE instructions necessitated by parameter
  1063. // clobbering.
  1064. for (auto &TR : Transfers) {
  1065. MBB.insertAfter(MachineBasicBlock::iterator(*TR.TransferInst),
  1066. TR.DebugInst);
  1067. }
  1068. Transfers.clear();
  1069. }
  1070. auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
  1071. if (const DebugLoc &DL = MI.getDebugLoc())
  1072. return DL.getLine() != 0;
  1073. return false;
  1074. };
  1075. for (auto &MBB : MF)
  1076. if (none_of(MBB.instrs(), hasNonArtificialLocation))
  1077. ArtificialBlocks.insert(&MBB);
  1078. LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
  1079. "OutLocs after initialization", dbgs()));
  1080. ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
  1081. unsigned int RPONumber = 0;
  1082. for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
  1083. OrderToBB[RPONumber] = *RI;
  1084. BBToOrder[*RI] = RPONumber;
  1085. Worklist.push(RPONumber);
  1086. ++RPONumber;
  1087. }
  1088. // This is a standard "union of predecessor outs" dataflow problem.
  1089. // To solve it, we perform join() and process() using the two worklist method
  1090. // until the ranges converge.
  1091. // Ranges have converged when both worklists are empty.
  1092. SmallPtrSet<const MachineBasicBlock *, 16> Visited;
  1093. while (!Worklist.empty() || !Pending.empty()) {
  1094. // We track what is on the pending worklist to avoid inserting the same
  1095. // thing twice. We could avoid this with a custom priority queue, but this
  1096. // is probably not worth it.
  1097. SmallPtrSet<MachineBasicBlock *, 16> OnPending;
  1098. LLVM_DEBUG(dbgs() << "Processing Worklist\n");
  1099. while (!Worklist.empty()) {
  1100. MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
  1101. Worklist.pop();
  1102. MBBJoined =
  1103. join(*MBB, OutLocs, InLocs, VarLocIDs, Visited, ArtificialBlocks);
  1104. Visited.insert(MBB);
  1105. if (MBBJoined) {
  1106. MBBJoined = false;
  1107. Changed = true;
  1108. // Now that we have started to extend ranges across BBs we need to
  1109. // examine spill instructions to see whether they spill registers that
  1110. // correspond to user variables.
  1111. for (auto &MI : *MBB)
  1112. OLChanged |=
  1113. process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
  1114. DebugEntryVals, transferChanges, OverlapFragments,
  1115. SeenFragments);
  1116. // Add any DBG_VALUE instructions necessitated by spills.
  1117. for (auto &TR : Transfers)
  1118. MBB->insertAfter(MachineBasicBlock::iterator(*TR.TransferInst),
  1119. TR.DebugInst);
  1120. Transfers.clear();
  1121. LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
  1122. "OutLocs after propagating", dbgs()));
  1123. LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
  1124. "InLocs after propagating", dbgs()));
  1125. if (OLChanged) {
  1126. OLChanged = false;
  1127. for (auto s : MBB->successors())
  1128. if (OnPending.insert(s).second) {
  1129. Pending.push(BBToOrder[s]);
  1130. }
  1131. }
  1132. }
  1133. }
  1134. Worklist.swap(Pending);
  1135. // At this point, pending must be empty, since it was just the empty
  1136. // worklist
  1137. assert(Pending.empty() && "Pending should be empty");
  1138. }
  1139. LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
  1140. LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
  1141. return Changed;
  1142. }
  1143. bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
  1144. if (!MF.getFunction().getSubprogram())
  1145. // LiveDebugValues will already have removed all DBG_VALUEs.
  1146. return false;
  1147. // Skip functions from NoDebug compilation units.
  1148. if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
  1149. DICompileUnit::NoDebug)
  1150. return false;
  1151. TRI = MF.getSubtarget().getRegisterInfo();
  1152. TII = MF.getSubtarget().getInstrInfo();
  1153. TFI = MF.getSubtarget().getFrameLowering();
  1154. TFI->determineCalleeSaves(MF, CalleeSavedRegs,
  1155. make_unique<RegScavenger>().get());
  1156. LS.initialize(MF);
  1157. bool Changed = ExtendRanges(MF);
  1158. return Changed;
  1159. }