LiveDebugVariables.cpp 46 KB

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