LiveDebugVariables.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970
  1. //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the LiveDebugVariables analysis.
  10. //
  11. // Remove all DBG_VALUE instructions referencing virtual registers and replace
  12. // them with a data structure tracking where live user variables are kept - in a
  13. // virtual register or in a stack slot.
  14. //
  15. // Allow the data structure to be updated during register allocation when values
  16. // are moved between registers and stack slots. Finally emit new DBG_VALUE
  17. // instructions after register allocation is complete.
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #include "LiveDebugVariables.h"
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/IntervalMap.h"
  24. #include "llvm/ADT/MapVector.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/BinaryFormat/Dwarf.h"
  31. #include "llvm/CodeGen/LexicalScopes.h"
  32. #include "llvm/CodeGen/LiveInterval.h"
  33. #include "llvm/CodeGen/LiveIntervals.h"
  34. #include "llvm/CodeGen/MachineBasicBlock.h"
  35. #include "llvm/CodeGen/MachineDominators.h"
  36. #include "llvm/CodeGen/MachineFunction.h"
  37. #include "llvm/CodeGen/MachineInstr.h"
  38. #include "llvm/CodeGen/MachineInstrBuilder.h"
  39. #include "llvm/CodeGen/MachineOperand.h"
  40. #include "llvm/CodeGen/MachineRegisterInfo.h"
  41. #include "llvm/CodeGen/SlotIndexes.h"
  42. #include "llvm/CodeGen/TargetInstrInfo.h"
  43. #include "llvm/CodeGen/TargetOpcodes.h"
  44. #include "llvm/CodeGen/TargetRegisterInfo.h"
  45. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  46. #include "llvm/CodeGen/VirtRegMap.h"
  47. #include "llvm/Config/llvm-config.h"
  48. #include "llvm/IR/DebugInfoMetadata.h"
  49. #include "llvm/IR/DebugLoc.h"
  50. #include "llvm/IR/Function.h"
  51. #include "llvm/InitializePasses.h"
  52. #include "llvm/Pass.h"
  53. #include "llvm/Support/Casting.h"
  54. #include "llvm/Support/CommandLine.h"
  55. #include "llvm/Support/Debug.h"
  56. #include "llvm/Support/raw_ostream.h"
  57. #include <algorithm>
  58. #include <cassert>
  59. #include <iterator>
  60. #include <memory>
  61. #include <optional>
  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. namespace {
  88. /// Describes a debug variable value by location number and expression along
  89. /// with some flags about the original usage of the location.
  90. class DbgVariableValue {
  91. public:
  92. DbgVariableValue(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList,
  93. const DIExpression &Expr)
  94. : WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) {
  95. assert(!(WasIndirect && WasList) &&
  96. "DBG_VALUE_LISTs should not be indirect.");
  97. SmallVector<unsigned> LocNoVec;
  98. for (unsigned LocNo : NewLocs) {
  99. auto It = find(LocNoVec, LocNo);
  100. if (It == LocNoVec.end())
  101. LocNoVec.push_back(LocNo);
  102. else {
  103. // Loc duplicates an element in LocNos; replace references to Op
  104. // with references to the duplicating element.
  105. unsigned OpIdx = LocNoVec.size();
  106. unsigned DuplicatingIdx = std::distance(LocNoVec.begin(), It);
  107. Expression =
  108. DIExpression::replaceArg(Expression, OpIdx, DuplicatingIdx);
  109. }
  110. }
  111. // FIXME: Debug values referencing 64+ unique machine locations are rare and
  112. // currently unsupported for performance reasons. If we can verify that
  113. // performance is acceptable for such debug values, we can increase the
  114. // bit-width of LocNoCount to 14 to enable up to 16384 unique machine
  115. // locations. We will also need to verify that this does not cause issues
  116. // with LiveDebugVariables' use of IntervalMap.
  117. if (LocNoVec.size() < 64) {
  118. LocNoCount = LocNoVec.size();
  119. if (LocNoCount > 0) {
  120. LocNos = std::make_unique<unsigned[]>(LocNoCount);
  121. std::copy(LocNoVec.begin(), LocNoVec.end(), loc_nos_begin());
  122. }
  123. } else {
  124. LLVM_DEBUG(dbgs() << "Found debug value with 64+ unique machine "
  125. "locations, dropping...\n");
  126. LocNoCount = 1;
  127. // Turn this into an undef debug value list; right now, the simplest form
  128. // of this is an expression with one arg, and an undef debug operand.
  129. Expression =
  130. DIExpression::get(Expr.getContext(), {dwarf::DW_OP_LLVM_arg, 0});
  131. if (auto FragmentInfoOpt = Expr.getFragmentInfo())
  132. Expression = *DIExpression::createFragmentExpression(
  133. Expression, FragmentInfoOpt->OffsetInBits,
  134. FragmentInfoOpt->SizeInBits);
  135. LocNos = std::make_unique<unsigned[]>(LocNoCount);
  136. LocNos[0] = UndefLocNo;
  137. }
  138. }
  139. DbgVariableValue() : LocNoCount(0), WasIndirect(false), WasList(false) {}
  140. DbgVariableValue(const DbgVariableValue &Other)
  141. : LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()),
  142. WasList(Other.getWasList()), Expression(Other.getExpression()) {
  143. if (Other.getLocNoCount()) {
  144. LocNos.reset(new unsigned[Other.getLocNoCount()]);
  145. std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
  146. }
  147. }
  148. DbgVariableValue &operator=(const DbgVariableValue &Other) {
  149. if (this == &Other)
  150. return *this;
  151. if (Other.getLocNoCount()) {
  152. LocNos.reset(new unsigned[Other.getLocNoCount()]);
  153. std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
  154. } else {
  155. LocNos.release();
  156. }
  157. LocNoCount = Other.getLocNoCount();
  158. WasIndirect = Other.getWasIndirect();
  159. WasList = Other.getWasList();
  160. Expression = Other.getExpression();
  161. return *this;
  162. }
  163. const DIExpression *getExpression() const { return Expression; }
  164. uint8_t getLocNoCount() const { return LocNoCount; }
  165. bool containsLocNo(unsigned LocNo) const {
  166. return is_contained(loc_nos(), LocNo);
  167. }
  168. bool getWasIndirect() const { return WasIndirect; }
  169. bool getWasList() const { return WasList; }
  170. bool isUndef() const { return LocNoCount == 0 || containsLocNo(UndefLocNo); }
  171. DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const {
  172. SmallVector<unsigned, 4> NewLocNos;
  173. for (unsigned LocNo : loc_nos())
  174. NewLocNos.push_back(LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1
  175. : LocNo);
  176. return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
  177. }
  178. DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const {
  179. SmallVector<unsigned> NewLocNos;
  180. for (unsigned LocNo : loc_nos())
  181. // Undef values don't exist in locations (and thus not in LocNoMap
  182. // either) so skip over them. See getLocationNo().
  183. NewLocNos.push_back(LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]);
  184. return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
  185. }
  186. DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const {
  187. SmallVector<unsigned> NewLocNos;
  188. NewLocNos.assign(loc_nos_begin(), loc_nos_end());
  189. auto OldLocIt = find(NewLocNos, OldLocNo);
  190. assert(OldLocIt != NewLocNos.end() && "Old location must be present.");
  191. *OldLocIt = NewLocNo;
  192. return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
  193. }
  194. bool hasLocNoGreaterThan(unsigned LocNo) const {
  195. return any_of(loc_nos(),
  196. [LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; });
  197. }
  198. void printLocNos(llvm::raw_ostream &OS) const {
  199. for (const unsigned &Loc : loc_nos())
  200. OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc;
  201. }
  202. friend inline bool operator==(const DbgVariableValue &LHS,
  203. const DbgVariableValue &RHS) {
  204. if (std::tie(LHS.LocNoCount, LHS.WasIndirect, LHS.WasList,
  205. LHS.Expression) !=
  206. std::tie(RHS.LocNoCount, RHS.WasIndirect, RHS.WasList, RHS.Expression))
  207. return false;
  208. return std::equal(LHS.loc_nos_begin(), LHS.loc_nos_end(),
  209. RHS.loc_nos_begin());
  210. }
  211. friend inline bool operator!=(const DbgVariableValue &LHS,
  212. const DbgVariableValue &RHS) {
  213. return !(LHS == RHS);
  214. }
  215. unsigned *loc_nos_begin() { return LocNos.get(); }
  216. const unsigned *loc_nos_begin() const { return LocNos.get(); }
  217. unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; }
  218. const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; }
  219. ArrayRef<unsigned> loc_nos() const {
  220. return ArrayRef<unsigned>(LocNos.get(), LocNoCount);
  221. }
  222. private:
  223. // IntervalMap requires the value object to be very small, to the extent
  224. // that we do not have enough room for an std::vector. Using a C-style array
  225. // (with a unique_ptr wrapper for convenience) allows us to optimize for this
  226. // specific case by packing the array size into only 6 bits (it is highly
  227. // unlikely that any debug value will need 64+ locations).
  228. std::unique_ptr<unsigned[]> LocNos;
  229. uint8_t LocNoCount : 6;
  230. bool WasIndirect : 1;
  231. bool WasList : 1;
  232. const DIExpression *Expression = nullptr;
  233. };
  234. } // namespace
  235. /// Map of where a user value is live to that value.
  236. using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>;
  237. /// Map of stack slot offsets for spilled locations.
  238. /// Non-spilled locations are not added to the map.
  239. using SpillOffsetMap = DenseMap<unsigned, unsigned>;
  240. /// Cache to save the location where it can be used as the starting
  241. /// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug.
  242. /// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from
  243. /// repeatedly searching the same set of PHIs/Labels/Debug instructions
  244. /// if it is called many times for the same block.
  245. using BlockSkipInstsMap =
  246. DenseMap<MachineBasicBlock *, MachineBasicBlock::iterator>;
  247. namespace {
  248. class LDVImpl;
  249. /// A user value is a part of a debug info user variable.
  250. ///
  251. /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
  252. /// holds part of a user variable. The part is identified by a byte offset.
  253. ///
  254. /// UserValues are grouped into equivalence classes for easier searching. Two
  255. /// user values are related if they are held by the same virtual register. The
  256. /// equivalence class is the transitive closure of that relation.
  257. class UserValue {
  258. const DILocalVariable *Variable; ///< The debug info variable we are part of.
  259. /// The part of the variable we describe.
  260. const std::optional<DIExpression::FragmentInfo> Fragment;
  261. DebugLoc dl; ///< The debug location for the variable. This is
  262. ///< used by dwarf writer to find lexical scope.
  263. UserValue *leader; ///< Equivalence class leader.
  264. UserValue *next = nullptr; ///< Next value in equivalence class, or null.
  265. /// Numbered locations referenced by locmap.
  266. SmallVector<MachineOperand, 4> locations;
  267. /// Map of slot indices where this value is live.
  268. LocMap locInts;
  269. /// Set of interval start indexes that have been trimmed to the
  270. /// lexical scope.
  271. SmallSet<SlotIndex, 2> trimmedDefs;
  272. /// Insert a DBG_VALUE into MBB at Idx for DbgValue.
  273. void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
  274. SlotIndex StopIdx, DbgVariableValue DbgValue,
  275. ArrayRef<bool> LocSpills,
  276. ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS,
  277. const TargetInstrInfo &TII,
  278. const TargetRegisterInfo &TRI,
  279. BlockSkipInstsMap &BBSkipInstsMap);
  280. /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
  281. /// is live. Returns true if any changes were made.
  282. bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
  283. LiveIntervals &LIS);
  284. public:
  285. /// Create a new UserValue.
  286. UserValue(const DILocalVariable *var,
  287. std::optional<DIExpression::FragmentInfo> Fragment, DebugLoc L,
  288. LocMap::Allocator &alloc)
  289. : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this),
  290. locInts(alloc) {}
  291. /// Get the leader of this value's equivalence class.
  292. UserValue *getLeader() {
  293. UserValue *l = leader;
  294. while (l != l->leader)
  295. l = l->leader;
  296. return leader = l;
  297. }
  298. /// Return the next UserValue in the equivalence class.
  299. UserValue *getNext() const { return next; }
  300. /// Merge equivalence classes.
  301. static UserValue *merge(UserValue *L1, UserValue *L2) {
  302. L2 = L2->getLeader();
  303. if (!L1)
  304. return L2;
  305. L1 = L1->getLeader();
  306. if (L1 == L2)
  307. return L1;
  308. // Splice L2 before L1's members.
  309. UserValue *End = L2;
  310. while (End->next) {
  311. End->leader = L1;
  312. End = End->next;
  313. }
  314. End->leader = L1;
  315. End->next = L1->next;
  316. L1->next = L2;
  317. return L1;
  318. }
  319. /// Return the location number that matches Loc.
  320. ///
  321. /// For undef values we always return location number UndefLocNo without
  322. /// inserting anything in locations. Since locations is a vector and the
  323. /// location number is the position in the vector and UndefLocNo is ~0,
  324. /// we would need a very big vector to put the value at the right position.
  325. unsigned getLocationNo(const MachineOperand &LocMO) {
  326. if (LocMO.isReg()) {
  327. if (LocMO.getReg() == 0)
  328. return UndefLocNo;
  329. // For register locations we dont care about use/def and other flags.
  330. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  331. if (locations[i].isReg() &&
  332. locations[i].getReg() == LocMO.getReg() &&
  333. locations[i].getSubReg() == LocMO.getSubReg())
  334. return i;
  335. } else
  336. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  337. if (LocMO.isIdenticalTo(locations[i]))
  338. return i;
  339. locations.push_back(LocMO);
  340. // We are storing a MachineOperand outside a MachineInstr.
  341. locations.back().clearParent();
  342. // Don't store def operands.
  343. if (locations.back().isReg()) {
  344. if (locations.back().isDef())
  345. locations.back().setIsDead(false);
  346. locations.back().setIsUse();
  347. }
  348. return locations.size() - 1;
  349. }
  350. /// Remove (recycle) a location number. If \p LocNo still is used by the
  351. /// locInts nothing is done.
  352. void removeLocationIfUnused(unsigned LocNo) {
  353. // Bail out if LocNo still is used.
  354. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
  355. const DbgVariableValue &DbgValue = I.value();
  356. if (DbgValue.containsLocNo(LocNo))
  357. return;
  358. }
  359. // Remove the entry in the locations vector, and adjust all references to
  360. // location numbers above the removed entry.
  361. locations.erase(locations.begin() + LocNo);
  362. for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
  363. const DbgVariableValue &DbgValue = I.value();
  364. if (DbgValue.hasLocNoGreaterThan(LocNo))
  365. I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(LocNo));
  366. }
  367. }
  368. /// Ensure that all virtual register locations are mapped.
  369. void mapVirtRegs(LDVImpl *LDV);
  370. /// Add a definition point to this user value.
  371. void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect,
  372. bool IsList, const DIExpression &Expr) {
  373. SmallVector<unsigned> Locs;
  374. for (const MachineOperand &Op : LocMOs)
  375. Locs.push_back(getLocationNo(Op));
  376. DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr);
  377. // Add a singular (Idx,Idx) -> value mapping.
  378. LocMap::iterator I = locInts.find(Idx);
  379. if (!I.valid() || I.start() != Idx)
  380. I.insert(Idx, Idx.getNextSlot(), std::move(DbgValue));
  381. else
  382. // A later DBG_VALUE at the same SlotIndex overrides the old location.
  383. I.setValue(std::move(DbgValue));
  384. }
  385. /// Extend the current definition as far as possible down.
  386. ///
  387. /// Stop when meeting an existing def or when leaving the live
  388. /// range of VNI. End points where VNI is no longer live are added to Kills.
  389. ///
  390. /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
  391. /// data-flow analysis to propagate them beyond basic block boundaries.
  392. ///
  393. /// \param Idx Starting point for the definition.
  394. /// \param DbgValue value to propagate.
  395. /// \param LiveIntervalInfo For each location number key in this map,
  396. /// restricts liveness to where the LiveRange has the value equal to the\
  397. /// VNInfo.
  398. /// \param [out] Kills Append end points of VNI's live range to Kills.
  399. /// \param LIS Live intervals analysis.
  400. void
  401. extendDef(SlotIndex Idx, DbgVariableValue DbgValue,
  402. SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
  403. &LiveIntervalInfo,
  404. std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
  405. LiveIntervals &LIS);
  406. /// The value in LI may be copies to other registers. Determine if
  407. /// any of the copies are available at the kill points, and add defs if
  408. /// possible.
  409. ///
  410. /// \param DbgValue Location number of LI->reg, and DIExpression.
  411. /// \param LocIntervals Scan for copies of the value for each location in the
  412. /// corresponding LiveInterval->reg.
  413. /// \param KilledAt The point where the range of DbgValue could be extended.
  414. /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here.
  415. void addDefsFromCopies(
  416. DbgVariableValue DbgValue,
  417. SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
  418. SlotIndex KilledAt,
  419. SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
  420. MachineRegisterInfo &MRI, LiveIntervals &LIS);
  421. /// Compute the live intervals of all locations after collecting all their
  422. /// def points.
  423. void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
  424. LiveIntervals &LIS, LexicalScopes &LS);
  425. /// Replace OldReg ranges with NewRegs ranges where NewRegs is
  426. /// live. Returns true if any changes were made.
  427. bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
  428. LiveIntervals &LIS);
  429. /// Rewrite virtual register locations according to the provided virtual
  430. /// register map. Record the stack slot offsets for the locations that
  431. /// were spilled.
  432. void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
  433. const TargetInstrInfo &TII,
  434. const TargetRegisterInfo &TRI,
  435. SpillOffsetMap &SpillOffsets);
  436. /// Recreate DBG_VALUE instruction from data structures.
  437. void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
  438. const TargetInstrInfo &TII,
  439. const TargetRegisterInfo &TRI,
  440. const SpillOffsetMap &SpillOffsets,
  441. BlockSkipInstsMap &BBSkipInstsMap);
  442. /// Return DebugLoc of this UserValue.
  443. const DebugLoc &getDebugLoc() { return dl; }
  444. void print(raw_ostream &, const TargetRegisterInfo *);
  445. };
  446. /// A user label is a part of a debug info user label.
  447. class UserLabel {
  448. const DILabel *Label; ///< The debug info label we are part of.
  449. DebugLoc dl; ///< The debug location for the label. This is
  450. ///< used by dwarf writer to find lexical scope.
  451. SlotIndex loc; ///< Slot used by the debug label.
  452. /// Insert a DBG_LABEL into MBB at Idx.
  453. void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
  454. LiveIntervals &LIS, const TargetInstrInfo &TII,
  455. BlockSkipInstsMap &BBSkipInstsMap);
  456. public:
  457. /// Create a new UserLabel.
  458. UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
  459. : Label(label), dl(std::move(L)), loc(Idx) {}
  460. /// Does this UserLabel match the parameters?
  461. bool matches(const DILabel *L, const DILocation *IA,
  462. const SlotIndex Index) const {
  463. return Label == L && dl->getInlinedAt() == IA && loc == Index;
  464. }
  465. /// Recreate DBG_LABEL instruction from data structures.
  466. void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
  467. BlockSkipInstsMap &BBSkipInstsMap);
  468. /// Return DebugLoc of this UserLabel.
  469. const DebugLoc &getDebugLoc() { return dl; }
  470. void print(raw_ostream &, const TargetRegisterInfo *);
  471. };
  472. /// Implementation of the LiveDebugVariables pass.
  473. class LDVImpl {
  474. LiveDebugVariables &pass;
  475. LocMap::Allocator allocator;
  476. MachineFunction *MF = nullptr;
  477. LiveIntervals *LIS;
  478. const TargetRegisterInfo *TRI;
  479. /// Position and VReg of a PHI instruction during register allocation.
  480. struct PHIValPos {
  481. SlotIndex SI; /// Slot where this PHI occurs.
  482. Register Reg; /// VReg this PHI occurs in.
  483. unsigned SubReg; /// Qualifiying subregister for Reg.
  484. };
  485. /// Map from debug instruction number to PHI position during allocation.
  486. std::map<unsigned, PHIValPos> PHIValToPos;
  487. /// Index of, for each VReg, which debug instruction numbers and corresponding
  488. /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs,
  489. /// at different positions.
  490. DenseMap<Register, std::vector<unsigned>> RegToPHIIdx;
  491. /// Record for any debug instructions unlinked from their blocks during
  492. /// regalloc. Stores the instr and it's location, so that they can be
  493. /// re-inserted after regalloc is over.
  494. struct InstrPos {
  495. MachineInstr *MI; ///< Debug instruction, unlinked from it's block.
  496. SlotIndex Idx; ///< Slot position where MI should be re-inserted.
  497. MachineBasicBlock *MBB; ///< Block that MI was in.
  498. };
  499. /// Collection of stored debug instructions, preserved until after regalloc.
  500. SmallVector<InstrPos, 32> StashedDebugInstrs;
  501. /// Whether emitDebugValues is called.
  502. bool EmitDone = false;
  503. /// Whether the machine function is modified during the pass.
  504. bool ModifiedMF = false;
  505. /// All allocated UserValue instances.
  506. SmallVector<std::unique_ptr<UserValue>, 8> userValues;
  507. /// All allocated UserLabel instances.
  508. SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
  509. /// Map virtual register to eq class leader.
  510. using VRMap = DenseMap<unsigned, UserValue *>;
  511. VRMap virtRegToEqClass;
  512. /// Map to find existing UserValue instances.
  513. using UVMap = DenseMap<DebugVariable, UserValue *>;
  514. UVMap userVarMap;
  515. /// Find or create a UserValue.
  516. UserValue *getUserValue(const DILocalVariable *Var,
  517. std::optional<DIExpression::FragmentInfo> Fragment,
  518. const DebugLoc &DL);
  519. /// Find the EC leader for VirtReg or null.
  520. UserValue *lookupVirtReg(Register VirtReg);
  521. /// Add DBG_VALUE instruction to our maps.
  522. ///
  523. /// \param MI DBG_VALUE instruction
  524. /// \param Idx Last valid SLotIndex before instruction.
  525. ///
  526. /// \returns True if the DBG_VALUE instruction should be deleted.
  527. bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
  528. /// Track variable location debug instructions while using the instruction
  529. /// referencing implementation. Such debug instructions do not need to be
  530. /// updated during regalloc because they identify instructions rather than
  531. /// register locations. However, they needs to be removed from the
  532. /// MachineFunction during regalloc, then re-inserted later, to avoid
  533. /// disrupting the allocator.
  534. ///
  535. /// \param MI Any DBG_VALUE / DBG_INSTR_REF / DBG_PHI instruction
  536. /// \param Idx Last valid SlotIndex before instruction
  537. ///
  538. /// \returns Iterator to continue processing from after unlinking.
  539. MachineBasicBlock::iterator handleDebugInstr(MachineInstr &MI, SlotIndex Idx);
  540. /// Add DBG_LABEL instruction to UserLabel.
  541. ///
  542. /// \param MI DBG_LABEL instruction
  543. /// \param Idx Last valid SlotIndex before instruction.
  544. ///
  545. /// \returns True if the DBG_LABEL instruction should be deleted.
  546. bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
  547. /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
  548. /// for each instruction.
  549. ///
  550. /// \param mf MachineFunction to be scanned.
  551. /// \param InstrRef Whether to operate in instruction referencing mode. If
  552. /// true, most of LiveDebugVariables doesn't run.
  553. ///
  554. /// \returns True if any debug values were found.
  555. bool collectDebugValues(MachineFunction &mf, bool InstrRef);
  556. /// Compute the live intervals of all user values after collecting all
  557. /// their def points.
  558. void computeIntervals();
  559. public:
  560. LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
  561. bool runOnMachineFunction(MachineFunction &mf, bool InstrRef);
  562. /// Release all memory.
  563. void clear() {
  564. MF = nullptr;
  565. PHIValToPos.clear();
  566. RegToPHIIdx.clear();
  567. StashedDebugInstrs.clear();
  568. userValues.clear();
  569. userLabels.clear();
  570. virtRegToEqClass.clear();
  571. userVarMap.clear();
  572. // Make sure we call emitDebugValues if the machine function was modified.
  573. assert((!ModifiedMF || EmitDone) &&
  574. "Dbg values are not emitted in LDV");
  575. EmitDone = false;
  576. ModifiedMF = false;
  577. }
  578. /// Map virtual register to an equivalence class.
  579. void mapVirtReg(Register VirtReg, UserValue *EC);
  580. /// Replace any PHI referring to OldReg with its corresponding NewReg, if
  581. /// present.
  582. void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs);
  583. /// Replace all references to OldReg with NewRegs.
  584. void splitRegister(Register OldReg, ArrayRef<Register> NewRegs);
  585. /// Recreate DBG_VALUE instruction from data structures.
  586. void emitDebugValues(VirtRegMap *VRM);
  587. void print(raw_ostream&);
  588. };
  589. } // end anonymous namespace
  590. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  591. static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
  592. const LLVMContext &Ctx) {
  593. if (!DL)
  594. return;
  595. auto *Scope = cast<DIScope>(DL.getScope());
  596. // Omit the directory, because it's likely to be long and uninteresting.
  597. CommentOS << Scope->getFilename();
  598. CommentOS << ':' << DL.getLine();
  599. if (DL.getCol() != 0)
  600. CommentOS << ':' << DL.getCol();
  601. DebugLoc InlinedAtDL = DL.getInlinedAt();
  602. if (!InlinedAtDL)
  603. return;
  604. CommentOS << " @[ ";
  605. printDebugLoc(InlinedAtDL, CommentOS, Ctx);
  606. CommentOS << " ]";
  607. }
  608. static void printExtendedName(raw_ostream &OS, const DINode *Node,
  609. const DILocation *DL) {
  610. const LLVMContext &Ctx = Node->getContext();
  611. StringRef Res;
  612. unsigned Line = 0;
  613. if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
  614. Res = V->getName();
  615. Line = V->getLine();
  616. } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
  617. Res = L->getName();
  618. Line = L->getLine();
  619. }
  620. if (!Res.empty())
  621. OS << Res << "," << Line;
  622. auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
  623. if (InlinedAt) {
  624. if (DebugLoc InlinedAtDL = InlinedAt) {
  625. OS << " @[";
  626. printDebugLoc(InlinedAtDL, OS, Ctx);
  627. OS << "]";
  628. }
  629. }
  630. }
  631. void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
  632. OS << "!\"";
  633. printExtendedName(OS, Variable, dl);
  634. OS << "\"\t";
  635. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
  636. OS << " [" << I.start() << ';' << I.stop() << "):";
  637. if (I.value().isUndef())
  638. OS << " undef";
  639. else {
  640. I.value().printLocNos(OS);
  641. if (I.value().getWasIndirect())
  642. OS << " ind";
  643. else if (I.value().getWasList())
  644. OS << " list";
  645. }
  646. }
  647. for (unsigned i = 0, e = locations.size(); i != e; ++i) {
  648. OS << " Loc" << i << '=';
  649. locations[i].print(OS, TRI);
  650. }
  651. OS << '\n';
  652. }
  653. void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
  654. OS << "!\"";
  655. printExtendedName(OS, Label, dl);
  656. OS << "\"\t";
  657. OS << loc;
  658. OS << '\n';
  659. }
  660. void LDVImpl::print(raw_ostream &OS) {
  661. OS << "********** DEBUG VARIABLES **********\n";
  662. for (auto &userValue : userValues)
  663. userValue->print(OS, TRI);
  664. OS << "********** DEBUG LABELS **********\n";
  665. for (auto &userLabel : userLabels)
  666. userLabel->print(OS, TRI);
  667. }
  668. #endif
  669. void UserValue::mapVirtRegs(LDVImpl *LDV) {
  670. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  671. if (locations[i].isReg() && locations[i].getReg().isVirtual())
  672. LDV->mapVirtReg(locations[i].getReg(), this);
  673. }
  674. UserValue *
  675. LDVImpl::getUserValue(const DILocalVariable *Var,
  676. std::optional<DIExpression::FragmentInfo> Fragment,
  677. const DebugLoc &DL) {
  678. // FIXME: Handle partially overlapping fragments. See
  679. // https://reviews.llvm.org/D70121#1849741.
  680. DebugVariable ID(Var, Fragment, DL->getInlinedAt());
  681. UserValue *&UV = userVarMap[ID];
  682. if (!UV) {
  683. userValues.push_back(
  684. std::make_unique<UserValue>(Var, Fragment, DL, allocator));
  685. UV = userValues.back().get();
  686. }
  687. return UV;
  688. }
  689. void LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) {
  690. assert(VirtReg.isVirtual() && "Only map VirtRegs");
  691. UserValue *&Leader = virtRegToEqClass[VirtReg];
  692. Leader = UserValue::merge(Leader, EC);
  693. }
  694. UserValue *LDVImpl::lookupVirtReg(Register VirtReg) {
  695. if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
  696. return UV->getLeader();
  697. return nullptr;
  698. }
  699. bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
  700. // DBG_VALUE loc, offset, variable, expr
  701. // DBG_VALUE_LIST variable, expr, locs...
  702. if (!MI.isDebugValue()) {
  703. LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI);
  704. return false;
  705. }
  706. if (!MI.getDebugVariableOp().isMetadata()) {
  707. LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: "
  708. << MI);
  709. return false;
  710. }
  711. if (MI.isNonListDebugValue() &&
  712. (MI.getNumOperands() != 4 ||
  713. !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) {
  714. LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI);
  715. return false;
  716. }
  717. // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
  718. // register that hasn't been defined yet. If we do not remove those here, then
  719. // the re-insertion of the DBG_VALUE instruction after register allocation
  720. // will be incorrect.
  721. bool Discard = false;
  722. for (const MachineOperand &Op : MI.debug_operands()) {
  723. if (Op.isReg() && Op.getReg().isVirtual()) {
  724. const Register Reg = Op.getReg();
  725. if (!LIS->hasInterval(Reg)) {
  726. // The DBG_VALUE is described by a virtual register that does not have a
  727. // live interval. Discard the DBG_VALUE.
  728. Discard = true;
  729. LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
  730. << " " << MI);
  731. } else {
  732. // The DBG_VALUE is only valid if either Reg is live out from Idx, or
  733. // Reg is defined dead at Idx (where Idx is the slot index for the
  734. // instruction preceding the DBG_VALUE).
  735. const LiveInterval &LI = LIS->getInterval(Reg);
  736. LiveQueryResult LRQ = LI.Query(Idx);
  737. if (!LRQ.valueOutOrDead()) {
  738. // We have found a DBG_VALUE with the value in a virtual register that
  739. // is not live. Discard the DBG_VALUE.
  740. Discard = true;
  741. LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
  742. << " " << MI);
  743. }
  744. }
  745. }
  746. }
  747. // Get or create the UserValue for (variable,offset) here.
  748. bool IsIndirect = MI.isDebugOffsetImm();
  749. if (IsIndirect)
  750. assert(MI.getDebugOffset().getImm() == 0 &&
  751. "DBG_VALUE with nonzero offset");
  752. bool IsList = MI.isDebugValueList();
  753. const DILocalVariable *Var = MI.getDebugVariable();
  754. const DIExpression *Expr = MI.getDebugExpression();
  755. UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc());
  756. if (!Discard)
  757. UV->addDef(Idx,
  758. ArrayRef<MachineOperand>(MI.debug_operands().begin(),
  759. MI.debug_operands().end()),
  760. IsIndirect, IsList, *Expr);
  761. else {
  762. MachineOperand MO = MachineOperand::CreateReg(0U, false);
  763. MO.setIsDebug();
  764. // We should still pass a list the same size as MI.debug_operands() even if
  765. // all MOs are undef, so that DbgVariableValue can correctly adjust the
  766. // expression while removing the duplicated undefs.
  767. SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO);
  768. UV->addDef(Idx, UndefMOs, false, IsList, *Expr);
  769. }
  770. return true;
  771. }
  772. MachineBasicBlock::iterator LDVImpl::handleDebugInstr(MachineInstr &MI,
  773. SlotIndex Idx) {
  774. assert(MI.isDebugValueLike() || MI.isDebugPHI());
  775. // In instruction referencing mode, there should be no DBG_VALUE instructions
  776. // that refer to virtual registers. They might still refer to constants.
  777. if (MI.isDebugValueLike())
  778. assert(none_of(MI.debug_operands(),
  779. [](const MachineOperand &MO) {
  780. return MO.isReg() && MO.getReg().isVirtual();
  781. }) &&
  782. "MIs should not refer to Virtual Registers in InstrRef mode.");
  783. // Unlink the instruction, store it in the debug instructions collection.
  784. auto NextInst = std::next(MI.getIterator());
  785. auto *MBB = MI.getParent();
  786. MI.removeFromParent();
  787. StashedDebugInstrs.push_back({&MI, Idx, MBB});
  788. return NextInst;
  789. }
  790. bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) {
  791. // DBG_LABEL label
  792. if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
  793. LLVM_DEBUG(dbgs() << "Can't handle " << MI);
  794. return false;
  795. }
  796. // Get or create the UserLabel for label here.
  797. const DILabel *Label = MI.getDebugLabel();
  798. const DebugLoc &DL = MI.getDebugLoc();
  799. bool Found = false;
  800. for (auto const &L : userLabels) {
  801. if (L->matches(Label, DL->getInlinedAt(), Idx)) {
  802. Found = true;
  803. break;
  804. }
  805. }
  806. if (!Found)
  807. userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx));
  808. return true;
  809. }
  810. bool LDVImpl::collectDebugValues(MachineFunction &mf, bool InstrRef) {
  811. bool Changed = false;
  812. for (MachineBasicBlock &MBB : mf) {
  813. for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
  814. MBBI != MBBE;) {
  815. // Use the first debug instruction in the sequence to get a SlotIndex
  816. // for following consecutive debug instructions.
  817. if (!MBBI->isDebugOrPseudoInstr()) {
  818. ++MBBI;
  819. continue;
  820. }
  821. // Debug instructions has no slot index. Use the previous
  822. // non-debug instruction's SlotIndex as its SlotIndex.
  823. SlotIndex Idx =
  824. MBBI == MBB.begin()
  825. ? LIS->getMBBStartIdx(&MBB)
  826. : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
  827. // Handle consecutive debug instructions with the same slot index.
  828. do {
  829. // In instruction referencing mode, pass each instr to handleDebugInstr
  830. // to be unlinked. Ignore DBG_VALUE_LISTs -- they refer to vregs, and
  831. // need to go through the normal live interval splitting process.
  832. if (InstrRef && (MBBI->isNonListDebugValue() || MBBI->isDebugPHI() ||
  833. MBBI->isDebugRef())) {
  834. MBBI = handleDebugInstr(*MBBI, Idx);
  835. Changed = true;
  836. // In normal debug mode, use the dedicated DBG_VALUE / DBG_LABEL handler
  837. // to track things through register allocation, and erase the instr.
  838. } else if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
  839. (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
  840. MBBI = MBB.erase(MBBI);
  841. Changed = true;
  842. } else
  843. ++MBBI;
  844. } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr());
  845. }
  846. }
  847. return Changed;
  848. }
  849. void UserValue::extendDef(
  850. SlotIndex Idx, DbgVariableValue DbgValue,
  851. SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
  852. &LiveIntervalInfo,
  853. std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
  854. LiveIntervals &LIS) {
  855. SlotIndex Start = Idx;
  856. MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
  857. SlotIndex Stop = LIS.getMBBEndIdx(MBB);
  858. LocMap::iterator I = locInts.find(Start);
  859. // Limit to the intersection of the VNIs' live ranges.
  860. for (auto &LII : LiveIntervalInfo) {
  861. LiveRange *LR = LII.second.first;
  862. assert(LR && LII.second.second && "Missing range info for Idx.");
  863. LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
  864. assert(Segment && Segment->valno == LII.second.second &&
  865. "Invalid VNInfo for Idx given?");
  866. if (Segment->end < Stop) {
  867. Stop = Segment->end;
  868. Kills = {Stop, {LII.first}};
  869. } else if (Segment->end == Stop && Kills) {
  870. // If multiple locations end at the same place, track all of them in
  871. // Kills.
  872. Kills->second.push_back(LII.first);
  873. }
  874. }
  875. // There could already be a short def at Start.
  876. if (I.valid() && I.start() <= Start) {
  877. // Stop when meeting a different location or an already extended interval.
  878. Start = Start.getNextSlot();
  879. if (I.value() != DbgValue || I.stop() != Start) {
  880. // Clear `Kills`, as we have a new def available.
  881. Kills = std::nullopt;
  882. return;
  883. }
  884. // This is a one-slot placeholder. Just skip it.
  885. ++I;
  886. }
  887. // Limited by the next def.
  888. if (I.valid() && I.start() < Stop) {
  889. Stop = I.start();
  890. // Clear `Kills`, as we have a new def available.
  891. Kills = std::nullopt;
  892. }
  893. if (Start < Stop) {
  894. DbgVariableValue ExtDbgValue(DbgValue);
  895. I.insert(Start, Stop, std::move(ExtDbgValue));
  896. }
  897. }
  898. void UserValue::addDefsFromCopies(
  899. DbgVariableValue DbgValue,
  900. SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
  901. SlotIndex KilledAt,
  902. SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
  903. MachineRegisterInfo &MRI, LiveIntervals &LIS) {
  904. // Don't track copies from physregs, there are too many uses.
  905. if (any_of(LocIntervals,
  906. [](auto LocI) { return !LocI.second->reg().isVirtual(); }))
  907. return;
  908. // Collect all the (vreg, valno) pairs that are copies of LI.
  909. SmallDenseMap<unsigned,
  910. SmallVector<std::pair<LiveInterval *, const VNInfo *>, 4>>
  911. CopyValues;
  912. for (auto &LocInterval : LocIntervals) {
  913. unsigned LocNo = LocInterval.first;
  914. LiveInterval *LI = LocInterval.second;
  915. for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) {
  916. MachineInstr *MI = MO.getParent();
  917. // Copies of the full value.
  918. if (MO.getSubReg() || !MI->isCopy())
  919. continue;
  920. Register DstReg = MI->getOperand(0).getReg();
  921. // Don't follow copies to physregs. These are usually setting up call
  922. // arguments, and the argument registers are always call clobbered. We are
  923. // better off in the source register which could be a callee-saved
  924. // register, or it could be spilled.
  925. if (!DstReg.isVirtual())
  926. continue;
  927. // Is the value extended to reach this copy? If not, another def may be
  928. // blocking it, or we are looking at a wrong value of LI.
  929. SlotIndex Idx = LIS.getInstructionIndex(*MI);
  930. LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
  931. if (!I.valid() || I.value() != DbgValue)
  932. continue;
  933. if (!LIS.hasInterval(DstReg))
  934. continue;
  935. LiveInterval *DstLI = &LIS.getInterval(DstReg);
  936. const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
  937. assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
  938. CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI));
  939. }
  940. }
  941. if (CopyValues.empty())
  942. return;
  943. #if !defined(NDEBUG)
  944. for (auto &LocInterval : LocIntervals)
  945. LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size()
  946. << " copies of " << *LocInterval.second << '\n');
  947. #endif
  948. // Try to add defs of the copied values for the kill point. Check that there
  949. // isn't already a def at Idx.
  950. LocMap::iterator I = locInts.find(KilledAt);
  951. if (I.valid() && I.start() <= KilledAt)
  952. return;
  953. DbgVariableValue NewValue(DbgValue);
  954. for (auto &LocInterval : LocIntervals) {
  955. unsigned LocNo = LocInterval.first;
  956. bool FoundCopy = false;
  957. for (auto &LIAndVNI : CopyValues[LocNo]) {
  958. LiveInterval *DstLI = LIAndVNI.first;
  959. const VNInfo *DstVNI = LIAndVNI.second;
  960. if (DstLI->getVNInfoAt(KilledAt) != DstVNI)
  961. continue;
  962. LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #"
  963. << DstVNI->id << " in " << *DstLI << '\n');
  964. MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
  965. assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
  966. unsigned NewLocNo = getLocationNo(CopyMI->getOperand(0));
  967. NewValue = NewValue.changeLocNo(LocNo, NewLocNo);
  968. FoundCopy = true;
  969. break;
  970. }
  971. // If there are any killed locations we can't find a copy for, we can't
  972. // extend the variable value.
  973. if (!FoundCopy)
  974. return;
  975. }
  976. I.insert(KilledAt, KilledAt.getNextSlot(), NewValue);
  977. NewDefs.push_back(std::make_pair(KilledAt, NewValue));
  978. }
  979. void UserValue::computeIntervals(MachineRegisterInfo &MRI,
  980. const TargetRegisterInfo &TRI,
  981. LiveIntervals &LIS, LexicalScopes &LS) {
  982. SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs;
  983. // Collect all defs to be extended (Skipping undefs).
  984. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
  985. if (!I.value().isUndef())
  986. Defs.push_back(std::make_pair(I.start(), I.value()));
  987. // Extend all defs, and possibly add new ones along the way.
  988. for (unsigned i = 0; i != Defs.size(); ++i) {
  989. SlotIndex Idx = Defs[i].first;
  990. DbgVariableValue DbgValue = Defs[i].second;
  991. SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs;
  992. SmallVector<const VNInfo *, 4> VNIs;
  993. bool ShouldExtendDef = false;
  994. for (unsigned LocNo : DbgValue.loc_nos()) {
  995. const MachineOperand &LocMO = locations[LocNo];
  996. if (!LocMO.isReg() || !LocMO.getReg().isVirtual()) {
  997. ShouldExtendDef |= !LocMO.isReg();
  998. continue;
  999. }
  1000. ShouldExtendDef = true;
  1001. LiveInterval *LI = nullptr;
  1002. const VNInfo *VNI = nullptr;
  1003. if (LIS.hasInterval(LocMO.getReg())) {
  1004. LI = &LIS.getInterval(LocMO.getReg());
  1005. VNI = LI->getVNInfoAt(Idx);
  1006. }
  1007. if (LI && VNI)
  1008. LIs[LocNo] = {LI, VNI};
  1009. }
  1010. if (ShouldExtendDef) {
  1011. std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills;
  1012. extendDef(Idx, DbgValue, LIs, Kills, LIS);
  1013. if (Kills) {
  1014. SmallVector<std::pair<unsigned, LiveInterval *>, 2> KilledLocIntervals;
  1015. bool AnySubreg = false;
  1016. for (unsigned LocNo : Kills->second) {
  1017. const MachineOperand &LocMO = this->locations[LocNo];
  1018. if (LocMO.getSubReg()) {
  1019. AnySubreg = true;
  1020. break;
  1021. }
  1022. LiveInterval *LI = &LIS.getInterval(LocMO.getReg());
  1023. KilledLocIntervals.push_back({LocNo, LI});
  1024. }
  1025. // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
  1026. // if the original location for example is %vreg0:sub_hi, and we find a
  1027. // full register copy in addDefsFromCopies (at the moment it only
  1028. // handles full register copies), then we must add the sub1 sub-register
  1029. // index to the new location. However, that is only possible if the new
  1030. // virtual register is of the same regclass (or if there is an
  1031. // equivalent sub-register in that regclass). For now, simply skip
  1032. // handling copies if a sub-register is involved.
  1033. if (!AnySubreg)
  1034. addDefsFromCopies(DbgValue, KilledLocIntervals, Kills->first, Defs,
  1035. MRI, LIS);
  1036. }
  1037. }
  1038. // For physregs, we only mark the start slot idx. DwarfDebug will see it
  1039. // as if the DBG_VALUE is valid up until the end of the basic block, or
  1040. // the next def of the physical register. So we do not need to extend the
  1041. // range. It might actually happen that the DBG_VALUE is the last use of
  1042. // the physical register (e.g. if this is an unused input argument to a
  1043. // function).
  1044. }
  1045. // The computed intervals may extend beyond the range of the debug
  1046. // location's lexical scope. In this case, splitting of an interval
  1047. // can result in an interval outside of the scope being created,
  1048. // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
  1049. // this, trim the intervals to the lexical scope in the case of inlined
  1050. // variables, since heavy inlining may cause production of dramatically big
  1051. // number of DBG_VALUEs to be generated.
  1052. if (!dl.getInlinedAt())
  1053. return;
  1054. LexicalScope *Scope = LS.findLexicalScope(dl);
  1055. if (!Scope)
  1056. return;
  1057. SlotIndex PrevEnd;
  1058. LocMap::iterator I = locInts.begin();
  1059. // Iterate over the lexical scope ranges. Each time round the loop
  1060. // we check the intervals for overlap with the end of the previous
  1061. // range and the start of the next. The first range is handled as
  1062. // a special case where there is no PrevEnd.
  1063. for (const InsnRange &Range : Scope->getRanges()) {
  1064. SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
  1065. SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
  1066. // Variable locations at the first instruction of a block should be
  1067. // based on the block's SlotIndex, not the first instruction's index.
  1068. if (Range.first == Range.first->getParent()->begin())
  1069. RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first);
  1070. // At the start of each iteration I has been advanced so that
  1071. // I.stop() >= PrevEnd. Check for overlap.
  1072. if (PrevEnd && I.start() < PrevEnd) {
  1073. SlotIndex IStop = I.stop();
  1074. DbgVariableValue DbgValue = I.value();
  1075. // Stop overlaps previous end - trim the end of the interval to
  1076. // the scope range.
  1077. I.setStopUnchecked(PrevEnd);
  1078. ++I;
  1079. // If the interval also overlaps the start of the "next" (i.e.
  1080. // current) range create a new interval for the remainder (which
  1081. // may be further trimmed).
  1082. if (RStart < IStop)
  1083. I.insert(RStart, IStop, DbgValue);
  1084. }
  1085. // Advance I so that I.stop() >= RStart, and check for overlap.
  1086. I.advanceTo(RStart);
  1087. if (!I.valid())
  1088. return;
  1089. if (I.start() < RStart) {
  1090. // Interval start overlaps range - trim to the scope range.
  1091. I.setStartUnchecked(RStart);
  1092. // Remember that this interval was trimmed.
  1093. trimmedDefs.insert(RStart);
  1094. }
  1095. // The end of a lexical scope range is the last instruction in the
  1096. // range. To convert to an interval we need the index of the
  1097. // instruction after it.
  1098. REnd = REnd.getNextIndex();
  1099. // Advance I to first interval outside current range.
  1100. I.advanceTo(REnd);
  1101. if (!I.valid())
  1102. return;
  1103. PrevEnd = REnd;
  1104. }
  1105. // Check for overlap with end of final range.
  1106. if (PrevEnd && I.start() < PrevEnd)
  1107. I.setStopUnchecked(PrevEnd);
  1108. }
  1109. void LDVImpl::computeIntervals() {
  1110. LexicalScopes LS;
  1111. LS.initialize(*MF);
  1112. for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
  1113. userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
  1114. userValues[i]->mapVirtRegs(this);
  1115. }
  1116. }
  1117. bool LDVImpl::runOnMachineFunction(MachineFunction &mf, bool InstrRef) {
  1118. clear();
  1119. MF = &mf;
  1120. LIS = &pass.getAnalysis<LiveIntervals>();
  1121. TRI = mf.getSubtarget().getRegisterInfo();
  1122. LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
  1123. << mf.getName() << " **********\n");
  1124. bool Changed = collectDebugValues(mf, InstrRef);
  1125. computeIntervals();
  1126. LLVM_DEBUG(print(dbgs()));
  1127. // Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive
  1128. // VRegs too, for when we're notified of a range split.
  1129. SlotIndexes *Slots = LIS->getSlotIndexes();
  1130. for (const auto &PHIIt : MF->DebugPHIPositions) {
  1131. const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second;
  1132. MachineBasicBlock *MBB = Position.MBB;
  1133. Register Reg = Position.Reg;
  1134. unsigned SubReg = Position.SubReg;
  1135. SlotIndex SI = Slots->getMBBStartIdx(MBB);
  1136. PHIValPos VP = {SI, Reg, SubReg};
  1137. PHIValToPos.insert(std::make_pair(PHIIt.first, VP));
  1138. RegToPHIIdx[Reg].push_back(PHIIt.first);
  1139. }
  1140. ModifiedMF = Changed;
  1141. return Changed;
  1142. }
  1143. static void removeDebugInstrs(MachineFunction &mf) {
  1144. for (MachineBasicBlock &MBB : mf) {
  1145. for (MachineInstr &MI : llvm::make_early_inc_range(MBB))
  1146. if (MI.isDebugInstr())
  1147. MBB.erase(&MI);
  1148. }
  1149. }
  1150. bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
  1151. if (!EnableLDV)
  1152. return false;
  1153. if (!mf.getFunction().getSubprogram()) {
  1154. removeDebugInstrs(mf);
  1155. return false;
  1156. }
  1157. // Have we been asked to track variable locations using instruction
  1158. // referencing?
  1159. bool InstrRef = mf.useDebugInstrRef();
  1160. if (!pImpl)
  1161. pImpl = new LDVImpl(this);
  1162. return static_cast<LDVImpl *>(pImpl)->runOnMachineFunction(mf, InstrRef);
  1163. }
  1164. void LiveDebugVariables::releaseMemory() {
  1165. if (pImpl)
  1166. static_cast<LDVImpl*>(pImpl)->clear();
  1167. }
  1168. LiveDebugVariables::~LiveDebugVariables() {
  1169. if (pImpl)
  1170. delete static_cast<LDVImpl*>(pImpl);
  1171. }
  1172. //===----------------------------------------------------------------------===//
  1173. // Live Range Splitting
  1174. //===----------------------------------------------------------------------===//
  1175. bool
  1176. UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
  1177. LiveIntervals& LIS) {
  1178. LLVM_DEBUG({
  1179. dbgs() << "Splitting Loc" << OldLocNo << '\t';
  1180. print(dbgs(), nullptr);
  1181. });
  1182. bool DidChange = false;
  1183. LocMap::iterator LocMapI;
  1184. LocMapI.setMap(locInts);
  1185. for (Register NewReg : NewRegs) {
  1186. LiveInterval *LI = &LIS.getInterval(NewReg);
  1187. if (LI->empty())
  1188. continue;
  1189. // Don't allocate the new LocNo until it is needed.
  1190. unsigned NewLocNo = UndefLocNo;
  1191. // Iterate over the overlaps between locInts and LI.
  1192. LocMapI.find(LI->beginIndex());
  1193. if (!LocMapI.valid())
  1194. continue;
  1195. LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
  1196. LiveInterval::iterator LIE = LI->end();
  1197. while (LocMapI.valid() && LII != LIE) {
  1198. // At this point, we know that LocMapI.stop() > LII->start.
  1199. LII = LI->advanceTo(LII, LocMapI.start());
  1200. if (LII == LIE)
  1201. break;
  1202. // Now LII->end > LocMapI.start(). Do we have an overlap?
  1203. if (LocMapI.value().containsLocNo(OldLocNo) &&
  1204. LII->start < LocMapI.stop()) {
  1205. // Overlapping correct location. Allocate NewLocNo now.
  1206. if (NewLocNo == UndefLocNo) {
  1207. MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false);
  1208. MO.setSubReg(locations[OldLocNo].getSubReg());
  1209. NewLocNo = getLocationNo(MO);
  1210. DidChange = true;
  1211. }
  1212. SlotIndex LStart = LocMapI.start();
  1213. SlotIndex LStop = LocMapI.stop();
  1214. DbgVariableValue OldDbgValue = LocMapI.value();
  1215. // Trim LocMapI down to the LII overlap.
  1216. if (LStart < LII->start)
  1217. LocMapI.setStartUnchecked(LII->start);
  1218. if (LStop > LII->end)
  1219. LocMapI.setStopUnchecked(LII->end);
  1220. // Change the value in the overlap. This may trigger coalescing.
  1221. LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo));
  1222. // Re-insert any removed OldDbgValue ranges.
  1223. if (LStart < LocMapI.start()) {
  1224. LocMapI.insert(LStart, LocMapI.start(), OldDbgValue);
  1225. ++LocMapI;
  1226. assert(LocMapI.valid() && "Unexpected coalescing");
  1227. }
  1228. if (LStop > LocMapI.stop()) {
  1229. ++LocMapI;
  1230. LocMapI.insert(LII->end, LStop, OldDbgValue);
  1231. --LocMapI;
  1232. }
  1233. }
  1234. // Advance to the next overlap.
  1235. if (LII->end < LocMapI.stop()) {
  1236. if (++LII == LIE)
  1237. break;
  1238. LocMapI.advanceTo(LII->start);
  1239. } else {
  1240. ++LocMapI;
  1241. if (!LocMapI.valid())
  1242. break;
  1243. LII = LI->advanceTo(LII, LocMapI.start());
  1244. }
  1245. }
  1246. }
  1247. // Finally, remove OldLocNo unless it is still used by some interval in the
  1248. // locInts map. One case when OldLocNo still is in use is when the register
  1249. // has been spilled. In such situations the spilled register is kept as a
  1250. // location until rewriteLocations is called (VirtRegMap is mapping the old
  1251. // register to the spill slot). So for a while we can have locations that map
  1252. // to virtual registers that have been removed from both the MachineFunction
  1253. // and from LiveIntervals.
  1254. //
  1255. // We may also just be using the location for a value with a different
  1256. // expression.
  1257. removeLocationIfUnused(OldLocNo);
  1258. LLVM_DEBUG({
  1259. dbgs() << "Split result: \t";
  1260. print(dbgs(), nullptr);
  1261. });
  1262. return DidChange;
  1263. }
  1264. bool
  1265. UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
  1266. LiveIntervals &LIS) {
  1267. bool DidChange = false;
  1268. // Split locations referring to OldReg. Iterate backwards so splitLocation can
  1269. // safely erase unused locations.
  1270. for (unsigned i = locations.size(); i ; --i) {
  1271. unsigned LocNo = i-1;
  1272. const MachineOperand *Loc = &locations[LocNo];
  1273. if (!Loc->isReg() || Loc->getReg() != OldReg)
  1274. continue;
  1275. DidChange |= splitLocation(LocNo, NewRegs, LIS);
  1276. }
  1277. return DidChange;
  1278. }
  1279. void LDVImpl::splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs) {
  1280. auto RegIt = RegToPHIIdx.find(OldReg);
  1281. if (RegIt == RegToPHIIdx.end())
  1282. return;
  1283. std::vector<std::pair<Register, unsigned>> NewRegIdxes;
  1284. // Iterate over all the debug instruction numbers affected by this split.
  1285. for (unsigned InstrID : RegIt->second) {
  1286. auto PHIIt = PHIValToPos.find(InstrID);
  1287. assert(PHIIt != PHIValToPos.end());
  1288. const SlotIndex &Slot = PHIIt->second.SI;
  1289. assert(OldReg == PHIIt->second.Reg);
  1290. // Find the new register that covers this position.
  1291. for (auto NewReg : NewRegs) {
  1292. const LiveInterval &LI = LIS->getInterval(NewReg);
  1293. auto LII = LI.find(Slot);
  1294. if (LII != LI.end() && LII->start <= Slot) {
  1295. // This new register covers this PHI position, record this for indexing.
  1296. NewRegIdxes.push_back(std::make_pair(NewReg, InstrID));
  1297. // Record that this value lives in a different VReg now.
  1298. PHIIt->second.Reg = NewReg;
  1299. break;
  1300. }
  1301. }
  1302. // If we do not find a new register covering this PHI, then register
  1303. // allocation has dropped its location, for example because it's not live.
  1304. // The old VReg will not be mapped to a physreg, and the instruction
  1305. // number will have been optimized out.
  1306. }
  1307. // Re-create register index using the new register numbers.
  1308. RegToPHIIdx.erase(RegIt);
  1309. for (auto &RegAndInstr : NewRegIdxes)
  1310. RegToPHIIdx[RegAndInstr.first].push_back(RegAndInstr.second);
  1311. }
  1312. void LDVImpl::splitRegister(Register OldReg, ArrayRef<Register> NewRegs) {
  1313. // Consider whether this split range affects any PHI locations.
  1314. splitPHIRegister(OldReg, NewRegs);
  1315. // Check whether any intervals mapped by a DBG_VALUE were split and need
  1316. // updating.
  1317. bool DidChange = false;
  1318. for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
  1319. DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
  1320. if (!DidChange)
  1321. return;
  1322. // Map all of the new virtual registers.
  1323. UserValue *UV = lookupVirtReg(OldReg);
  1324. for (Register NewReg : NewRegs)
  1325. mapVirtReg(NewReg, UV);
  1326. }
  1327. void LiveDebugVariables::
  1328. splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) {
  1329. if (pImpl)
  1330. static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
  1331. }
  1332. void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
  1333. const TargetInstrInfo &TII,
  1334. const TargetRegisterInfo &TRI,
  1335. SpillOffsetMap &SpillOffsets) {
  1336. // Build a set of new locations with new numbers so we can coalesce our
  1337. // IntervalMap if two vreg intervals collapse to the same physical location.
  1338. // Use MapVector instead of SetVector because MapVector::insert returns the
  1339. // position of the previously or newly inserted element. The boolean value
  1340. // tracks if the location was produced by a spill.
  1341. // FIXME: This will be problematic if we ever support direct and indirect
  1342. // frame index locations, i.e. expressing both variables in memory and
  1343. // 'int x, *px = &x'. The "spilled" bit must become part of the location.
  1344. MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
  1345. SmallVector<unsigned, 4> LocNoMap(locations.size());
  1346. for (unsigned I = 0, E = locations.size(); I != E; ++I) {
  1347. bool Spilled = false;
  1348. unsigned SpillOffset = 0;
  1349. MachineOperand Loc = locations[I];
  1350. // Only virtual registers are rewritten.
  1351. if (Loc.isReg() && Loc.getReg() && Loc.getReg().isVirtual()) {
  1352. Register VirtReg = Loc.getReg();
  1353. if (VRM.isAssignedReg(VirtReg) &&
  1354. Register::isPhysicalRegister(VRM.getPhys(VirtReg))) {
  1355. // This can create a %noreg operand in rare cases when the sub-register
  1356. // index is no longer available. That means the user value is in a
  1357. // non-existent sub-register, and %noreg is exactly what we want.
  1358. Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
  1359. } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
  1360. // Retrieve the stack slot offset.
  1361. unsigned SpillSize;
  1362. const MachineRegisterInfo &MRI = MF.getRegInfo();
  1363. const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
  1364. bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
  1365. SpillOffset, MF);
  1366. // FIXME: Invalidate the location if the offset couldn't be calculated.
  1367. (void)Success;
  1368. Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
  1369. Spilled = true;
  1370. } else {
  1371. Loc.setReg(0);
  1372. Loc.setSubReg(0);
  1373. }
  1374. }
  1375. // Insert this location if it doesn't already exist and record a mapping
  1376. // from the old number to the new number.
  1377. auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
  1378. unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
  1379. LocNoMap[I] = NewLocNo;
  1380. }
  1381. // Rewrite the locations and record the stack slot offsets for spills.
  1382. locations.clear();
  1383. SpillOffsets.clear();
  1384. for (auto &Pair : NewLocations) {
  1385. bool Spilled;
  1386. unsigned SpillOffset;
  1387. std::tie(Spilled, SpillOffset) = Pair.second;
  1388. locations.push_back(Pair.first);
  1389. if (Spilled) {
  1390. unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
  1391. SpillOffsets[NewLocNo] = SpillOffset;
  1392. }
  1393. }
  1394. // Update the interval map, but only coalesce left, since intervals to the
  1395. // right use the old location numbers. This should merge two contiguous
  1396. // DBG_VALUE intervals with different vregs that were allocated to the same
  1397. // physical register.
  1398. for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
  1399. I.setValueUnchecked(I.value().remapLocNos(LocNoMap));
  1400. I.setStart(I.start());
  1401. }
  1402. }
  1403. /// Find an iterator for inserting a DBG_VALUE instruction.
  1404. static MachineBasicBlock::iterator
  1405. findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS,
  1406. BlockSkipInstsMap &BBSkipInstsMap) {
  1407. SlotIndex Start = LIS.getMBBStartIdx(MBB);
  1408. Idx = Idx.getBaseIndex();
  1409. // Try to find an insert location by going backwards from Idx.
  1410. MachineInstr *MI;
  1411. while (!(MI = LIS.getInstructionFromIndex(Idx))) {
  1412. // We've reached the beginning of MBB.
  1413. if (Idx == Start) {
  1414. // Retrieve the last PHI/Label/Debug location found when calling
  1415. // SkipPHIsLabelsAndDebug last time. Start searching from there.
  1416. //
  1417. // Note the iterator kept in BBSkipInstsMap is one step back based
  1418. // on the iterator returned by SkipPHIsLabelsAndDebug last time.
  1419. // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(),
  1420. // BBSkipInstsMap won't save it. This is to consider the case that
  1421. // new instructions may be inserted at the beginning of MBB after
  1422. // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in
  1423. // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions
  1424. // are inserted at the beginning of the MBB, the iterator in
  1425. // BBSkipInstsMap won't point to the beginning of the MBB anymore.
  1426. // Therefore The next search in SkipPHIsLabelsAndDebug will skip those
  1427. // newly added instructions and that is unwanted.
  1428. MachineBasicBlock::iterator BeginIt;
  1429. auto MapIt = BBSkipInstsMap.find(MBB);
  1430. if (MapIt == BBSkipInstsMap.end())
  1431. BeginIt = MBB->begin();
  1432. else
  1433. BeginIt = std::next(MapIt->second);
  1434. auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt);
  1435. if (I != BeginIt)
  1436. BBSkipInstsMap[MBB] = std::prev(I);
  1437. return I;
  1438. }
  1439. Idx = Idx.getPrevIndex();
  1440. }
  1441. // Don't insert anything after the first terminator, though.
  1442. return MI->isTerminator() ? MBB->getFirstTerminator() :
  1443. std::next(MachineBasicBlock::iterator(MI));
  1444. }
  1445. /// Find an iterator for inserting the next DBG_VALUE instruction
  1446. /// (or end if no more insert locations found).
  1447. static MachineBasicBlock::iterator
  1448. findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I,
  1449. SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs,
  1450. LiveIntervals &LIS, const TargetRegisterInfo &TRI) {
  1451. SmallVector<Register, 4> Regs;
  1452. for (const MachineOperand &LocMO : LocMOs)
  1453. if (LocMO.isReg())
  1454. Regs.push_back(LocMO.getReg());
  1455. if (Regs.empty())
  1456. return MBB->instr_end();
  1457. // Find the next instruction in the MBB that define the register Reg.
  1458. while (I != MBB->end() && !I->isTerminator()) {
  1459. if (!LIS.isNotInMIMap(*I) &&
  1460. SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
  1461. break;
  1462. if (any_of(Regs, [&I, &TRI](Register &Reg) {
  1463. return I->definesRegister(Reg, &TRI);
  1464. }))
  1465. // The insert location is directly after the instruction/bundle.
  1466. return std::next(I);
  1467. ++I;
  1468. }
  1469. return MBB->end();
  1470. }
  1471. void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
  1472. SlotIndex StopIdx, DbgVariableValue DbgValue,
  1473. ArrayRef<bool> LocSpills,
  1474. ArrayRef<unsigned> SpillOffsets,
  1475. LiveIntervals &LIS, const TargetInstrInfo &TII,
  1476. const TargetRegisterInfo &TRI,
  1477. BlockSkipInstsMap &BBSkipInstsMap) {
  1478. SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
  1479. // Only search within the current MBB.
  1480. StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
  1481. MachineBasicBlock::iterator I =
  1482. findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap);
  1483. // Undef values don't exist in locations so create new "noreg" register MOs
  1484. // for them. See getLocationNo().
  1485. SmallVector<MachineOperand, 8> MOs;
  1486. if (DbgValue.isUndef()) {
  1487. MOs.assign(DbgValue.loc_nos().size(),
  1488. MachineOperand::CreateReg(
  1489. /* Reg */ 0, /* isDef */ false, /* isImp */ false,
  1490. /* isKill */ false, /* isDead */ false,
  1491. /* isUndef */ false, /* isEarlyClobber */ false,
  1492. /* SubReg */ 0, /* isDebug */ true));
  1493. } else {
  1494. for (unsigned LocNo : DbgValue.loc_nos())
  1495. MOs.push_back(locations[LocNo]);
  1496. }
  1497. ++NumInsertedDebugValues;
  1498. assert(cast<DILocalVariable>(Variable)
  1499. ->isValidLocationForIntrinsic(getDebugLoc()) &&
  1500. "Expected inlined-at fields to agree");
  1501. // If the location was spilled, the new DBG_VALUE will be indirect. If the
  1502. // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
  1503. // that the original virtual register was a pointer. Also, add the stack slot
  1504. // offset for the spilled register to the expression.
  1505. const DIExpression *Expr = DbgValue.getExpression();
  1506. bool IsIndirect = DbgValue.getWasIndirect();
  1507. bool IsList = DbgValue.getWasList();
  1508. for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) {
  1509. if (LocSpills[I]) {
  1510. if (!IsList) {
  1511. uint8_t DIExprFlags = DIExpression::ApplyOffset;
  1512. if (IsIndirect)
  1513. DIExprFlags |= DIExpression::DerefAfter;
  1514. Expr = DIExpression::prepend(Expr, DIExprFlags, SpillOffsets[I]);
  1515. IsIndirect = true;
  1516. } else {
  1517. SmallVector<uint64_t, 4> Ops;
  1518. DIExpression::appendOffset(Ops, SpillOffsets[I]);
  1519. Ops.push_back(dwarf::DW_OP_deref);
  1520. Expr = DIExpression::appendOpsToArg(Expr, Ops, I);
  1521. }
  1522. }
  1523. assert((!LocSpills[I] || MOs[I].isFI()) &&
  1524. "a spilled location must be a frame index");
  1525. }
  1526. unsigned DbgValueOpcode =
  1527. IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE;
  1528. do {
  1529. BuildMI(*MBB, I, getDebugLoc(), TII.get(DbgValueOpcode), IsIndirect, MOs,
  1530. Variable, Expr);
  1531. // Continue and insert DBG_VALUES after every redefinition of a register
  1532. // associated with the debug value within the range
  1533. I = findNextInsertLocation(MBB, I, StopIdx, MOs, LIS, TRI);
  1534. } while (I != MBB->end());
  1535. }
  1536. void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
  1537. LiveIntervals &LIS, const TargetInstrInfo &TII,
  1538. BlockSkipInstsMap &BBSkipInstsMap) {
  1539. MachineBasicBlock::iterator I =
  1540. findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap);
  1541. ++NumInsertedDebugLabels;
  1542. BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
  1543. .addMetadata(Label);
  1544. }
  1545. void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
  1546. const TargetInstrInfo &TII,
  1547. const TargetRegisterInfo &TRI,
  1548. const SpillOffsetMap &SpillOffsets,
  1549. BlockSkipInstsMap &BBSkipInstsMap) {
  1550. MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
  1551. for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
  1552. SlotIndex Start = I.start();
  1553. SlotIndex Stop = I.stop();
  1554. DbgVariableValue DbgValue = I.value();
  1555. SmallVector<bool> SpilledLocs;
  1556. SmallVector<unsigned> LocSpillOffsets;
  1557. for (unsigned LocNo : DbgValue.loc_nos()) {
  1558. auto SpillIt =
  1559. !DbgValue.isUndef() ? SpillOffsets.find(LocNo) : SpillOffsets.end();
  1560. bool Spilled = SpillIt != SpillOffsets.end();
  1561. SpilledLocs.push_back(Spilled);
  1562. LocSpillOffsets.push_back(Spilled ? SpillIt->second : 0);
  1563. }
  1564. // If the interval start was trimmed to the lexical scope insert the
  1565. // DBG_VALUE at the previous index (otherwise it appears after the
  1566. // first instruction in the range).
  1567. if (trimmedDefs.count(Start))
  1568. Start = Start.getPrevIndex();
  1569. LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):";
  1570. DbgValue.printLocNos(dbg));
  1571. MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
  1572. SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
  1573. LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
  1574. insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, LocSpillOffsets,
  1575. LIS, TII, TRI, BBSkipInstsMap);
  1576. // This interval may span multiple basic blocks.
  1577. // Insert a DBG_VALUE into each one.
  1578. while (Stop > MBBEnd) {
  1579. // Move to the next block.
  1580. Start = MBBEnd;
  1581. if (++MBB == MFEnd)
  1582. break;
  1583. MBBEnd = LIS.getMBBEndIdx(&*MBB);
  1584. LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
  1585. insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs,
  1586. LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap);
  1587. }
  1588. LLVM_DEBUG(dbgs() << '\n');
  1589. if (MBB == MFEnd)
  1590. break;
  1591. ++I;
  1592. }
  1593. }
  1594. void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
  1595. BlockSkipInstsMap &BBSkipInstsMap) {
  1596. LLVM_DEBUG(dbgs() << "\t" << loc);
  1597. MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator();
  1598. LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
  1599. insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap);
  1600. LLVM_DEBUG(dbgs() << '\n');
  1601. }
  1602. void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
  1603. LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
  1604. if (!MF)
  1605. return;
  1606. BlockSkipInstsMap BBSkipInstsMap;
  1607. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  1608. SpillOffsetMap SpillOffsets;
  1609. for (auto &userValue : userValues) {
  1610. LLVM_DEBUG(userValue->print(dbgs(), TRI));
  1611. userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
  1612. userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets,
  1613. BBSkipInstsMap);
  1614. }
  1615. LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
  1616. for (auto &userLabel : userLabels) {
  1617. LLVM_DEBUG(userLabel->print(dbgs(), TRI));
  1618. userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap);
  1619. }
  1620. LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n");
  1621. auto Slots = LIS->getSlotIndexes();
  1622. for (auto &It : PHIValToPos) {
  1623. // For each ex-PHI, identify its physreg location or stack slot, and emit
  1624. // a DBG_PHI for it.
  1625. unsigned InstNum = It.first;
  1626. auto Slot = It.second.SI;
  1627. Register Reg = It.second.Reg;
  1628. unsigned SubReg = It.second.SubReg;
  1629. MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(Slot);
  1630. if (VRM->isAssignedReg(Reg) &&
  1631. Register::isPhysicalRegister(VRM->getPhys(Reg))) {
  1632. unsigned PhysReg = VRM->getPhys(Reg);
  1633. if (SubReg != 0)
  1634. PhysReg = TRI->getSubReg(PhysReg, SubReg);
  1635. auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
  1636. TII->get(TargetOpcode::DBG_PHI));
  1637. Builder.addReg(PhysReg);
  1638. Builder.addImm(InstNum);
  1639. } else if (VRM->getStackSlot(Reg) != VirtRegMap::NO_STACK_SLOT) {
  1640. const MachineRegisterInfo &MRI = MF->getRegInfo();
  1641. const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
  1642. unsigned SpillSize, SpillOffset;
  1643. unsigned regSizeInBits = TRI->getRegSizeInBits(*TRC);
  1644. if (SubReg)
  1645. regSizeInBits = TRI->getSubRegIdxSize(SubReg);
  1646. // Test whether this location is legal with the given subreg. If the
  1647. // subregister has a nonzero offset, drop this location, it's too complex
  1648. // to describe. (TODO: future work).
  1649. bool Success =
  1650. TII->getStackSlotRange(TRC, SubReg, SpillSize, SpillOffset, *MF);
  1651. if (Success && SpillOffset == 0) {
  1652. auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
  1653. TII->get(TargetOpcode::DBG_PHI));
  1654. Builder.addFrameIndex(VRM->getStackSlot(Reg));
  1655. Builder.addImm(InstNum);
  1656. // Record how large the original value is. The stack slot might be
  1657. // merged and altered during optimisation, but we will want to know how
  1658. // large the value is, at this DBG_PHI.
  1659. Builder.addImm(regSizeInBits);
  1660. }
  1661. LLVM_DEBUG(
  1662. if (SpillOffset != 0) {
  1663. dbgs() << "DBG_PHI for Vreg " << Reg << " subreg " << SubReg <<
  1664. " has nonzero offset\n";
  1665. }
  1666. );
  1667. }
  1668. // If there was no mapping for a value ID, it's optimized out. Create no
  1669. // DBG_PHI, and any variables using this value will become optimized out.
  1670. }
  1671. MF->DebugPHIPositions.clear();
  1672. LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
  1673. // Re-insert any debug instrs back in the position they were. We must
  1674. // re-insert in the same order to ensure that debug instructions don't swap,
  1675. // which could re-order assignments. Do so in a batch -- once we find the
  1676. // insert position, insert all instructions at the same SlotIdx. They are
  1677. // guaranteed to appear in-sequence in StashedDebugInstrs because we insert
  1678. // them in order.
  1679. for (auto *StashIt = StashedDebugInstrs.begin();
  1680. StashIt != StashedDebugInstrs.end(); ++StashIt) {
  1681. SlotIndex Idx = StashIt->Idx;
  1682. MachineBasicBlock *MBB = StashIt->MBB;
  1683. MachineInstr *MI = StashIt->MI;
  1684. auto EmitInstsHere = [this, &StashIt, MBB, Idx,
  1685. MI](MachineBasicBlock::iterator InsertPos) {
  1686. // Insert this debug instruction.
  1687. MBB->insert(InsertPos, MI);
  1688. // Look at subsequent stashed debug instructions: if they're at the same
  1689. // index, insert those too.
  1690. auto NextItem = std::next(StashIt);
  1691. while (NextItem != StashedDebugInstrs.end() && NextItem->Idx == Idx) {
  1692. assert(NextItem->MBB == MBB && "Instrs with same slot index should be"
  1693. "in the same block");
  1694. MBB->insert(InsertPos, NextItem->MI);
  1695. StashIt = NextItem;
  1696. NextItem = std::next(StashIt);
  1697. };
  1698. };
  1699. // Start block index: find the first non-debug instr in the block, and
  1700. // insert before it.
  1701. if (Idx == Slots->getMBBStartIdx(MBB)) {
  1702. MachineBasicBlock::iterator InsertPos =
  1703. findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap);
  1704. EmitInstsHere(InsertPos);
  1705. continue;
  1706. }
  1707. if (MachineInstr *Pos = Slots->getInstructionFromIndex(Idx)) {
  1708. // Insert at the end of any debug instructions.
  1709. auto PostDebug = std::next(Pos->getIterator());
  1710. PostDebug = skipDebugInstructionsForward(PostDebug, MBB->instr_end());
  1711. EmitInstsHere(PostDebug);
  1712. } else {
  1713. // Insert position disappeared; walk forwards through slots until we
  1714. // find a new one.
  1715. SlotIndex End = Slots->getMBBEndIdx(MBB);
  1716. for (; Idx < End; Idx = Slots->getNextNonNullIndex(Idx)) {
  1717. Pos = Slots->getInstructionFromIndex(Idx);
  1718. if (Pos) {
  1719. EmitInstsHere(Pos->getIterator());
  1720. break;
  1721. }
  1722. }
  1723. // We have reached the end of the block and didn't find anywhere to
  1724. // insert! It's not safe to discard any debug instructions; place them
  1725. // in front of the first terminator, or in front of end().
  1726. if (Idx >= End) {
  1727. auto TermIt = MBB->getFirstTerminator();
  1728. EmitInstsHere(TermIt);
  1729. }
  1730. }
  1731. }
  1732. EmitDone = true;
  1733. BBSkipInstsMap.clear();
  1734. }
  1735. void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
  1736. if (pImpl)
  1737. static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
  1738. }
  1739. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1740. LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
  1741. if (pImpl)
  1742. static_cast<LDVImpl*>(pImpl)->print(dbgs());
  1743. }
  1744. #endif