LiveDebugVariables.cpp 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954
  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/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/Passes.h"
  41. #include "llvm/CodeGen/SlotIndexes.h"
  42. #include "llvm/CodeGen/TargetInstrInfo.h"
  43. #include "llvm/CodeGen/TargetOpcodes.h"
  44. #include "llvm/CodeGen/TargetPassConfig.h"
  45. #include "llvm/CodeGen/TargetRegisterInfo.h"
  46. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  47. #include "llvm/CodeGen/VirtRegMap.h"
  48. #include "llvm/Config/llvm-config.h"
  49. #include "llvm/IR/DebugInfoMetadata.h"
  50. #include "llvm/IR/DebugLoc.h"
  51. #include "llvm/IR/Function.h"
  52. #include "llvm/IR/Metadata.h"
  53. #include "llvm/InitializePasses.h"
  54. #include "llvm/MC/MCRegisterInfo.h"
  55. #include "llvm/Pass.h"
  56. #include "llvm/Support/Casting.h"
  57. #include "llvm/Support/CommandLine.h"
  58. #include "llvm/Support/Debug.h"
  59. #include "llvm/Support/raw_ostream.h"
  60. #include "llvm/Target/TargetMachine.h"
  61. #include <algorithm>
  62. #include <cassert>
  63. #include <iterator>
  64. #include <memory>
  65. #include <utility>
  66. using namespace llvm;
  67. #define DEBUG_TYPE "livedebugvars"
  68. static cl::opt<bool>
  69. EnableLDV("live-debug-variables", cl::init(true),
  70. cl::desc("Enable the live debug variables pass"), cl::Hidden);
  71. STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
  72. STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
  73. char LiveDebugVariables::ID = 0;
  74. INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
  75. "Debug Variable Analysis", false, false)
  76. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  77. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  78. INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
  79. "Debug Variable Analysis", false, false)
  80. void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
  81. AU.addRequired<MachineDominatorTree>();
  82. AU.addRequiredTransitive<LiveIntervals>();
  83. AU.setPreservesAll();
  84. MachineFunctionPass::getAnalysisUsage(AU);
  85. }
  86. LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
  87. initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
  88. }
  89. enum : unsigned { UndefLocNo = ~0U };
  90. namespace {
  91. /// Describes a debug variable value by location number and expression along
  92. /// with some flags about the original usage of the location.
  93. class DbgVariableValue {
  94. public:
  95. DbgVariableValue(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList,
  96. const DIExpression &Expr)
  97. : WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) {
  98. assert(!(WasIndirect && WasList) &&
  99. "DBG_VALUE_LISTs should not be indirect.");
  100. SmallVector<unsigned> LocNoVec;
  101. for (unsigned LocNo : NewLocs) {
  102. auto It = find(LocNoVec, LocNo);
  103. if (It == LocNoVec.end())
  104. LocNoVec.push_back(LocNo);
  105. else {
  106. // Loc duplicates an element in LocNos; replace references to Op
  107. // with references to the duplicating element.
  108. unsigned OpIdx = LocNoVec.size();
  109. unsigned DuplicatingIdx = std::distance(LocNoVec.begin(), It);
  110. Expression =
  111. DIExpression::replaceArg(Expression, OpIdx, DuplicatingIdx);
  112. }
  113. }
  114. // FIXME: Debug values referencing 64+ unique machine locations are rare and
  115. // currently unsupported for performance reasons. If we can verify that
  116. // performance is acceptable for such debug values, we can increase the
  117. // bit-width of LocNoCount to 14 to enable up to 16384 unique machine
  118. // locations. We will also need to verify that this does not cause issues
  119. // with LiveDebugVariables' use of IntervalMap.
  120. if (LocNoVec.size() < 64) {
  121. LocNoCount = LocNoVec.size();
  122. if (LocNoCount > 0) {
  123. LocNos = std::make_unique<unsigned[]>(LocNoCount);
  124. std::copy(LocNoVec.begin(), LocNoVec.end(), loc_nos_begin());
  125. }
  126. } else {
  127. LLVM_DEBUG(dbgs() << "Found debug value with 64+ unique machine "
  128. "locations, dropping...\n");
  129. LocNoCount = 1;
  130. // Turn this into an undef debug value list; right now, the simplest form
  131. // of this is an expression with one arg, and an undef debug operand.
  132. Expression =
  133. DIExpression::get(Expr.getContext(), {dwarf::DW_OP_LLVM_arg, 0,
  134. dwarf::DW_OP_stack_value});
  135. if (auto FragmentInfoOpt = Expr.getFragmentInfo())
  136. Expression = *DIExpression::createFragmentExpression(
  137. Expression, FragmentInfoOpt->OffsetInBits,
  138. FragmentInfoOpt->SizeInBits);
  139. LocNos = std::make_unique<unsigned[]>(LocNoCount);
  140. LocNos[0] = UndefLocNo;
  141. }
  142. }
  143. DbgVariableValue() : LocNoCount(0), WasIndirect(false), WasList(false) {}
  144. DbgVariableValue(const DbgVariableValue &Other)
  145. : LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()),
  146. WasList(Other.getWasList()), Expression(Other.getExpression()) {
  147. if (Other.getLocNoCount()) {
  148. LocNos.reset(new unsigned[Other.getLocNoCount()]);
  149. std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
  150. }
  151. }
  152. DbgVariableValue &operator=(const DbgVariableValue &Other) {
  153. if (this == &Other)
  154. return *this;
  155. if (Other.getLocNoCount()) {
  156. LocNos.reset(new unsigned[Other.getLocNoCount()]);
  157. std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
  158. } else {
  159. LocNos.release();
  160. }
  161. LocNoCount = Other.getLocNoCount();
  162. WasIndirect = Other.getWasIndirect();
  163. WasList = Other.getWasList();
  164. Expression = Other.getExpression();
  165. return *this;
  166. }
  167. const DIExpression *getExpression() const { return Expression; }
  168. uint8_t getLocNoCount() const { return LocNoCount; }
  169. bool containsLocNo(unsigned LocNo) const {
  170. return is_contained(loc_nos(), LocNo);
  171. }
  172. bool getWasIndirect() const { return WasIndirect; }
  173. bool getWasList() const { return WasList; }
  174. bool isUndef() const { return LocNoCount == 0 || containsLocNo(UndefLocNo); }
  175. DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const {
  176. SmallVector<unsigned, 4> NewLocNos;
  177. for (unsigned LocNo : loc_nos())
  178. NewLocNos.push_back(LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1
  179. : LocNo);
  180. return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
  181. }
  182. DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const {
  183. SmallVector<unsigned> NewLocNos;
  184. for (unsigned LocNo : loc_nos())
  185. // Undef values don't exist in locations (and thus not in LocNoMap
  186. // either) so skip over them. See getLocationNo().
  187. NewLocNos.push_back(LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]);
  188. return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
  189. }
  190. DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const {
  191. SmallVector<unsigned> NewLocNos;
  192. NewLocNos.assign(loc_nos_begin(), loc_nos_end());
  193. auto OldLocIt = find(NewLocNos, OldLocNo);
  194. assert(OldLocIt != NewLocNos.end() && "Old location must be present.");
  195. *OldLocIt = NewLocNo;
  196. return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
  197. }
  198. bool hasLocNoGreaterThan(unsigned LocNo) const {
  199. return any_of(loc_nos(),
  200. [LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; });
  201. }
  202. void printLocNos(llvm::raw_ostream &OS) const {
  203. for (const unsigned &Loc : loc_nos())
  204. OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc;
  205. }
  206. friend inline bool operator==(const DbgVariableValue &LHS,
  207. const DbgVariableValue &RHS) {
  208. if (std::tie(LHS.LocNoCount, LHS.WasIndirect, LHS.WasList,
  209. LHS.Expression) !=
  210. std::tie(RHS.LocNoCount, RHS.WasIndirect, RHS.WasList, RHS.Expression))
  211. return false;
  212. return std::equal(LHS.loc_nos_begin(), LHS.loc_nos_end(),
  213. RHS.loc_nos_begin());
  214. }
  215. friend inline bool operator!=(const DbgVariableValue &LHS,
  216. const DbgVariableValue &RHS) {
  217. return !(LHS == RHS);
  218. }
  219. unsigned *loc_nos_begin() { return LocNos.get(); }
  220. const unsigned *loc_nos_begin() const { return LocNos.get(); }
  221. unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; }
  222. const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; }
  223. ArrayRef<unsigned> loc_nos() const {
  224. return ArrayRef<unsigned>(LocNos.get(), LocNoCount);
  225. }
  226. private:
  227. // IntervalMap requires the value object to be very small, to the extent
  228. // that we do not have enough room for an std::vector. Using a C-style array
  229. // (with a unique_ptr wrapper for convenience) allows us to optimize for this
  230. // specific case by packing the array size into only 6 bits (it is highly
  231. // unlikely that any debug value will need 64+ locations).
  232. std::unique_ptr<unsigned[]> LocNos;
  233. uint8_t LocNoCount : 6;
  234. bool WasIndirect : 1;
  235. bool WasList : 1;
  236. const DIExpression *Expression = nullptr;
  237. };
  238. } // namespace
  239. /// Map of where a user value is live to that value.
  240. using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>;
  241. /// Map of stack slot offsets for spilled locations.
  242. /// Non-spilled locations are not added to the map.
  243. using SpillOffsetMap = DenseMap<unsigned, unsigned>;
  244. /// Cache to save the location where it can be used as the starting
  245. /// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug.
  246. /// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from
  247. /// repeatedly searching the same set of PHIs/Labels/Debug instructions
  248. /// if it is called many times for the same block.
  249. using BlockSkipInstsMap =
  250. DenseMap<MachineBasicBlock *, MachineBasicBlock::iterator>;
  251. namespace {
  252. class LDVImpl;
  253. /// A user value is a part of a debug info user variable.
  254. ///
  255. /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
  256. /// holds part of a user variable. The part is identified by a byte offset.
  257. ///
  258. /// UserValues are grouped into equivalence classes for easier searching. Two
  259. /// user values are related if they are held by the same virtual register. The
  260. /// equivalence class is the transitive closure of that relation.
  261. class UserValue {
  262. const DILocalVariable *Variable; ///< The debug info variable we are part of.
  263. /// The part of the variable we describe.
  264. const Optional<DIExpression::FragmentInfo> Fragment;
  265. DebugLoc dl; ///< The debug location for the variable. This is
  266. ///< used by dwarf writer to find lexical scope.
  267. UserValue *leader; ///< Equivalence class leader.
  268. UserValue *next = nullptr; ///< Next value in equivalence class, or null.
  269. /// Numbered locations referenced by locmap.
  270. SmallVector<MachineOperand, 4> locations;
  271. /// Map of slot indices where this value is live.
  272. LocMap locInts;
  273. /// Set of interval start indexes that have been trimmed to the
  274. /// lexical scope.
  275. SmallSet<SlotIndex, 2> trimmedDefs;
  276. /// Insert a DBG_VALUE into MBB at Idx for DbgValue.
  277. void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
  278. SlotIndex StopIdx, DbgVariableValue DbgValue,
  279. ArrayRef<bool> LocSpills,
  280. ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS,
  281. const TargetInstrInfo &TII,
  282. const TargetRegisterInfo &TRI,
  283. BlockSkipInstsMap &BBSkipInstsMap);
  284. /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
  285. /// is live. Returns true if any changes were made.
  286. bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
  287. LiveIntervals &LIS);
  288. public:
  289. /// Create a new UserValue.
  290. UserValue(const DILocalVariable *var,
  291. Optional<DIExpression::FragmentInfo> Fragment, DebugLoc L,
  292. LocMap::Allocator &alloc)
  293. : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this),
  294. locInts(alloc) {}
  295. /// Get the leader of this value's equivalence class.
  296. UserValue *getLeader() {
  297. UserValue *l = leader;
  298. while (l != l->leader)
  299. l = l->leader;
  300. return leader = l;
  301. }
  302. /// Return the next UserValue in the equivalence class.
  303. UserValue *getNext() const { return next; }
  304. /// Merge equivalence classes.
  305. static UserValue *merge(UserValue *L1, UserValue *L2) {
  306. L2 = L2->getLeader();
  307. if (!L1)
  308. return L2;
  309. L1 = L1->getLeader();
  310. if (L1 == L2)
  311. return L1;
  312. // Splice L2 before L1's members.
  313. UserValue *End = L2;
  314. while (End->next) {
  315. End->leader = L1;
  316. End = End->next;
  317. }
  318. End->leader = L1;
  319. End->next = L1->next;
  320. L1->next = L2;
  321. return L1;
  322. }
  323. /// Return the location number that matches Loc.
  324. ///
  325. /// For undef values we always return location number UndefLocNo without
  326. /// inserting anything in locations. Since locations is a vector and the
  327. /// location number is the position in the vector and UndefLocNo is ~0,
  328. /// we would need a very big vector to put the value at the right position.
  329. unsigned getLocationNo(const MachineOperand &LocMO) {
  330. if (LocMO.isReg()) {
  331. if (LocMO.getReg() == 0)
  332. return UndefLocNo;
  333. // For register locations we dont care about use/def and other flags.
  334. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  335. if (locations[i].isReg() &&
  336. locations[i].getReg() == LocMO.getReg() &&
  337. locations[i].getSubReg() == LocMO.getSubReg())
  338. return i;
  339. } else
  340. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  341. if (LocMO.isIdenticalTo(locations[i]))
  342. return i;
  343. locations.push_back(LocMO);
  344. // We are storing a MachineOperand outside a MachineInstr.
  345. locations.back().clearParent();
  346. // Don't store def operands.
  347. if (locations.back().isReg()) {
  348. if (locations.back().isDef())
  349. locations.back().setIsDead(false);
  350. locations.back().setIsUse();
  351. }
  352. return locations.size() - 1;
  353. }
  354. /// Remove (recycle) a location number. If \p LocNo still is used by the
  355. /// locInts nothing is done.
  356. void removeLocationIfUnused(unsigned LocNo) {
  357. // Bail out if LocNo still is used.
  358. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
  359. const DbgVariableValue &DbgValue = I.value();
  360. if (DbgValue.containsLocNo(LocNo))
  361. return;
  362. }
  363. // Remove the entry in the locations vector, and adjust all references to
  364. // location numbers above the removed entry.
  365. locations.erase(locations.begin() + LocNo);
  366. for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
  367. const DbgVariableValue &DbgValue = I.value();
  368. if (DbgValue.hasLocNoGreaterThan(LocNo))
  369. I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(LocNo));
  370. }
  371. }
  372. /// Ensure that all virtual register locations are mapped.
  373. void mapVirtRegs(LDVImpl *LDV);
  374. /// Add a definition point to this user value.
  375. void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect,
  376. bool IsList, const DIExpression &Expr) {
  377. SmallVector<unsigned> Locs;
  378. for (const MachineOperand &Op : LocMOs)
  379. Locs.push_back(getLocationNo(Op));
  380. DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr);
  381. // Add a singular (Idx,Idx) -> value mapping.
  382. LocMap::iterator I = locInts.find(Idx);
  383. if (!I.valid() || I.start() != Idx)
  384. I.insert(Idx, Idx.getNextSlot(), std::move(DbgValue));
  385. else
  386. // A later DBG_VALUE at the same SlotIndex overrides the old location.
  387. I.setValue(std::move(DbgValue));
  388. }
  389. /// Extend the current definition as far as possible down.
  390. ///
  391. /// Stop when meeting an existing def or when leaving the live
  392. /// range of VNI. End points where VNI is no longer live are added to Kills.
  393. ///
  394. /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
  395. /// data-flow analysis to propagate them beyond basic block boundaries.
  396. ///
  397. /// \param Idx Starting point for the definition.
  398. /// \param DbgValue value to propagate.
  399. /// \param LiveIntervalInfo For each location number key in this map,
  400. /// restricts liveness to where the LiveRange has the value equal to the\
  401. /// VNInfo.
  402. /// \param [out] Kills Append end points of VNI's live range to Kills.
  403. /// \param LIS Live intervals analysis.
  404. void extendDef(SlotIndex Idx, DbgVariableValue DbgValue,
  405. SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
  406. &LiveIntervalInfo,
  407. Optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
  408. LiveIntervals &LIS);
  409. /// The value in LI may be copies to other registers. Determine if
  410. /// any of the copies are available at the kill points, and add defs if
  411. /// possible.
  412. ///
  413. /// \param DbgValue Location number of LI->reg, and DIExpression.
  414. /// \param LocIntervals Scan for copies of the value for each location in the
  415. /// corresponding LiveInterval->reg.
  416. /// \param KilledAt The point where the range of DbgValue could be extended.
  417. /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here.
  418. void addDefsFromCopies(
  419. DbgVariableValue DbgValue,
  420. SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
  421. SlotIndex KilledAt,
  422. SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
  423. MachineRegisterInfo &MRI, LiveIntervals &LIS);
  424. /// Compute the live intervals of all locations after collecting all their
  425. /// def points.
  426. void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
  427. LiveIntervals &LIS, LexicalScopes &LS);
  428. /// Replace OldReg ranges with NewRegs ranges where NewRegs is
  429. /// live. Returns true if any changes were made.
  430. bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
  431. LiveIntervals &LIS);
  432. /// Rewrite virtual register locations according to the provided virtual
  433. /// register map. Record the stack slot offsets for the locations that
  434. /// were spilled.
  435. void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
  436. const TargetInstrInfo &TII,
  437. const TargetRegisterInfo &TRI,
  438. SpillOffsetMap &SpillOffsets);
  439. /// Recreate DBG_VALUE instruction from data structures.
  440. void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
  441. const TargetInstrInfo &TII,
  442. const TargetRegisterInfo &TRI,
  443. const SpillOffsetMap &SpillOffsets,
  444. BlockSkipInstsMap &BBSkipInstsMap);
  445. /// Return DebugLoc of this UserValue.
  446. const DebugLoc &getDebugLoc() { return dl; }
  447. void print(raw_ostream &, const TargetRegisterInfo *);
  448. };
  449. /// A user label is a part of a debug info user label.
  450. class UserLabel {
  451. const DILabel *Label; ///< The debug info label we are part of.
  452. DebugLoc dl; ///< The debug location for the label. This is
  453. ///< used by dwarf writer to find lexical scope.
  454. SlotIndex loc; ///< Slot used by the debug label.
  455. /// Insert a DBG_LABEL into MBB at Idx.
  456. void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
  457. LiveIntervals &LIS, const TargetInstrInfo &TII,
  458. BlockSkipInstsMap &BBSkipInstsMap);
  459. public:
  460. /// Create a new UserLabel.
  461. UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
  462. : Label(label), dl(std::move(L)), loc(Idx) {}
  463. /// Does this UserLabel match the parameters?
  464. bool matches(const DILabel *L, const DILocation *IA,
  465. const SlotIndex Index) const {
  466. return Label == L && dl->getInlinedAt() == IA && loc == Index;
  467. }
  468. /// Recreate DBG_LABEL instruction from data structures.
  469. void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
  470. BlockSkipInstsMap &BBSkipInstsMap);
  471. /// Return DebugLoc of this UserLabel.
  472. const DebugLoc &getDebugLoc() { return dl; }
  473. void print(raw_ostream &, const TargetRegisterInfo *);
  474. };
  475. /// Implementation of the LiveDebugVariables pass.
  476. class LDVImpl {
  477. LiveDebugVariables &pass;
  478. LocMap::Allocator allocator;
  479. MachineFunction *MF = nullptr;
  480. LiveIntervals *LIS;
  481. const TargetRegisterInfo *TRI;
  482. /// Position and VReg of a PHI instruction during register allocation.
  483. struct PHIValPos {
  484. SlotIndex SI; /// Slot where this PHI occurs.
  485. Register Reg; /// VReg this PHI occurs in.
  486. unsigned SubReg; /// Qualifiying subregister for Reg.
  487. };
  488. /// Map from debug instruction number to PHI position during allocation.
  489. std::map<unsigned, PHIValPos> PHIValToPos;
  490. /// Index of, for each VReg, which debug instruction numbers and corresponding
  491. /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs,
  492. /// at different positions.
  493. DenseMap<Register, std::vector<unsigned>> RegToPHIIdx;
  494. /// Record for any debug instructions unlinked from their blocks during
  495. /// regalloc. Stores the instr and it's location, so that they can be
  496. /// re-inserted after regalloc is over.
  497. struct InstrPos {
  498. MachineInstr *MI; ///< Debug instruction, unlinked from it's block.
  499. SlotIndex Idx; ///< Slot position where MI should be re-inserted.
  500. MachineBasicBlock *MBB; ///< Block that MI was in.
  501. };
  502. /// Collection of stored debug instructions, preserved until after regalloc.
  503. SmallVector<InstrPos, 32> StashedDebugInstrs;
  504. /// Whether emitDebugValues is called.
  505. bool EmitDone = false;
  506. /// Whether the machine function is modified during the pass.
  507. bool ModifiedMF = false;
  508. /// All allocated UserValue instances.
  509. SmallVector<std::unique_ptr<UserValue>, 8> userValues;
  510. /// All allocated UserLabel instances.
  511. SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
  512. /// Map virtual register to eq class leader.
  513. using VRMap = DenseMap<unsigned, UserValue *>;
  514. VRMap virtRegToEqClass;
  515. /// Map to find existing UserValue instances.
  516. using UVMap = DenseMap<DebugVariable, UserValue *>;
  517. UVMap userVarMap;
  518. /// Find or create a UserValue.
  519. UserValue *getUserValue(const DILocalVariable *Var,
  520. Optional<DIExpression::FragmentInfo> Fragment,
  521. const DebugLoc &DL);
  522. /// Find the EC leader for VirtReg or null.
  523. UserValue *lookupVirtReg(Register VirtReg);
  524. /// Add DBG_VALUE instruction to our maps.
  525. ///
  526. /// \param MI DBG_VALUE instruction
  527. /// \param Idx Last valid SLotIndex before instruction.
  528. ///
  529. /// \returns True if the DBG_VALUE instruction should be deleted.
  530. bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
  531. /// Track variable location debug instructions while using the instruction
  532. /// referencing implementation. Such debug instructions do not need to be
  533. /// updated during regalloc because they identify instructions rather than
  534. /// register locations. However, they needs to be removed from the
  535. /// MachineFunction during regalloc, then re-inserted later, to avoid
  536. /// disrupting the allocator.
  537. ///
  538. /// \param MI Any DBG_VALUE / DBG_INSTR_REF / DBG_PHI instruction
  539. /// \param Idx Last valid SlotIndex before instruction
  540. ///
  541. /// \returns Iterator to continue processing from after unlinking.
  542. MachineBasicBlock::iterator handleDebugInstr(MachineInstr &MI, SlotIndex Idx);
  543. /// Add DBG_LABEL instruction to UserLabel.
  544. ///
  545. /// \param MI DBG_LABEL instruction
  546. /// \param Idx Last valid SlotIndex before instruction.
  547. ///
  548. /// \returns True if the DBG_LABEL instruction should be deleted.
  549. bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
  550. /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
  551. /// for each instruction.
  552. ///
  553. /// \param mf MachineFunction to be scanned.
  554. /// \param InstrRef Whether to operate in instruction referencing mode. If
  555. /// true, most of LiveDebugVariables doesn't run.
  556. ///
  557. /// \returns True if any debug values were found.
  558. bool collectDebugValues(MachineFunction &mf, bool InstrRef);
  559. /// Compute the live intervals of all user values after collecting all
  560. /// their def points.
  561. void computeIntervals();
  562. public:
  563. LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
  564. bool runOnMachineFunction(MachineFunction &mf, bool InstrRef);
  565. /// Release all memory.
  566. void clear() {
  567. MF = nullptr;
  568. PHIValToPos.clear();
  569. RegToPHIIdx.clear();
  570. StashedDebugInstrs.clear();
  571. userValues.clear();
  572. userLabels.clear();
  573. virtRegToEqClass.clear();
  574. userVarMap.clear();
  575. // Make sure we call emitDebugValues if the machine function was modified.
  576. assert((!ModifiedMF || EmitDone) &&
  577. "Dbg values are not emitted in LDV");
  578. EmitDone = false;
  579. ModifiedMF = false;
  580. }
  581. /// Map virtual register to an equivalence class.
  582. void mapVirtReg(Register VirtReg, UserValue *EC);
  583. /// Replace any PHI referring to OldReg with its corresponding NewReg, if
  584. /// present.
  585. void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs);
  586. /// Replace all references to OldReg with NewRegs.
  587. void splitRegister(Register OldReg, ArrayRef<Register> NewRegs);
  588. /// Recreate DBG_VALUE instruction from data structures.
  589. void emitDebugValues(VirtRegMap *VRM);
  590. void print(raw_ostream&);
  591. };
  592. } // end anonymous namespace
  593. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  594. static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
  595. const LLVMContext &Ctx) {
  596. if (!DL)
  597. return;
  598. auto *Scope = cast<DIScope>(DL.getScope());
  599. // Omit the directory, because it's likely to be long and uninteresting.
  600. CommentOS << Scope->getFilename();
  601. CommentOS << ':' << DL.getLine();
  602. if (DL.getCol() != 0)
  603. CommentOS << ':' << DL.getCol();
  604. DebugLoc InlinedAtDL = DL.getInlinedAt();
  605. if (!InlinedAtDL)
  606. return;
  607. CommentOS << " @[ ";
  608. printDebugLoc(InlinedAtDL, CommentOS, Ctx);
  609. CommentOS << " ]";
  610. }
  611. static void printExtendedName(raw_ostream &OS, const DINode *Node,
  612. const DILocation *DL) {
  613. const LLVMContext &Ctx = Node->getContext();
  614. StringRef Res;
  615. unsigned Line = 0;
  616. if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
  617. Res = V->getName();
  618. Line = V->getLine();
  619. } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
  620. Res = L->getName();
  621. Line = L->getLine();
  622. }
  623. if (!Res.empty())
  624. OS << Res << "," << Line;
  625. auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
  626. if (InlinedAt) {
  627. if (DebugLoc InlinedAtDL = InlinedAt) {
  628. OS << " @[";
  629. printDebugLoc(InlinedAtDL, OS, Ctx);
  630. OS << "]";
  631. }
  632. }
  633. }
  634. void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
  635. OS << "!\"";
  636. printExtendedName(OS, Variable, dl);
  637. OS << "\"\t";
  638. for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
  639. OS << " [" << I.start() << ';' << I.stop() << "):";
  640. if (I.value().isUndef())
  641. OS << " undef";
  642. else {
  643. I.value().printLocNos(OS);
  644. if (I.value().getWasIndirect())
  645. OS << " ind";
  646. else if (I.value().getWasList())
  647. OS << " list";
  648. }
  649. }
  650. for (unsigned i = 0, e = locations.size(); i != e; ++i) {
  651. OS << " Loc" << i << '=';
  652. locations[i].print(OS, TRI);
  653. }
  654. OS << '\n';
  655. }
  656. void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
  657. OS << "!\"";
  658. printExtendedName(OS, Label, dl);
  659. OS << "\"\t";
  660. OS << loc;
  661. OS << '\n';
  662. }
  663. void LDVImpl::print(raw_ostream &OS) {
  664. OS << "********** DEBUG VARIABLES **********\n";
  665. for (auto &userValue : userValues)
  666. userValue->print(OS, TRI);
  667. OS << "********** DEBUG LABELS **********\n";
  668. for (auto &userLabel : userLabels)
  669. userLabel->print(OS, TRI);
  670. }
  671. #endif
  672. void UserValue::mapVirtRegs(LDVImpl *LDV) {
  673. for (unsigned i = 0, e = locations.size(); i != e; ++i)
  674. if (locations[i].isReg() &&
  675. Register::isVirtualRegister(locations[i].getReg()))
  676. LDV->mapVirtReg(locations[i].getReg(), this);
  677. }
  678. UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
  679. Optional<DIExpression::FragmentInfo> Fragment,
  680. const DebugLoc &DL) {
  681. // FIXME: Handle partially overlapping fragments. See
  682. // https://reviews.llvm.org/D70121#1849741.
  683. DebugVariable ID(Var, Fragment, DL->getInlinedAt());
  684. UserValue *&UV = userVarMap[ID];
  685. if (!UV) {
  686. userValues.push_back(
  687. std::make_unique<UserValue>(Var, Fragment, DL, allocator));
  688. UV = userValues.back().get();
  689. }
  690. return UV;
  691. }
  692. void LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) {
  693. assert(Register::isVirtualRegister(VirtReg) && "Only map VirtRegs");
  694. UserValue *&Leader = virtRegToEqClass[VirtReg];
  695. Leader = UserValue::merge(Leader, EC);
  696. }
  697. UserValue *LDVImpl::lookupVirtReg(Register VirtReg) {
  698. if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
  699. return UV->getLeader();
  700. return nullptr;
  701. }
  702. bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
  703. // DBG_VALUE loc, offset, variable, expr
  704. // DBG_VALUE_LIST variable, expr, locs...
  705. if (!MI.isDebugValue()) {
  706. LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI);
  707. return false;
  708. }
  709. if (!MI.getDebugVariableOp().isMetadata()) {
  710. LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: "
  711. << MI);
  712. return false;
  713. }
  714. if (MI.isNonListDebugValue() &&
  715. (MI.getNumOperands() != 4 ||
  716. !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) {
  717. LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI);
  718. return false;
  719. }
  720. // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
  721. // register that hasn't been defined yet. If we do not remove those here, then
  722. // the re-insertion of the DBG_VALUE instruction after register allocation
  723. // will be incorrect.
  724. bool Discard = false;
  725. for (const MachineOperand &Op : MI.debug_operands()) {
  726. if (Op.isReg() && Register::isVirtualRegister(Op.getReg())) {
  727. const Register Reg = Op.getReg();
  728. if (!LIS->hasInterval(Reg)) {
  729. // The DBG_VALUE is described by a virtual register that does not have a
  730. // live interval. Discard the DBG_VALUE.
  731. Discard = true;
  732. LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
  733. << " " << MI);
  734. } else {
  735. // The DBG_VALUE is only valid if either Reg is live out from Idx, or
  736. // Reg is defined dead at Idx (where Idx is the slot index for the
  737. // instruction preceding the DBG_VALUE).
  738. const LiveInterval &LI = LIS->getInterval(Reg);
  739. LiveQueryResult LRQ = LI.Query(Idx);
  740. if (!LRQ.valueOutOrDead()) {
  741. // We have found a DBG_VALUE with the value in a virtual register that
  742. // is not live. Discard the DBG_VALUE.
  743. Discard = true;
  744. LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
  745. << " " << MI);
  746. }
  747. }
  748. }
  749. }
  750. // Get or create the UserValue for (variable,offset) here.
  751. bool IsIndirect = MI.isDebugOffsetImm();
  752. if (IsIndirect)
  753. assert(MI.getDebugOffset().getImm() == 0 &&
  754. "DBG_VALUE with nonzero offset");
  755. bool IsList = MI.isDebugValueList();
  756. const DILocalVariable *Var = MI.getDebugVariable();
  757. const DIExpression *Expr = MI.getDebugExpression();
  758. UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc());
  759. if (!Discard)
  760. UV->addDef(Idx,
  761. ArrayRef<MachineOperand>(MI.debug_operands().begin(),
  762. MI.debug_operands().end()),
  763. IsIndirect, IsList, *Expr);
  764. else {
  765. MachineOperand MO = MachineOperand::CreateReg(0U, false);
  766. MO.setIsDebug();
  767. // We should still pass a list the same size as MI.debug_operands() even if
  768. // all MOs are undef, so that DbgVariableValue can correctly adjust the
  769. // expression while removing the duplicated undefs.
  770. SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO);
  771. UV->addDef(Idx, UndefMOs, false, IsList, *Expr);
  772. }
  773. return true;
  774. }
  775. MachineBasicBlock::iterator LDVImpl::handleDebugInstr(MachineInstr &MI,
  776. SlotIndex Idx) {
  777. assert(MI.isDebugValue() || MI.isDebugRef() || MI.isDebugPHI());
  778. // In instruction referencing mode, there should be no DBG_VALUE instructions
  779. // that refer to virtual registers. They might still refer to constants.
  780. if (MI.isDebugValue())
  781. assert(!MI.getOperand(0).isReg() || !MI.getOperand(0).getReg().isVirtual());
  782. // Unlink the instruction, store it in the debug instructions collection.
  783. auto NextInst = std::next(MI.getIterator());
  784. auto *MBB = MI.getParent();
  785. MI.removeFromParent();
  786. StashedDebugInstrs.push_back({&MI, Idx, MBB});
  787. return NextInst;
  788. }
  789. bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) {
  790. // DBG_LABEL label
  791. if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
  792. LLVM_DEBUG(dbgs() << "Can't handle " << MI);
  793. return false;
  794. }
  795. // Get or create the UserLabel for label here.
  796. const DILabel *Label = MI.getDebugLabel();
  797. const DebugLoc &DL = MI.getDebugLoc();
  798. bool Found = false;
  799. for (auto const &L : userLabels) {
  800. if (L->matches(Label, DL->getInlinedAt(), Idx)) {
  801. Found = true;
  802. break;
  803. }
  804. }
  805. if (!Found)
  806. userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx));
  807. return true;
  808. }
  809. bool LDVImpl::collectDebugValues(MachineFunction &mf, bool InstrRef) {
  810. bool Changed = false;
  811. for (MachineBasicBlock &MBB : mf) {
  812. for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
  813. MBBI != MBBE;) {
  814. // Use the first debug instruction in the sequence to get a SlotIndex
  815. // for following consecutive debug instructions.
  816. if (!MBBI->isDebugOrPseudoInstr()) {
  817. ++MBBI;
  818. continue;
  819. }
  820. // Debug instructions has no slot index. Use the previous
  821. // non-debug instruction's SlotIndex as its SlotIndex.
  822. SlotIndex Idx =
  823. MBBI == MBB.begin()
  824. ? LIS->getMBBStartIdx(&MBB)
  825. : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
  826. // Handle consecutive debug instructions with the same slot index.
  827. do {
  828. // In instruction referencing mode, pass each instr to handleDebugInstr
  829. // to be unlinked. Ignore DBG_VALUE_LISTs -- they refer to vregs, and
  830. // need to go through the normal live interval splitting process.
  831. if (InstrRef && (MBBI->isNonListDebugValue() || MBBI->isDebugPHI() ||
  832. MBBI->isDebugRef())) {
  833. MBBI = handleDebugInstr(*MBBI, Idx);
  834. Changed = true;
  835. // In normal debug mode, use the dedicated DBG_VALUE / DBG_LABEL handler
  836. // to track things through register allocation, and erase the instr.
  837. } else if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
  838. (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
  839. MBBI = MBB.erase(MBBI);
  840. Changed = true;
  841. } else
  842. ++MBBI;
  843. } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr());
  844. }
  845. }
  846. return Changed;
  847. }
  848. void UserValue::extendDef(
  849. SlotIndex Idx, DbgVariableValue DbgValue,
  850. SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
  851. &LiveIntervalInfo,
  852. Optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
  853. LiveIntervals &LIS) {
  854. SlotIndex Start = Idx;
  855. MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
  856. SlotIndex Stop = LIS.getMBBEndIdx(MBB);
  857. LocMap::iterator I = locInts.find(Start);
  858. // Limit to the intersection of the VNIs' live ranges.
  859. for (auto &LII : LiveIntervalInfo) {
  860. LiveRange *LR = LII.second.first;
  861. assert(LR && LII.second.second && "Missing range info for Idx.");
  862. LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
  863. assert(Segment && Segment->valno == LII.second.second &&
  864. "Invalid VNInfo for Idx given?");
  865. if (Segment->end < Stop) {
  866. Stop = Segment->end;
  867. Kills = {Stop, {LII.first}};
  868. } else if (Segment->end == Stop && Kills.hasValue()) {
  869. // If multiple locations end at the same place, track all of them in
  870. // Kills.
  871. Kills->second.push_back(LII.first);
  872. }
  873. }
  874. // There could already be a short def at Start.
  875. if (I.valid() && I.start() <= Start) {
  876. // Stop when meeting a different location or an already extended interval.
  877. Start = Start.getNextSlot();
  878. if (I.value() != DbgValue || I.stop() != Start) {
  879. // Clear `Kills`, as we have a new def available.
  880. Kills = None;
  881. return;
  882. }
  883. // This is a one-slot placeholder. Just skip it.
  884. ++I;
  885. }
  886. // Limited by the next def.
  887. if (I.valid() && I.start() < Stop) {
  888. Stop = I.start();
  889. // Clear `Kills`, as we have a new def available.
  890. Kills = None;
  891. }
  892. if (Start < Stop) {
  893. DbgVariableValue ExtDbgValue(DbgValue);
  894. I.insert(Start, Stop, std::move(ExtDbgValue));
  895. }
  896. }
  897. void UserValue::addDefsFromCopies(
  898. DbgVariableValue DbgValue,
  899. SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
  900. SlotIndex KilledAt,
  901. SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
  902. MachineRegisterInfo &MRI, LiveIntervals &LIS) {
  903. // Don't track copies from physregs, there are too many uses.
  904. if (any_of(LocIntervals, [](auto LocI) {
  905. return !Register::isVirtualRegister(LocI.second->reg());
  906. }))
  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 (!Register::isVirtualRegister(DstReg))
  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() || !Register::isVirtualRegister(LocMO.getReg())) {
  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. 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() &&
  1352. Register::isVirtualRegister(Loc.getReg())) {
  1353. Register VirtReg = Loc.getReg();
  1354. if (VRM.isAssignedReg(VirtReg) &&
  1355. Register::isPhysicalRegister(VRM.getPhys(VirtReg))) {
  1356. // This can create a %noreg operand in rare cases when the sub-register
  1357. // index is no longer available. That means the user value is in a
  1358. // non-existent sub-register, and %noreg is exactly what we want.
  1359. Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
  1360. } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
  1361. // Retrieve the stack slot offset.
  1362. unsigned SpillSize;
  1363. const MachineRegisterInfo &MRI = MF.getRegInfo();
  1364. const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
  1365. bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
  1366. SpillOffset, MF);
  1367. // FIXME: Invalidate the location if the offset couldn't be calculated.
  1368. (void)Success;
  1369. Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
  1370. Spilled = true;
  1371. } else {
  1372. Loc.setReg(0);
  1373. Loc.setSubReg(0);
  1374. }
  1375. }
  1376. // Insert this location if it doesn't already exist and record a mapping
  1377. // from the old number to the new number.
  1378. auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
  1379. unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
  1380. LocNoMap[I] = NewLocNo;
  1381. }
  1382. // Rewrite the locations and record the stack slot offsets for spills.
  1383. locations.clear();
  1384. SpillOffsets.clear();
  1385. for (auto &Pair : NewLocations) {
  1386. bool Spilled;
  1387. unsigned SpillOffset;
  1388. std::tie(Spilled, SpillOffset) = Pair.second;
  1389. locations.push_back(Pair.first);
  1390. if (Spilled) {
  1391. unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
  1392. SpillOffsets[NewLocNo] = SpillOffset;
  1393. }
  1394. }
  1395. // Update the interval map, but only coalesce left, since intervals to the
  1396. // right use the old location numbers. This should merge two contiguous
  1397. // DBG_VALUE intervals with different vregs that were allocated to the same
  1398. // physical register.
  1399. for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
  1400. I.setValueUnchecked(I.value().remapLocNos(LocNoMap));
  1401. I.setStart(I.start());
  1402. }
  1403. }
  1404. /// Find an iterator for inserting a DBG_VALUE instruction.
  1405. static MachineBasicBlock::iterator
  1406. findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS,
  1407. BlockSkipInstsMap &BBSkipInstsMap) {
  1408. SlotIndex Start = LIS.getMBBStartIdx(MBB);
  1409. Idx = Idx.getBaseIndex();
  1410. // Try to find an insert location by going backwards from Idx.
  1411. MachineInstr *MI;
  1412. while (!(MI = LIS.getInstructionFromIndex(Idx))) {
  1413. // We've reached the beginning of MBB.
  1414. if (Idx == Start) {
  1415. // Retrieve the last PHI/Label/Debug location found when calling
  1416. // SkipPHIsLabelsAndDebug last time. Start searching from there.
  1417. //
  1418. // Note the iterator kept in BBSkipInstsMap is one step back based
  1419. // on the iterator returned by SkipPHIsLabelsAndDebug last time.
  1420. // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(),
  1421. // BBSkipInstsMap won't save it. This is to consider the case that
  1422. // new instructions may be inserted at the beginning of MBB after
  1423. // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in
  1424. // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions
  1425. // are inserted at the beginning of the MBB, the iterator in
  1426. // BBSkipInstsMap won't point to the beginning of the MBB anymore.
  1427. // Therefore The next search in SkipPHIsLabelsAndDebug will skip those
  1428. // newly added instructions and that is unwanted.
  1429. MachineBasicBlock::iterator BeginIt;
  1430. auto MapIt = BBSkipInstsMap.find(MBB);
  1431. if (MapIt == BBSkipInstsMap.end())
  1432. BeginIt = MBB->begin();
  1433. else
  1434. BeginIt = std::next(MapIt->second);
  1435. auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt);
  1436. if (I != BeginIt)
  1437. BBSkipInstsMap[MBB] = std::prev(I);
  1438. return I;
  1439. }
  1440. Idx = Idx.getPrevIndex();
  1441. }
  1442. // Don't insert anything after the first terminator, though.
  1443. return MI->isTerminator() ? MBB->getFirstTerminator() :
  1444. std::next(MachineBasicBlock::iterator(MI));
  1445. }
  1446. /// Find an iterator for inserting the next DBG_VALUE instruction
  1447. /// (or end if no more insert locations found).
  1448. static MachineBasicBlock::iterator
  1449. findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I,
  1450. SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs,
  1451. LiveIntervals &LIS, const TargetRegisterInfo &TRI) {
  1452. SmallVector<Register, 4> Regs;
  1453. for (const MachineOperand &LocMO : LocMOs)
  1454. if (LocMO.isReg())
  1455. Regs.push_back(LocMO.getReg());
  1456. if (Regs.empty())
  1457. return MBB->instr_end();
  1458. // Find the next instruction in the MBB that define the register Reg.
  1459. while (I != MBB->end() && !I->isTerminator()) {
  1460. if (!LIS.isNotInMIMap(*I) &&
  1461. SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
  1462. break;
  1463. if (any_of(Regs, [&I, &TRI](Register &Reg) {
  1464. return I->definesRegister(Reg, &TRI);
  1465. }))
  1466. // The insert location is directly after the instruction/bundle.
  1467. return std::next(I);
  1468. ++I;
  1469. }
  1470. return MBB->end();
  1471. }
  1472. void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
  1473. SlotIndex StopIdx, DbgVariableValue DbgValue,
  1474. ArrayRef<bool> LocSpills,
  1475. ArrayRef<unsigned> SpillOffsets,
  1476. LiveIntervals &LIS, const TargetInstrInfo &TII,
  1477. const TargetRegisterInfo &TRI,
  1478. BlockSkipInstsMap &BBSkipInstsMap) {
  1479. SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
  1480. // Only search within the current MBB.
  1481. StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
  1482. MachineBasicBlock::iterator I =
  1483. findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap);
  1484. // Undef values don't exist in locations so create new "noreg" register MOs
  1485. // for them. See getLocationNo().
  1486. SmallVector<MachineOperand, 8> MOs;
  1487. if (DbgValue.isUndef()) {
  1488. MOs.assign(DbgValue.loc_nos().size(),
  1489. MachineOperand::CreateReg(
  1490. /* Reg */ 0, /* isDef */ false, /* isImp */ false,
  1491. /* isKill */ false, /* isDead */ false,
  1492. /* isUndef */ false, /* isEarlyClobber */ false,
  1493. /* SubReg */ 0, /* isDebug */ true));
  1494. } else {
  1495. for (unsigned LocNo : DbgValue.loc_nos())
  1496. MOs.push_back(locations[LocNo]);
  1497. }
  1498. ++NumInsertedDebugValues;
  1499. assert(cast<DILocalVariable>(Variable)
  1500. ->isValidLocationForIntrinsic(getDebugLoc()) &&
  1501. "Expected inlined-at fields to agree");
  1502. // If the location was spilled, the new DBG_VALUE will be indirect. If the
  1503. // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
  1504. // that the original virtual register was a pointer. Also, add the stack slot
  1505. // offset for the spilled register to the expression.
  1506. const DIExpression *Expr = DbgValue.getExpression();
  1507. bool IsIndirect = DbgValue.getWasIndirect();
  1508. bool IsList = DbgValue.getWasList();
  1509. for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) {
  1510. if (LocSpills[I]) {
  1511. if (!IsList) {
  1512. uint8_t DIExprFlags = DIExpression::ApplyOffset;
  1513. if (IsIndirect)
  1514. DIExprFlags |= DIExpression::DerefAfter;
  1515. Expr = DIExpression::prepend(Expr, DIExprFlags, SpillOffsets[I]);
  1516. IsIndirect = true;
  1517. } else {
  1518. SmallVector<uint64_t, 4> Ops;
  1519. DIExpression::appendOffset(Ops, SpillOffsets[I]);
  1520. Ops.push_back(dwarf::DW_OP_deref);
  1521. Expr = DIExpression::appendOpsToArg(Expr, Ops, I);
  1522. }
  1523. }
  1524. assert((!LocSpills[I] || MOs[I].isFI()) &&
  1525. "a spilled location must be a frame index");
  1526. }
  1527. unsigned DbgValueOpcode =
  1528. IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE;
  1529. do {
  1530. BuildMI(*MBB, I, getDebugLoc(), TII.get(DbgValueOpcode), IsIndirect, MOs,
  1531. Variable, Expr);
  1532. // Continue and insert DBG_VALUES after every redefinition of a register
  1533. // associated with the debug value within the range
  1534. I = findNextInsertLocation(MBB, I, StopIdx, MOs, LIS, TRI);
  1535. } while (I != MBB->end());
  1536. }
  1537. void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
  1538. LiveIntervals &LIS, const TargetInstrInfo &TII,
  1539. BlockSkipInstsMap &BBSkipInstsMap) {
  1540. MachineBasicBlock::iterator I =
  1541. findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap);
  1542. ++NumInsertedDebugLabels;
  1543. BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
  1544. .addMetadata(Label);
  1545. }
  1546. void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
  1547. const TargetInstrInfo &TII,
  1548. const TargetRegisterInfo &TRI,
  1549. const SpillOffsetMap &SpillOffsets,
  1550. BlockSkipInstsMap &BBSkipInstsMap) {
  1551. MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
  1552. for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
  1553. SlotIndex Start = I.start();
  1554. SlotIndex Stop = I.stop();
  1555. DbgVariableValue DbgValue = I.value();
  1556. SmallVector<bool> SpilledLocs;
  1557. SmallVector<unsigned> LocSpillOffsets;
  1558. for (unsigned LocNo : DbgValue.loc_nos()) {
  1559. auto SpillIt =
  1560. !DbgValue.isUndef() ? SpillOffsets.find(LocNo) : SpillOffsets.end();
  1561. bool Spilled = SpillIt != SpillOffsets.end();
  1562. SpilledLocs.push_back(Spilled);
  1563. LocSpillOffsets.push_back(Spilled ? SpillIt->second : 0);
  1564. }
  1565. // If the interval start was trimmed to the lexical scope insert the
  1566. // DBG_VALUE at the previous index (otherwise it appears after the
  1567. // first instruction in the range).
  1568. if (trimmedDefs.count(Start))
  1569. Start = Start.getPrevIndex();
  1570. LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):";
  1571. DbgValue.printLocNos(dbg));
  1572. MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
  1573. SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
  1574. LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
  1575. insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, LocSpillOffsets,
  1576. LIS, TII, TRI, BBSkipInstsMap);
  1577. // This interval may span multiple basic blocks.
  1578. // Insert a DBG_VALUE into each one.
  1579. while (Stop > MBBEnd) {
  1580. // Move to the next block.
  1581. Start = MBBEnd;
  1582. if (++MBB == MFEnd)
  1583. break;
  1584. MBBEnd = LIS.getMBBEndIdx(&*MBB);
  1585. LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
  1586. insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs,
  1587. LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap);
  1588. }
  1589. LLVM_DEBUG(dbgs() << '\n');
  1590. if (MBB == MFEnd)
  1591. break;
  1592. ++I;
  1593. }
  1594. }
  1595. void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
  1596. BlockSkipInstsMap &BBSkipInstsMap) {
  1597. LLVM_DEBUG(dbgs() << "\t" << loc);
  1598. MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator();
  1599. LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
  1600. insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap);
  1601. LLVM_DEBUG(dbgs() << '\n');
  1602. }
  1603. void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
  1604. LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
  1605. if (!MF)
  1606. return;
  1607. BlockSkipInstsMap BBSkipInstsMap;
  1608. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  1609. SpillOffsetMap SpillOffsets;
  1610. for (auto &userValue : userValues) {
  1611. LLVM_DEBUG(userValue->print(dbgs(), TRI));
  1612. userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
  1613. userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets,
  1614. BBSkipInstsMap);
  1615. }
  1616. LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
  1617. for (auto &userLabel : userLabels) {
  1618. LLVM_DEBUG(userLabel->print(dbgs(), TRI));
  1619. userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap);
  1620. }
  1621. LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n");
  1622. auto Slots = LIS->getSlotIndexes();
  1623. for (auto &It : PHIValToPos) {
  1624. // For each ex-PHI, identify its physreg location or stack slot, and emit
  1625. // a DBG_PHI for it.
  1626. unsigned InstNum = It.first;
  1627. auto Slot = It.second.SI;
  1628. Register Reg = It.second.Reg;
  1629. unsigned SubReg = It.second.SubReg;
  1630. MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(Slot);
  1631. if (VRM->isAssignedReg(Reg) &&
  1632. Register::isPhysicalRegister(VRM->getPhys(Reg))) {
  1633. unsigned PhysReg = VRM->getPhys(Reg);
  1634. if (SubReg != 0)
  1635. PhysReg = TRI->getSubReg(PhysReg, SubReg);
  1636. auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
  1637. TII->get(TargetOpcode::DBG_PHI));
  1638. Builder.addReg(PhysReg);
  1639. Builder.addImm(InstNum);
  1640. } else if (VRM->getStackSlot(Reg) != VirtRegMap::NO_STACK_SLOT) {
  1641. const MachineRegisterInfo &MRI = MF->getRegInfo();
  1642. const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
  1643. unsigned SpillSize, SpillOffset;
  1644. // Test whether this location is legal with the given subreg.
  1645. bool Success =
  1646. TII->getStackSlotRange(TRC, SubReg, SpillSize, SpillOffset, *MF);
  1647. if (Success) {
  1648. auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
  1649. TII->get(TargetOpcode::DBG_PHI));
  1650. Builder.addFrameIndex(VRM->getStackSlot(Reg));
  1651. Builder.addImm(InstNum);
  1652. }
  1653. }
  1654. // If there was no mapping for a value ID, it's optimized out. Create no
  1655. // DBG_PHI, and any variables using this value will become optimized out.
  1656. }
  1657. MF->DebugPHIPositions.clear();
  1658. LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
  1659. // Re-insert any debug instrs back in the position they were. We must
  1660. // re-insert in the same order to ensure that debug instructions don't swap,
  1661. // which could re-order assignments. Do so in a batch -- once we find the
  1662. // insert position, insert all instructions at the same SlotIdx. They are
  1663. // guaranteed to appear in-sequence in StashedDebugInstrs because we insert
  1664. // them in order.
  1665. for (auto StashIt = StashedDebugInstrs.begin();
  1666. StashIt != StashedDebugInstrs.end(); ++StashIt) {
  1667. SlotIndex Idx = StashIt->Idx;
  1668. MachineBasicBlock *MBB = StashIt->MBB;
  1669. MachineInstr *MI = StashIt->MI;
  1670. auto EmitInstsHere = [this, &StashIt, MBB, Idx,
  1671. MI](MachineBasicBlock::iterator InsertPos) {
  1672. // Insert this debug instruction.
  1673. MBB->insert(InsertPos, MI);
  1674. // Look at subsequent stashed debug instructions: if they're at the same
  1675. // index, insert those too.
  1676. auto NextItem = std::next(StashIt);
  1677. while (NextItem != StashedDebugInstrs.end() && NextItem->Idx == Idx) {
  1678. assert(NextItem->MBB == MBB && "Instrs with same slot index should be"
  1679. "in the same block");
  1680. MBB->insert(InsertPos, NextItem->MI);
  1681. StashIt = NextItem;
  1682. NextItem = std::next(StashIt);
  1683. };
  1684. };
  1685. // Start block index: find the first non-debug instr in the block, and
  1686. // insert before it.
  1687. if (Idx == Slots->getMBBStartIdx(MBB)) {
  1688. MachineBasicBlock::iterator InsertPos =
  1689. findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap);
  1690. EmitInstsHere(InsertPos);
  1691. continue;
  1692. }
  1693. if (MachineInstr *Pos = Slots->getInstructionFromIndex(Idx)) {
  1694. // Insert at the end of any debug instructions.
  1695. auto PostDebug = std::next(Pos->getIterator());
  1696. PostDebug = skipDebugInstructionsForward(PostDebug, MBB->instr_end());
  1697. EmitInstsHere(PostDebug);
  1698. } else {
  1699. // Insert position disappeared; walk forwards through slots until we
  1700. // find a new one.
  1701. SlotIndex End = Slots->getMBBEndIdx(MBB);
  1702. for (; Idx < End; Idx = Slots->getNextNonNullIndex(Idx)) {
  1703. Pos = Slots->getInstructionFromIndex(Idx);
  1704. if (Pos) {
  1705. EmitInstsHere(Pos->getIterator());
  1706. break;
  1707. }
  1708. }
  1709. // We have reached the end of the block and didn't find anywhere to
  1710. // insert! It's not safe to discard any debug instructions; place them
  1711. // in front of the first terminator, or in front of end().
  1712. if (Idx >= End) {
  1713. auto TermIt = MBB->getFirstTerminator();
  1714. EmitInstsHere(TermIt);
  1715. }
  1716. }
  1717. }
  1718. EmitDone = true;
  1719. BBSkipInstsMap.clear();
  1720. }
  1721. void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
  1722. if (pImpl)
  1723. static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
  1724. }
  1725. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1726. LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
  1727. if (pImpl)
  1728. static_cast<LDVImpl*>(pImpl)->print(dbgs());
  1729. }
  1730. #endif