LiveDebugVariables.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  1. //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the LiveDebugVariables analysis.
  11. //
  12. // Remove all DBG_VALUE instructions referencing virtual registers and replace
  13. // them with a data structure tracking where live user variables are kept - in a
  14. // virtual register or in a stack slot.
  15. //
  16. // Allow the data structure to be updated during register allocation when values
  17. // are moved between registers and stack slots. Finally emit new DBG_VALUE
  18. // instructions after register allocation is complete.
  19. //
  20. //===----------------------------------------------------------------------===//
  21. #include "LiveDebugVariables.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/IntervalMap.h"
  25. #include "llvm/ADT/STLExtras.h"
  26. #include "llvm/ADT/SmallSet.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/Statistic.h"
  29. #include "llvm/ADT/StringRef.h"
  30. #include "llvm/CodeGen/LexicalScopes.h"
  31. #include "llvm/CodeGen/LiveInterval.h"
  32. #include "llvm/CodeGen/LiveIntervals.h"
  33. #include "llvm/CodeGen/MachineBasicBlock.h"
  34. #include "llvm/CodeGen/MachineDominators.h"
  35. #include "llvm/CodeGen/MachineFunction.h"
  36. #include "llvm/CodeGen/MachineInstr.h"
  37. #include "llvm/CodeGen/MachineInstrBuilder.h"
  38. #include "llvm/CodeGen/MachineOperand.h"
  39. #include "llvm/CodeGen/MachineRegisterInfo.h"
  40. #include "llvm/CodeGen/SlotIndexes.h"
  41. #include "llvm/CodeGen/TargetInstrInfo.h"
  42. #include "llvm/CodeGen/TargetOpcodes.h"
  43. #include "llvm/CodeGen/TargetRegisterInfo.h"
  44. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  45. #include "llvm/CodeGen/VirtRegMap.h"
  46. #include "llvm/Config/llvm-config.h"
  47. #include "llvm/IR/DebugInfoMetadata.h"
  48. #include "llvm/IR/DebugLoc.h"
  49. #include "llvm/IR/Function.h"
  50. #include "llvm/IR/Metadata.h"
  51. #include "llvm/MC/MCRegisterInfo.h"
  52. #include "llvm/Pass.h"
  53. #include "llvm/Support/Casting.h"
  54. #include "llvm/Support/CommandLine.h"
  55. #include "llvm/Support/Compiler.h"
  56. #include "llvm/Support/Debug.h"
  57. #include "llvm/Support/raw_ostream.h"
  58. #include <algorithm>
  59. #include <cassert>
  60. #include <iterator>
  61. #include <memory>
  62. #include <utility>
  63. using namespace llvm;
  64. #define DEBUG_TYPE "livedebugvars"
  65. static cl::opt<bool>
  66. EnableLDV("live-debug-variables", cl::init(true),
  67. cl::desc("Enable the live debug variables pass"), cl::Hidden);
  68. STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
  69. STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
  70. char LiveDebugVariables::ID = 0;
  71. INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
  72. "Debug Variable Analysis", false, false)
  73. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  74. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  75. INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
  76. "Debug Variable Analysis", false, false)
  77. void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
  78. AU.addRequired<MachineDominatorTree>();
  79. AU.addRequiredTransitive<LiveIntervals>();
  80. AU.setPreservesAll();
  81. MachineFunctionPass::getAnalysisUsage(AU);
  82. }
  83. LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
  84. initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
  85. }
  86. enum : unsigned { UndefLocNo = ~0U };
  87. /// Describes a location by number along with some flags about the original
  88. /// usage of the location.
  89. class DbgValueLocation {
  90. public:
  91. DbgValueLocation(unsigned LocNo, bool WasIndirect)
  92. : LocNo(LocNo), WasIndirect(WasIndirect) {
  93. static_assert(sizeof(*this) == sizeof(unsigned), "bad bitfield packing");
  94. assert(locNo() == LocNo && "location truncation");
  95. }
  96. DbgValueLocation() : LocNo(0), WasIndirect(0) {}
  97. unsigned locNo() const {
  98. // Fix up the undef location number, which gets truncated.
  99. return LocNo == INT_MAX ? UndefLocNo : LocNo;
  100. }
  101. bool wasIndirect() const { return WasIndirect; }
  102. bool isUndef() const { return locNo() == UndefLocNo; }
  103. DbgValueLocation changeLocNo(unsigned NewLocNo) const {
  104. return DbgValueLocation(NewLocNo, WasIndirect);
  105. }
  106. friend inline bool operator==(const DbgValueLocation &LHS,
  107. const DbgValueLocation &RHS) {
  108. return LHS.LocNo == RHS.LocNo && LHS.WasIndirect == RHS.WasIndirect;
  109. }
  110. friend inline bool operator!=(const DbgValueLocation &LHS,
  111. const DbgValueLocation &RHS) {
  112. return !(LHS == RHS);
  113. }
  114. private:
  115. unsigned LocNo : 31;
  116. unsigned WasIndirect : 1;
  117. };
  118. /// Map of where a user value is live, and its location.
  119. using LocMap = IntervalMap<SlotIndex, DbgValueLocation, 4>;
  120. /// Map of stack slot offsets for spilled locations.
  121. /// Non-spilled locations are not added to the map.
  122. using SpillOffsetMap = DenseMap<unsigned, unsigned>;
  123. namespace {
  124. class LDVImpl;
  125. /// A user value is a part of a debug info user variable.
  126. ///
  127. /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
  128. /// holds part of a user variable. The part is identified by a byte offset.
  129. ///
  130. /// UserValues are grouped into equivalence classes for easier searching. Two
  131. /// user values are related if they refer to the same variable, or if they are
  132. /// held by the same virtual register. The equivalence class is the transitive
  133. /// closure of that relation.
  134. class UserValue {
  135. const DILocalVariable *Variable; ///< The debug info variable we are part of.
  136. const DIExpression *Expression; ///< Any complex address expression.
  137. DebugLoc dl; ///< The debug location for the variable. This is
  138. ///< used by dwarf writer to find lexical scope.
  139. UserValue *leader; ///< Equivalence class leader.
  140. UserValue *next = nullptr; ///< Next value in equivalence class, or null.
  141. /// Numbered locations referenced by locmap.
  142. SmallVector<MachineOperand, 4> locations;
  143. /// Map of slot indices where this value is live.
  144. LocMap locInts;
  145. /// Set of interval start indexes that have been trimmed to the
  146. /// lexical scope.
  147. SmallSet<SlotIndex, 2> trimmedDefs;
  148. /// Insert a DBG_VALUE into MBB at Idx for LocNo.
  149. void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
  150. SlotIndex StopIdx, DbgValueLocation Loc, bool Spilled,
  151. unsigned SpillOffset, LiveIntervals &LIS,
  152. const TargetInstrInfo &TII,
  153. const TargetRegisterInfo &TRI);
  154. /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
  155. /// is live. Returns true if any changes were made.
  156. bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
  157. LiveIntervals &LIS);
  158. public:
  159. /// Create a new UserValue.
  160. UserValue(const DILocalVariable *var, const DIExpression *expr, DebugLoc L,
  161. LocMap::Allocator &alloc)
  162. : Variable(var), Expression(expr), dl(std::move(L)), leader(this),
  163. locInts(alloc) {}
  164. /// Get the leader of this value's equivalence class.
  165. UserValue *getLeader() {
  166. UserValue *l = leader;
  167. while (l != l->leader)
  168. l = l->leader;
  169. return leader = l;
  170. }
  171. /// Return the next UserValue in the equivalence class.
  172. UserValue *getNext() const { return next; }
  173. /// Does this UserValue match the parameters?
  174. bool match(const DILocalVariable *Var, const DIExpression *Expr,
  175. const DILocation *IA) const {
  176. // FIXME: The fragment should be part of the equivalence class, but not
  177. // other things in the expression like stack values.
  178. return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA;
  179. }
  180. /// Merge equivalence classes.
  181. static UserValue *merge(UserValue *L1, UserValue *L2) {
  182. L2 = L2->getLeader();
  183. if (!L1)
  184. return L2;
  185. L1 = L1->getLeader();
  186. if (L1 == L2)
  187. return L1;
  188. // Splice L2 before L1's members.
  189. UserValue *End = L2;
  190. while (End->next) {
  191. End->leader = L1;
  192. End = End->next;
  193. }
  194. End->leader = L1;
  195. End->next = L1->next;
  196. L1->next = L2;
  197. return L1;
  198. }
  199. /// Return the location number that matches Loc.
  200. ///
  201. /// For undef values we always return location number UndefLocNo without
  202. /// inserting anything in locations. Since locations is a vector and the
  203. /// location number is the position in the vector and UndefLocNo is ~0,
  204. /// we would need a very big vector to put the value at the right position.
  205. unsigned getLocationNo(const MachineOperand &LocMO) {
  206. if (LocMO.isReg()) {
  207. if (LocMO.getReg() == 0)
  208. return UndefLocNo;
  209. // For register locations we dont care about use/def and other flags.
  210. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  211. if (locations[i].isReg() &&
  212. locations[i].getReg() == LocMO.getReg() &&
  213. locations[i].getSubReg() == LocMO.getSubReg())
  214. return i;
  215. } else
  216. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  217. if (LocMO.isIdenticalTo(locations[i]))
  218. return i;
  219. locations.push_back(LocMO);
  220. // We are storing a MachineOperand outside a MachineInstr.
  221. locations.back().clearParent();
  222. // Don't store def operands.
  223. if (locations.back().isReg()) {
  224. if (locations.back().isDef())
  225. locations.back().setIsDead(false);
  226. locations.back().setIsUse();
  227. }
  228. return locations.size() - 1;
  229. }
  230. /// Ensure that all virtual register locations are mapped.
  231. void mapVirtRegs(LDVImpl *LDV);
  232. /// Add a definition point to this value.
  233. void addDef(SlotIndex Idx, const MachineOperand &LocMO, bool IsIndirect) {
  234. DbgValueLocation Loc(getLocationNo(LocMO), IsIndirect);
  235. // Add a singular (Idx,Idx) -> Loc mapping.
  236. LocMap::iterator I = locInts.find(Idx);
  237. if (!I.valid() || I.start() != Idx)
  238. I.insert(Idx, Idx.getNextSlot(), Loc);
  239. else
  240. // A later DBG_VALUE at the same SlotIndex overrides the old location.
  241. I.setValue(Loc);
  242. }
  243. /// Extend the current definition as far as possible down.
  244. ///
  245. /// Stop when meeting an existing def or when leaving the live
  246. /// range of VNI. End points where VNI is no longer live are added to Kills.
  247. ///
  248. /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
  249. /// data-flow analysis to propagate them beyond basic block boundaries.
  250. ///
  251. /// \param Idx Starting point for the definition.
  252. /// \param Loc Location number to propagate.
  253. /// \param LR Restrict liveness to where LR has the value VNI. May be null.
  254. /// \param VNI When LR is not null, this is the value to restrict to.
  255. /// \param [out] Kills Append end points of VNI's live range to Kills.
  256. /// \param LIS Live intervals analysis.
  257. void extendDef(SlotIndex Idx, DbgValueLocation Loc,
  258. LiveRange *LR, const VNInfo *VNI,
  259. SmallVectorImpl<SlotIndex> *Kills,
  260. LiveIntervals &LIS);
  261. /// The value in LI/LocNo may be copies to other registers. Determine if
  262. /// any of the copies are available at the kill points, and add defs if
  263. /// possible.
  264. ///
  265. /// \param LI Scan for copies of the value in LI->reg.
  266. /// \param LocNo Location number of LI->reg.
  267. /// \param WasIndirect Indicates if the original use of LI->reg was indirect
  268. /// \param Kills Points where the range of LocNo could be extended.
  269. /// \param [in,out] NewDefs Append (Idx, LocNo) of inserted defs here.
  270. void addDefsFromCopies(
  271. LiveInterval *LI, unsigned LocNo, bool WasIndirect,
  272. const SmallVectorImpl<SlotIndex> &Kills,
  273. SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
  274. MachineRegisterInfo &MRI, LiveIntervals &LIS);
  275. /// Compute the live intervals of all locations after collecting all their
  276. /// def points.
  277. void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
  278. LiveIntervals &LIS, LexicalScopes &LS);
  279. /// Replace OldReg ranges with NewRegs ranges where NewRegs is
  280. /// live. Returns true if any changes were made.
  281. bool splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
  282. LiveIntervals &LIS);
  283. /// Rewrite virtual register locations according to the provided virtual
  284. /// register map. Record the stack slot offsets for the locations that
  285. /// were spilled.
  286. void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
  287. const TargetInstrInfo &TII,
  288. const TargetRegisterInfo &TRI,
  289. SpillOffsetMap &SpillOffsets);
  290. /// Recreate DBG_VALUE instruction from data structures.
  291. void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
  292. const TargetInstrInfo &TII,
  293. const TargetRegisterInfo &TRI,
  294. const SpillOffsetMap &SpillOffsets);
  295. /// Return DebugLoc of this UserValue.
  296. DebugLoc getDebugLoc() { return dl;}
  297. void print(raw_ostream &, const TargetRegisterInfo *);
  298. };
  299. /// A user label is a part of a debug info user label.
  300. class UserLabel {
  301. const DILabel *Label; ///< The debug info label we are part of.
  302. DebugLoc dl; ///< The debug location for the label. This is
  303. ///< used by dwarf writer to find lexical scope.
  304. SlotIndex loc; ///< Slot used by the debug label.
  305. /// Insert a DBG_LABEL into MBB at Idx.
  306. void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
  307. LiveIntervals &LIS, const TargetInstrInfo &TII);
  308. public:
  309. /// Create a new UserLabel.
  310. UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
  311. : Label(label), dl(std::move(L)), loc(Idx) {}
  312. /// Does this UserLabel match the parameters?
  313. bool match(const DILabel *L, const DILocation *IA,
  314. const SlotIndex Index) const {
  315. return Label == L && dl->getInlinedAt() == IA && loc == Index;
  316. }
  317. /// Recreate DBG_LABEL instruction from data structures.
  318. void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII);
  319. /// Return DebugLoc of this UserLabel.
  320. DebugLoc getDebugLoc() { return dl; }
  321. void print(raw_ostream &, const TargetRegisterInfo *);
  322. };
  323. /// Implementation of the LiveDebugVariables pass.
  324. class LDVImpl {
  325. LiveDebugVariables &pass;
  326. LocMap::Allocator allocator;
  327. MachineFunction *MF = nullptr;
  328. LiveIntervals *LIS;
  329. const TargetRegisterInfo *TRI;
  330. /// Whether emitDebugValues is called.
  331. bool EmitDone = false;
  332. /// Whether the machine function is modified during the pass.
  333. bool ModifiedMF = false;
  334. /// All allocated UserValue instances.
  335. SmallVector<std::unique_ptr<UserValue>, 8> userValues;
  336. /// All allocated UserLabel instances.
  337. SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
  338. /// Map virtual register to eq class leader.
  339. using VRMap = DenseMap<unsigned, UserValue *>;
  340. VRMap virtRegToEqClass;
  341. /// Map user variable to eq class leader.
  342. using UVMap = DenseMap<const DILocalVariable *, UserValue *>;
  343. UVMap userVarMap;
  344. /// Find or create a UserValue.
  345. UserValue *getUserValue(const DILocalVariable *Var, const DIExpression *Expr,
  346. const DebugLoc &DL);
  347. /// Find the EC leader for VirtReg or null.
  348. UserValue *lookupVirtReg(unsigned VirtReg);
  349. /// Add DBG_VALUE instruction to our maps.
  350. ///
  351. /// \param MI DBG_VALUE instruction
  352. /// \param Idx Last valid SLotIndex before instruction.
  353. ///
  354. /// \returns True if the DBG_VALUE instruction should be deleted.
  355. bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
  356. /// Add DBG_LABEL instruction to UserLabel.
  357. ///
  358. /// \param MI DBG_LABEL instruction
  359. /// \param Idx Last valid SlotIndex before instruction.
  360. ///
  361. /// \returns True if the DBG_LABEL instruction should be deleted.
  362. bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
  363. /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
  364. /// for each instruction.
  365. ///
  366. /// \param mf MachineFunction to be scanned.
  367. ///
  368. /// \returns True if any debug values were found.
  369. bool collectDebugValues(MachineFunction &mf);
  370. /// Compute the live intervals of all user values after collecting all
  371. /// their def points.
  372. void computeIntervals();
  373. public:
  374. LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
  375. bool runOnMachineFunction(MachineFunction &mf);
  376. /// Release all memory.
  377. void clear() {
  378. MF = nullptr;
  379. userValues.clear();
  380. userLabels.clear();
  381. virtRegToEqClass.clear();
  382. userVarMap.clear();
  383. // Make sure we call emitDebugValues if the machine function was modified.
  384. assert((!ModifiedMF || EmitDone) &&
  385. "Dbg values are not emitted in LDV");
  386. EmitDone = false;
  387. ModifiedMF = false;
  388. }
  389. /// Map virtual register to an equivalence class.
  390. void mapVirtReg(unsigned VirtReg, UserValue *EC);
  391. /// Replace all references to OldReg with NewRegs.
  392. void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
  393. /// Recreate DBG_VALUE instruction from data structures.
  394. void emitDebugValues(VirtRegMap *VRM);
  395. void print(raw_ostream&);
  396. };
  397. } // end anonymous namespace
  398. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  399. static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
  400. const LLVMContext &Ctx) {
  401. if (!DL)
  402. return;
  403. auto *Scope = cast<DIScope>(DL.getScope());
  404. // Omit the directory, because it's likely to be long and uninteresting.
  405. CommentOS << Scope->getFilename();
  406. CommentOS << ':' << DL.getLine();
  407. if (DL.getCol() != 0)
  408. CommentOS << ':' << DL.getCol();
  409. DebugLoc InlinedAtDL = DL.getInlinedAt();
  410. if (!InlinedAtDL)
  411. return;
  412. CommentOS << " @[ ";
  413. printDebugLoc(InlinedAtDL, CommentOS, Ctx);
  414. CommentOS << " ]";
  415. }
  416. static void printExtendedName(raw_ostream &OS, const DINode *Node,
  417. const DILocation *DL) {
  418. const LLVMContext &Ctx = Node->getContext();
  419. StringRef Res;
  420. unsigned Line;
  421. if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
  422. Res = V->getName();
  423. Line = V->getLine();
  424. } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
  425. Res = L->getName();
  426. Line = L->getLine();
  427. }
  428. if (!Res.empty())
  429. OS << Res << "," << Line;
  430. if (auto *InlinedAt = DL->getInlinedAt()) {
  431. if (DebugLoc InlinedAtDL = InlinedAt) {
  432. OS << " @[";
  433. printDebugLoc(InlinedAtDL, OS, Ctx);
  434. OS << "]";
  435. }
  436. }
  437. }
  438. void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
  439. OS << "!\"";
  440. printExtendedName(OS, Variable, dl);
  441. OS << "\"\t";
  442. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
  443. OS << " [" << I.start() << ';' << I.stop() << "):";
  444. if (I.value().isUndef())
  445. OS << "undef";
  446. else {
  447. OS << I.value().locNo();
  448. if (I.value().wasIndirect())
  449. OS << " ind";
  450. }
  451. }
  452. for (unsigned i = 0, e = locations.size(); i != e; ++i) {
  453. OS << " Loc" << i << '=';
  454. locations[i].print(OS, TRI);
  455. }
  456. OS << '\n';
  457. }
  458. void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
  459. OS << "!\"";
  460. printExtendedName(OS, Label, dl);
  461. OS << "\"\t";
  462. OS << loc;
  463. OS << '\n';
  464. }
  465. void LDVImpl::print(raw_ostream &OS) {
  466. OS << "********** DEBUG VARIABLES **********\n";
  467. for (auto &userValue : userValues)
  468. userValue->print(OS, TRI);
  469. OS << "********** DEBUG LABELS **********\n";
  470. for (auto &userLabel : userLabels)
  471. userLabel->print(OS, TRI);
  472. }
  473. #endif
  474. void UserValue::mapVirtRegs(LDVImpl *LDV) {
  475. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  476. if (locations[i].isReg() &&
  477. TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
  478. LDV->mapVirtReg(locations[i].getReg(), this);
  479. }
  480. UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
  481. const DIExpression *Expr, const DebugLoc &DL) {
  482. UserValue *&Leader = userVarMap[Var];
  483. if (Leader) {
  484. UserValue *UV = Leader->getLeader();
  485. Leader = UV;
  486. for (; UV; UV = UV->getNext())
  487. if (UV->match(Var, Expr, DL->getInlinedAt()))
  488. return UV;
  489. }
  490. userValues.push_back(
  491. llvm::make_unique<UserValue>(Var, Expr, DL, allocator));
  492. UserValue *UV = userValues.back().get();
  493. Leader = UserValue::merge(Leader, UV);
  494. return UV;
  495. }
  496. void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
  497. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
  498. UserValue *&Leader = virtRegToEqClass[VirtReg];
  499. Leader = UserValue::merge(Leader, EC);
  500. }
  501. UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
  502. if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
  503. return UV->getLeader();
  504. return nullptr;
  505. }
  506. bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
  507. // DBG_VALUE loc, offset, variable
  508. if (MI.getNumOperands() != 4 ||
  509. !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
  510. !MI.getOperand(2).isMetadata()) {
  511. LLVM_DEBUG(dbgs() << "Can't handle " << MI);
  512. return false;
  513. }
  514. // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
  515. // register that hasn't been defined yet. If we do not remove those here, then
  516. // the re-insertion of the DBG_VALUE instruction after register allocation
  517. // will be incorrect.
  518. // TODO: If earlier passes are corrected to generate sane debug information
  519. // (and if the machine verifier is improved to catch this), then these checks
  520. // could be removed or replaced by asserts.
  521. bool Discard = false;
  522. if (MI.getOperand(0).isReg() &&
  523. TargetRegisterInfo::isVirtualRegister(MI.getOperand(0).getReg())) {
  524. const unsigned Reg = MI.getOperand(0).getReg();
  525. if (!LIS->hasInterval(Reg)) {
  526. // The DBG_VALUE is described by a virtual register that does not have a
  527. // live interval. Discard the DBG_VALUE.
  528. Discard = true;
  529. LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
  530. << " " << MI);
  531. } else {
  532. // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg
  533. // is defined dead at Idx (where Idx is the slot index for the instruction
  534. // preceeding the DBG_VALUE).
  535. const LiveInterval &LI = LIS->getInterval(Reg);
  536. LiveQueryResult LRQ = LI.Query(Idx);
  537. if (!LRQ.valueOutOrDead()) {
  538. // We have found a DBG_VALUE with the value in a virtual register that
  539. // is not live. Discard the DBG_VALUE.
  540. Discard = true;
  541. LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
  542. << " " << MI);
  543. }
  544. }
  545. }
  546. // Get or create the UserValue for (variable,offset) here.
  547. bool IsIndirect = MI.getOperand(1).isImm();
  548. if (IsIndirect)
  549. assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
  550. const DILocalVariable *Var = MI.getDebugVariable();
  551. const DIExpression *Expr = MI.getDebugExpression();
  552. UserValue *UV =
  553. getUserValue(Var, Expr, MI.getDebugLoc());
  554. if (!Discard)
  555. UV->addDef(Idx, MI.getOperand(0), IsIndirect);
  556. else {
  557. MachineOperand MO = MachineOperand::CreateReg(0U, false);
  558. MO.setIsDebug();
  559. UV->addDef(Idx, MO, false);
  560. }
  561. return true;
  562. }
  563. bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) {
  564. // DBG_LABEL label
  565. if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
  566. LLVM_DEBUG(dbgs() << "Can't handle " << MI);
  567. return false;
  568. }
  569. // Get or create the UserLabel for label here.
  570. const DILabel *Label = MI.getDebugLabel();
  571. const DebugLoc &DL = MI.getDebugLoc();
  572. bool Found = false;
  573. for (auto const &L : userLabels) {
  574. if (L->match(Label, DL->getInlinedAt(), Idx)) {
  575. Found = true;
  576. break;
  577. }
  578. }
  579. if (!Found)
  580. userLabels.push_back(llvm::make_unique<UserLabel>(Label, DL, Idx));
  581. return true;
  582. }
  583. bool LDVImpl::collectDebugValues(MachineFunction &mf) {
  584. bool Changed = false;
  585. for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
  586. ++MFI) {
  587. MachineBasicBlock *MBB = &*MFI;
  588. for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
  589. MBBI != MBBE;) {
  590. // Use the first debug instruction in the sequence to get a SlotIndex
  591. // for following consecutive debug instructions.
  592. if (!MBBI->isDebugInstr()) {
  593. ++MBBI;
  594. continue;
  595. }
  596. // Debug instructions has no slot index. Use the previous
  597. // non-debug instruction's SlotIndex as its SlotIndex.
  598. SlotIndex Idx =
  599. MBBI == MBB->begin()
  600. ? LIS->getMBBStartIdx(MBB)
  601. : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
  602. // Handle consecutive debug instructions with the same slot index.
  603. do {
  604. // Only handle DBG_VALUE in handleDebugValue(). Skip all other
  605. // kinds of debug instructions.
  606. if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
  607. (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
  608. MBBI = MBB->erase(MBBI);
  609. Changed = true;
  610. } else
  611. ++MBBI;
  612. } while (MBBI != MBBE && MBBI->isDebugInstr());
  613. }
  614. }
  615. return Changed;
  616. }
  617. void UserValue::extendDef(SlotIndex Idx, DbgValueLocation Loc, LiveRange *LR,
  618. const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
  619. LiveIntervals &LIS) {
  620. SlotIndex Start = Idx;
  621. MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
  622. SlotIndex Stop = LIS.getMBBEndIdx(MBB);
  623. LocMap::iterator I = locInts.find(Start);
  624. // Limit to VNI's live range.
  625. bool ToEnd = true;
  626. if (LR && VNI) {
  627. LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
  628. if (!Segment || Segment->valno != VNI) {
  629. if (Kills)
  630. Kills->push_back(Start);
  631. return;
  632. }
  633. if (Segment->end < Stop) {
  634. Stop = Segment->end;
  635. ToEnd = false;
  636. }
  637. }
  638. // There could already be a short def at Start.
  639. if (I.valid() && I.start() <= Start) {
  640. // Stop when meeting a different location or an already extended interval.
  641. Start = Start.getNextSlot();
  642. if (I.value() != Loc || I.stop() != Start)
  643. return;
  644. // This is a one-slot placeholder. Just skip it.
  645. ++I;
  646. }
  647. // Limited by the next def.
  648. if (I.valid() && I.start() < Stop) {
  649. Stop = I.start();
  650. ToEnd = false;
  651. }
  652. // Limited by VNI's live range.
  653. else if (!ToEnd && Kills)
  654. Kills->push_back(Stop);
  655. if (Start < Stop)
  656. I.insert(Start, Stop, Loc);
  657. }
  658. void UserValue::addDefsFromCopies(
  659. LiveInterval *LI, unsigned LocNo, bool WasIndirect,
  660. const SmallVectorImpl<SlotIndex> &Kills,
  661. SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
  662. MachineRegisterInfo &MRI, LiveIntervals &LIS) {
  663. if (Kills.empty())
  664. return;
  665. // Don't track copies from physregs, there are too many uses.
  666. if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
  667. return;
  668. // Collect all the (vreg, valno) pairs that are copies of LI.
  669. SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
  670. for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
  671. MachineInstr *MI = MO.getParent();
  672. // Copies of the full value.
  673. if (MO.getSubReg() || !MI->isCopy())
  674. continue;
  675. unsigned DstReg = MI->getOperand(0).getReg();
  676. // Don't follow copies to physregs. These are usually setting up call
  677. // arguments, and the argument registers are always call clobbered. We are
  678. // better off in the source register which could be a callee-saved register,
  679. // or it could be spilled.
  680. if (!TargetRegisterInfo::isVirtualRegister(DstReg))
  681. continue;
  682. // Is LocNo extended to reach this copy? If not, another def may be blocking
  683. // it, or we are looking at a wrong value of LI.
  684. SlotIndex Idx = LIS.getInstructionIndex(*MI);
  685. LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
  686. if (!I.valid() || I.value().locNo() != LocNo)
  687. continue;
  688. if (!LIS.hasInterval(DstReg))
  689. continue;
  690. LiveInterval *DstLI = &LIS.getInterval(DstReg);
  691. const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
  692. assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
  693. CopyValues.push_back(std::make_pair(DstLI, DstVNI));
  694. }
  695. if (CopyValues.empty())
  696. return;
  697. LLVM_DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI
  698. << '\n');
  699. // Try to add defs of the copied values for each kill point.
  700. for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
  701. SlotIndex Idx = Kills[i];
  702. for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
  703. LiveInterval *DstLI = CopyValues[j].first;
  704. const VNInfo *DstVNI = CopyValues[j].second;
  705. if (DstLI->getVNInfoAt(Idx) != DstVNI)
  706. continue;
  707. // Check that there isn't already a def at Idx
  708. LocMap::iterator I = locInts.find(Idx);
  709. if (I.valid() && I.start() <= Idx)
  710. continue;
  711. LLVM_DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
  712. << DstVNI->id << " in " << *DstLI << '\n');
  713. MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
  714. assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
  715. unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
  716. DbgValueLocation NewLoc(LocNo, WasIndirect);
  717. I.insert(Idx, Idx.getNextSlot(), NewLoc);
  718. NewDefs.push_back(std::make_pair(Idx, NewLoc));
  719. break;
  720. }
  721. }
  722. }
  723. void UserValue::computeIntervals(MachineRegisterInfo &MRI,
  724. const TargetRegisterInfo &TRI,
  725. LiveIntervals &LIS, LexicalScopes &LS) {
  726. SmallVector<std::pair<SlotIndex, DbgValueLocation>, 16> Defs;
  727. // Collect all defs to be extended (Skipping undefs).
  728. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
  729. if (!I.value().isUndef())
  730. Defs.push_back(std::make_pair(I.start(), I.value()));
  731. // Extend all defs, and possibly add new ones along the way.
  732. for (unsigned i = 0; i != Defs.size(); ++i) {
  733. SlotIndex Idx = Defs[i].first;
  734. DbgValueLocation Loc = Defs[i].second;
  735. const MachineOperand &LocMO = locations[Loc.locNo()];
  736. if (!LocMO.isReg()) {
  737. extendDef(Idx, Loc, nullptr, nullptr, nullptr, LIS);
  738. continue;
  739. }
  740. // Register locations are constrained to where the register value is live.
  741. if (TargetRegisterInfo::isVirtualRegister(LocMO.getReg())) {
  742. LiveInterval *LI = nullptr;
  743. const VNInfo *VNI = nullptr;
  744. if (LIS.hasInterval(LocMO.getReg())) {
  745. LI = &LIS.getInterval(LocMO.getReg());
  746. VNI = LI->getVNInfoAt(Idx);
  747. }
  748. SmallVector<SlotIndex, 16> Kills;
  749. extendDef(Idx, Loc, LI, VNI, &Kills, LIS);
  750. // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
  751. // if the original location for example is %vreg0:sub_hi, and we find a
  752. // full register copy in addDefsFromCopies (at the moment it only handles
  753. // full register copies), then we must add the sub1 sub-register index to
  754. // the new location. However, that is only possible if the new virtual
  755. // register is of the same regclass (or if there is an equivalent
  756. // sub-register in that regclass). For now, simply skip handling copies if
  757. // a sub-register is involved.
  758. if (LI && !LocMO.getSubReg())
  759. addDefsFromCopies(LI, Loc.locNo(), Loc.wasIndirect(), Kills, Defs, MRI,
  760. LIS);
  761. continue;
  762. }
  763. // For physregs, we only mark the start slot idx. DwarfDebug will see it
  764. // as if the DBG_VALUE is valid up until the end of the basic block, or
  765. // the next def of the physical register. So we do not need to extend the
  766. // range. It might actually happen that the DBG_VALUE is the last use of
  767. // the physical register (e.g. if this is an unused input argument to a
  768. // function).
  769. }
  770. // The computed intervals may extend beyond the range of the debug
  771. // location's lexical scope. In this case, splitting of an interval
  772. // can result in an interval outside of the scope being created,
  773. // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
  774. // this, trim the intervals to the lexical scope.
  775. LexicalScope *Scope = LS.findLexicalScope(dl);
  776. if (!Scope)
  777. return;
  778. SlotIndex PrevEnd;
  779. LocMap::iterator I = locInts.begin();
  780. // Iterate over the lexical scope ranges. Each time round the loop
  781. // we check the intervals for overlap with the end of the previous
  782. // range and the start of the next. The first range is handled as
  783. // a special case where there is no PrevEnd.
  784. for (const InsnRange &Range : Scope->getRanges()) {
  785. SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
  786. SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
  787. // At the start of each iteration I has been advanced so that
  788. // I.stop() >= PrevEnd. Check for overlap.
  789. if (PrevEnd && I.start() < PrevEnd) {
  790. SlotIndex IStop = I.stop();
  791. DbgValueLocation Loc = I.value();
  792. // Stop overlaps previous end - trim the end of the interval to
  793. // the scope range.
  794. I.setStopUnchecked(PrevEnd);
  795. ++I;
  796. // If the interval also overlaps the start of the "next" (i.e.
  797. // current) range create a new interval for the remainder (which
  798. // may be further trimmed).
  799. if (RStart < IStop)
  800. I.insert(RStart, IStop, Loc);
  801. }
  802. // Advance I so that I.stop() >= RStart, and check for overlap.
  803. I.advanceTo(RStart);
  804. if (!I.valid())
  805. return;
  806. if (I.start() < RStart) {
  807. // Interval start overlaps range - trim to the scope range.
  808. I.setStartUnchecked(RStart);
  809. // Remember that this interval was trimmed.
  810. trimmedDefs.insert(RStart);
  811. }
  812. // The end of a lexical scope range is the last instruction in the
  813. // range. To convert to an interval we need the index of the
  814. // instruction after it.
  815. REnd = REnd.getNextIndex();
  816. // Advance I to first interval outside current range.
  817. I.advanceTo(REnd);
  818. if (!I.valid())
  819. return;
  820. PrevEnd = REnd;
  821. }
  822. // Check for overlap with end of final range.
  823. if (PrevEnd && I.start() < PrevEnd)
  824. I.setStopUnchecked(PrevEnd);
  825. }
  826. void LDVImpl::computeIntervals() {
  827. LexicalScopes LS;
  828. LS.initialize(*MF);
  829. for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
  830. userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
  831. userValues[i]->mapVirtRegs(this);
  832. }
  833. }
  834. bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
  835. clear();
  836. MF = &mf;
  837. LIS = &pass.getAnalysis<LiveIntervals>();
  838. TRI = mf.getSubtarget().getRegisterInfo();
  839. LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
  840. << mf.getName() << " **********\n");
  841. bool Changed = collectDebugValues(mf);
  842. computeIntervals();
  843. LLVM_DEBUG(print(dbgs()));
  844. ModifiedMF = Changed;
  845. return Changed;
  846. }
  847. static void removeDebugValues(MachineFunction &mf) {
  848. for (MachineBasicBlock &MBB : mf) {
  849. for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
  850. if (!MBBI->isDebugValue()) {
  851. ++MBBI;
  852. continue;
  853. }
  854. MBBI = MBB.erase(MBBI);
  855. }
  856. }
  857. }
  858. bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
  859. if (!EnableLDV)
  860. return false;
  861. if (!mf.getFunction().getSubprogram()) {
  862. removeDebugValues(mf);
  863. return false;
  864. }
  865. if (!pImpl)
  866. pImpl = new LDVImpl(this);
  867. return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
  868. }
  869. void LiveDebugVariables::releaseMemory() {
  870. if (pImpl)
  871. static_cast<LDVImpl*>(pImpl)->clear();
  872. }
  873. LiveDebugVariables::~LiveDebugVariables() {
  874. if (pImpl)
  875. delete static_cast<LDVImpl*>(pImpl);
  876. }
  877. //===----------------------------------------------------------------------===//
  878. // Live Range Splitting
  879. //===----------------------------------------------------------------------===//
  880. bool
  881. UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
  882. LiveIntervals& LIS) {
  883. LLVM_DEBUG({
  884. dbgs() << "Splitting Loc" << OldLocNo << '\t';
  885. print(dbgs(), nullptr);
  886. });
  887. bool DidChange = false;
  888. LocMap::iterator LocMapI;
  889. LocMapI.setMap(locInts);
  890. for (unsigned i = 0; i != NewRegs.size(); ++i) {
  891. LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
  892. if (LI->empty())
  893. continue;
  894. // Don't allocate the new LocNo until it is needed.
  895. unsigned NewLocNo = UndefLocNo;
  896. // Iterate over the overlaps between locInts and LI.
  897. LocMapI.find(LI->beginIndex());
  898. if (!LocMapI.valid())
  899. continue;
  900. LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
  901. LiveInterval::iterator LIE = LI->end();
  902. while (LocMapI.valid() && LII != LIE) {
  903. // At this point, we know that LocMapI.stop() > LII->start.
  904. LII = LI->advanceTo(LII, LocMapI.start());
  905. if (LII == LIE)
  906. break;
  907. // Now LII->end > LocMapI.start(). Do we have an overlap?
  908. if (LocMapI.value().locNo() == OldLocNo && LII->start < LocMapI.stop()) {
  909. // Overlapping correct location. Allocate NewLocNo now.
  910. if (NewLocNo == UndefLocNo) {
  911. MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
  912. MO.setSubReg(locations[OldLocNo].getSubReg());
  913. NewLocNo = getLocationNo(MO);
  914. DidChange = true;
  915. }
  916. SlotIndex LStart = LocMapI.start();
  917. SlotIndex LStop = LocMapI.stop();
  918. DbgValueLocation OldLoc = LocMapI.value();
  919. // Trim LocMapI down to the LII overlap.
  920. if (LStart < LII->start)
  921. LocMapI.setStartUnchecked(LII->start);
  922. if (LStop > LII->end)
  923. LocMapI.setStopUnchecked(LII->end);
  924. // Change the value in the overlap. This may trigger coalescing.
  925. LocMapI.setValue(OldLoc.changeLocNo(NewLocNo));
  926. // Re-insert any removed OldLocNo ranges.
  927. if (LStart < LocMapI.start()) {
  928. LocMapI.insert(LStart, LocMapI.start(), OldLoc);
  929. ++LocMapI;
  930. assert(LocMapI.valid() && "Unexpected coalescing");
  931. }
  932. if (LStop > LocMapI.stop()) {
  933. ++LocMapI;
  934. LocMapI.insert(LII->end, LStop, OldLoc);
  935. --LocMapI;
  936. }
  937. }
  938. // Advance to the next overlap.
  939. if (LII->end < LocMapI.stop()) {
  940. if (++LII == LIE)
  941. break;
  942. LocMapI.advanceTo(LII->start);
  943. } else {
  944. ++LocMapI;
  945. if (!LocMapI.valid())
  946. break;
  947. LII = LI->advanceTo(LII, LocMapI.start());
  948. }
  949. }
  950. }
  951. // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
  952. locations.erase(locations.begin() + OldLocNo);
  953. LocMapI.goToBegin();
  954. while (LocMapI.valid()) {
  955. DbgValueLocation v = LocMapI.value();
  956. if (v.locNo() == OldLocNo) {
  957. LLVM_DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
  958. << LocMapI.stop() << ")\n");
  959. LocMapI.erase();
  960. } else {
  961. // Undef values always have location number UndefLocNo, so don't change
  962. // locNo in that case. See getLocationNo().
  963. if (!v.isUndef() && v.locNo() > OldLocNo)
  964. LocMapI.setValueUnchecked(v.changeLocNo(v.locNo() - 1));
  965. ++LocMapI;
  966. }
  967. }
  968. LLVM_DEBUG({
  969. dbgs() << "Split result: \t";
  970. print(dbgs(), nullptr);
  971. });
  972. return DidChange;
  973. }
  974. bool
  975. UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
  976. LiveIntervals &LIS) {
  977. bool DidChange = false;
  978. // Split locations referring to OldReg. Iterate backwards so splitLocation can
  979. // safely erase unused locations.
  980. for (unsigned i = locations.size(); i ; --i) {
  981. unsigned LocNo = i-1;
  982. const MachineOperand *Loc = &locations[LocNo];
  983. if (!Loc->isReg() || Loc->getReg() != OldReg)
  984. continue;
  985. DidChange |= splitLocation(LocNo, NewRegs, LIS);
  986. }
  987. return DidChange;
  988. }
  989. void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
  990. bool DidChange = false;
  991. for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
  992. DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
  993. if (!DidChange)
  994. return;
  995. // Map all of the new virtual registers.
  996. UserValue *UV = lookupVirtReg(OldReg);
  997. for (unsigned i = 0; i != NewRegs.size(); ++i)
  998. mapVirtReg(NewRegs[i], UV);
  999. }
  1000. void LiveDebugVariables::
  1001. splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
  1002. if (pImpl)
  1003. static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
  1004. }
  1005. void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
  1006. const TargetInstrInfo &TII,
  1007. const TargetRegisterInfo &TRI,
  1008. SpillOffsetMap &SpillOffsets) {
  1009. // Build a set of new locations with new numbers so we can coalesce our
  1010. // IntervalMap if two vreg intervals collapse to the same physical location.
  1011. // Use MapVector instead of SetVector because MapVector::insert returns the
  1012. // position of the previously or newly inserted element. The boolean value
  1013. // tracks if the location was produced by a spill.
  1014. // FIXME: This will be problematic if we ever support direct and indirect
  1015. // frame index locations, i.e. expressing both variables in memory and
  1016. // 'int x, *px = &x'. The "spilled" bit must become part of the location.
  1017. MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
  1018. SmallVector<unsigned, 4> LocNoMap(locations.size());
  1019. for (unsigned I = 0, E = locations.size(); I != E; ++I) {
  1020. bool Spilled = false;
  1021. unsigned SpillOffset = 0;
  1022. MachineOperand Loc = locations[I];
  1023. // Only virtual registers are rewritten.
  1024. if (Loc.isReg() && Loc.getReg() &&
  1025. TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
  1026. unsigned VirtReg = Loc.getReg();
  1027. if (VRM.isAssignedReg(VirtReg) &&
  1028. TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
  1029. // This can create a %noreg operand in rare cases when the sub-register
  1030. // index is no longer available. That means the user value is in a
  1031. // non-existent sub-register, and %noreg is exactly what we want.
  1032. Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
  1033. } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
  1034. // Retrieve the stack slot offset.
  1035. unsigned SpillSize;
  1036. const MachineRegisterInfo &MRI = MF.getRegInfo();
  1037. const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
  1038. bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
  1039. SpillOffset, MF);
  1040. // FIXME: Invalidate the location if the offset couldn't be calculated.
  1041. (void)Success;
  1042. Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
  1043. Spilled = true;
  1044. } else {
  1045. Loc.setReg(0);
  1046. Loc.setSubReg(0);
  1047. }
  1048. }
  1049. // Insert this location if it doesn't already exist and record a mapping
  1050. // from the old number to the new number.
  1051. auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
  1052. unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
  1053. LocNoMap[I] = NewLocNo;
  1054. }
  1055. // Rewrite the locations and record the stack slot offsets for spills.
  1056. locations.clear();
  1057. SpillOffsets.clear();
  1058. for (auto &Pair : NewLocations) {
  1059. bool Spilled;
  1060. unsigned SpillOffset;
  1061. std::tie(Spilled, SpillOffset) = Pair.second;
  1062. locations.push_back(Pair.first);
  1063. if (Spilled) {
  1064. unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
  1065. SpillOffsets[NewLocNo] = SpillOffset;
  1066. }
  1067. }
  1068. // Update the interval map, but only coalesce left, since intervals to the
  1069. // right use the old location numbers. This should merge two contiguous
  1070. // DBG_VALUE intervals with different vregs that were allocated to the same
  1071. // physical register.
  1072. for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
  1073. DbgValueLocation Loc = I.value();
  1074. // Undef values don't exist in locations (and thus not in LocNoMap either)
  1075. // so skip over them. See getLocationNo().
  1076. if (Loc.isUndef())
  1077. continue;
  1078. unsigned NewLocNo = LocNoMap[Loc.locNo()];
  1079. I.setValueUnchecked(Loc.changeLocNo(NewLocNo));
  1080. I.setStart(I.start());
  1081. }
  1082. }
  1083. /// Find an iterator for inserting a DBG_VALUE instruction.
  1084. static MachineBasicBlock::iterator
  1085. findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
  1086. LiveIntervals &LIS) {
  1087. SlotIndex Start = LIS.getMBBStartIdx(MBB);
  1088. Idx = Idx.getBaseIndex();
  1089. // Try to find an insert location by going backwards from Idx.
  1090. MachineInstr *MI;
  1091. while (!(MI = LIS.getInstructionFromIndex(Idx))) {
  1092. // We've reached the beginning of MBB.
  1093. if (Idx == Start) {
  1094. MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
  1095. return I;
  1096. }
  1097. Idx = Idx.getPrevIndex();
  1098. }
  1099. // Don't insert anything after the first terminator, though.
  1100. return MI->isTerminator() ? MBB->getFirstTerminator() :
  1101. std::next(MachineBasicBlock::iterator(MI));
  1102. }
  1103. /// Find an iterator for inserting the next DBG_VALUE instruction
  1104. /// (or end if no more insert locations found).
  1105. static MachineBasicBlock::iterator
  1106. findNextInsertLocation(MachineBasicBlock *MBB,
  1107. MachineBasicBlock::iterator I,
  1108. SlotIndex StopIdx, MachineOperand &LocMO,
  1109. LiveIntervals &LIS,
  1110. const TargetRegisterInfo &TRI) {
  1111. if (!LocMO.isReg())
  1112. return MBB->instr_end();
  1113. unsigned Reg = LocMO.getReg();
  1114. // Find the next instruction in the MBB that define the register Reg.
  1115. while (I != MBB->end() && !I->isTerminator()) {
  1116. if (!LIS.isNotInMIMap(*I) &&
  1117. SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
  1118. break;
  1119. if (I->definesRegister(Reg, &TRI))
  1120. // The insert location is directly after the instruction/bundle.
  1121. return std::next(I);
  1122. ++I;
  1123. }
  1124. return MBB->end();
  1125. }
  1126. void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
  1127. SlotIndex StopIdx, DbgValueLocation Loc,
  1128. bool Spilled, unsigned SpillOffset,
  1129. LiveIntervals &LIS, const TargetInstrInfo &TII,
  1130. const TargetRegisterInfo &TRI) {
  1131. SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
  1132. // Only search within the current MBB.
  1133. StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
  1134. MachineBasicBlock::iterator I = findInsertLocation(MBB, StartIdx, LIS);
  1135. // Undef values don't exist in locations so create new "noreg" register MOs
  1136. // for them. See getLocationNo().
  1137. MachineOperand MO = !Loc.isUndef() ?
  1138. locations[Loc.locNo()] :
  1139. MachineOperand::CreateReg(/* Reg */ 0, /* isDef */ false, /* isImp */ false,
  1140. /* isKill */ false, /* isDead */ false,
  1141. /* isUndef */ false, /* isEarlyClobber */ false,
  1142. /* SubReg */ 0, /* isDebug */ true);
  1143. ++NumInsertedDebugValues;
  1144. assert(cast<DILocalVariable>(Variable)
  1145. ->isValidLocationForIntrinsic(getDebugLoc()) &&
  1146. "Expected inlined-at fields to agree");
  1147. // If the location was spilled, the new DBG_VALUE will be indirect. If the
  1148. // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
  1149. // that the original virtual register was a pointer. Also, add the stack slot
  1150. // offset for the spilled register to the expression.
  1151. const DIExpression *Expr = Expression;
  1152. bool IsIndirect = Loc.wasIndirect();
  1153. if (Spilled) {
  1154. auto Deref = IsIndirect ? DIExpression::WithDeref : DIExpression::NoDeref;
  1155. Expr =
  1156. DIExpression::prepend(Expr, DIExpression::NoDeref, SpillOffset, Deref);
  1157. IsIndirect = true;
  1158. }
  1159. assert((!Spilled || MO.isFI()) && "a spilled location must be a frame index");
  1160. do {
  1161. BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
  1162. IsIndirect, MO, Variable, Expr);
  1163. // Continue and insert DBG_VALUES after every redefinition of register
  1164. // associated with the debug value within the range
  1165. I = findNextInsertLocation(MBB, I, StopIdx, MO, LIS, TRI);
  1166. } while (I != MBB->end());
  1167. }
  1168. void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
  1169. LiveIntervals &LIS,
  1170. const TargetInstrInfo &TII) {
  1171. MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
  1172. ++NumInsertedDebugLabels;
  1173. BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
  1174. .addMetadata(Label);
  1175. }
  1176. void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
  1177. const TargetInstrInfo &TII,
  1178. const TargetRegisterInfo &TRI,
  1179. const SpillOffsetMap &SpillOffsets) {
  1180. MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
  1181. for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
  1182. SlotIndex Start = I.start();
  1183. SlotIndex Stop = I.stop();
  1184. DbgValueLocation Loc = I.value();
  1185. auto SpillIt =
  1186. !Loc.isUndef() ? SpillOffsets.find(Loc.locNo()) : SpillOffsets.end();
  1187. bool Spilled = SpillIt != SpillOffsets.end();
  1188. unsigned SpillOffset = Spilled ? SpillIt->second : 0;
  1189. // If the interval start was trimmed to the lexical scope insert the
  1190. // DBG_VALUE at the previous index (otherwise it appears after the
  1191. // first instruction in the range).
  1192. if (trimmedDefs.count(Start))
  1193. Start = Start.getPrevIndex();
  1194. LLVM_DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << Loc.locNo());
  1195. MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
  1196. SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
  1197. LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
  1198. insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, SpillOffset, LIS, TII,
  1199. TRI);
  1200. // This interval may span multiple basic blocks.
  1201. // Insert a DBG_VALUE into each one.
  1202. while (Stop > MBBEnd) {
  1203. // Move to the next block.
  1204. Start = MBBEnd;
  1205. if (++MBB == MFEnd)
  1206. break;
  1207. MBBEnd = LIS.getMBBEndIdx(&*MBB);
  1208. LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
  1209. insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, SpillOffset, LIS, TII,
  1210. TRI);
  1211. }
  1212. LLVM_DEBUG(dbgs() << '\n');
  1213. if (MBB == MFEnd)
  1214. break;
  1215. ++I;
  1216. }
  1217. }
  1218. void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII) {
  1219. LLVM_DEBUG(dbgs() << "\t" << loc);
  1220. MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator();
  1221. LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
  1222. insertDebugLabel(&*MBB, loc, LIS, TII);
  1223. LLVM_DEBUG(dbgs() << '\n');
  1224. }
  1225. void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
  1226. LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
  1227. if (!MF)
  1228. return;
  1229. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  1230. SpillOffsetMap SpillOffsets;
  1231. for (auto &userValue : userValues) {
  1232. LLVM_DEBUG(userValue->print(dbgs(), TRI));
  1233. userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
  1234. userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets);
  1235. }
  1236. LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
  1237. for (auto &userLabel : userLabels) {
  1238. LLVM_DEBUG(userLabel->print(dbgs(), TRI));
  1239. userLabel->emitDebugLabel(*LIS, *TII);
  1240. }
  1241. EmitDone = true;
  1242. }
  1243. void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
  1244. if (pImpl)
  1245. static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
  1246. }
  1247. bool LiveDebugVariables::doInitialization(Module &M) {
  1248. return Pass::doInitialization(M);
  1249. }
  1250. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1251. LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
  1252. if (pImpl)
  1253. static_cast<LDVImpl*>(pImpl)->print(dbgs());
  1254. }
  1255. #endif