InstrRefBasedImpl.h 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. //===- InstrRefBasedImpl.h - Tracking Debug Value MIs ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H
  9. #define LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H
  10. #include "llvm/ADT/DenseMap.h"
  11. #include "llvm/ADT/SmallPtrSet.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/ADT/UniqueVector.h"
  14. #include "llvm/CodeGen/LexicalScopes.h"
  15. #include "llvm/CodeGen/MachineBasicBlock.h"
  16. #include "llvm/CodeGen/MachineFrameInfo.h"
  17. #include "llvm/CodeGen/MachineFunction.h"
  18. #include "llvm/CodeGen/MachineInstr.h"
  19. #include "llvm/CodeGen/TargetFrameLowering.h"
  20. #include "llvm/CodeGen/TargetInstrInfo.h"
  21. #include "llvm/CodeGen/TargetPassConfig.h"
  22. #include "llvm/IR/DebugInfoMetadata.h"
  23. #include "LiveDebugValues.h"
  24. class TransferTracker;
  25. // Forward dec of unit test class, so that we can peer into the LDV object.
  26. class InstrRefLDVTest;
  27. namespace LiveDebugValues {
  28. class MLocTracker;
  29. using namespace llvm;
  30. /// Handle-class for a particular "location". This value-type uniquely
  31. /// symbolises a register or stack location, allowing manipulation of locations
  32. /// without concern for where that location is. Practically, this allows us to
  33. /// treat the state of the machine at a particular point as an array of values,
  34. /// rather than a map of values.
  35. class LocIdx {
  36. unsigned Location;
  37. // Default constructor is private, initializing to an illegal location number.
  38. // Use only for "not an entry" elements in IndexedMaps.
  39. LocIdx() : Location(UINT_MAX) {}
  40. public:
  41. #define NUM_LOC_BITS 24
  42. LocIdx(unsigned L) : Location(L) {
  43. assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits");
  44. }
  45. static LocIdx MakeIllegalLoc() { return LocIdx(); }
  46. static LocIdx MakeTombstoneLoc() {
  47. LocIdx L = LocIdx();
  48. --L.Location;
  49. return L;
  50. }
  51. bool isIllegal() const { return Location == UINT_MAX; }
  52. uint64_t asU64() const { return Location; }
  53. bool operator==(unsigned L) const { return Location == L; }
  54. bool operator==(const LocIdx &L) const { return Location == L.Location; }
  55. bool operator!=(unsigned L) const { return !(*this == L); }
  56. bool operator!=(const LocIdx &L) const { return !(*this == L); }
  57. bool operator<(const LocIdx &Other) const {
  58. return Location < Other.Location;
  59. }
  60. };
  61. // The location at which a spilled value resides. It consists of a register and
  62. // an offset.
  63. struct SpillLoc {
  64. unsigned SpillBase;
  65. StackOffset SpillOffset;
  66. bool operator==(const SpillLoc &Other) const {
  67. return std::make_pair(SpillBase, SpillOffset) ==
  68. std::make_pair(Other.SpillBase, Other.SpillOffset);
  69. }
  70. bool operator<(const SpillLoc &Other) const {
  71. return std::make_tuple(SpillBase, SpillOffset.getFixed(),
  72. SpillOffset.getScalable()) <
  73. std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(),
  74. Other.SpillOffset.getScalable());
  75. }
  76. };
  77. /// Unique identifier for a value defined by an instruction, as a value type.
  78. /// Casts back and forth to a uint64_t. Probably replacable with something less
  79. /// bit-constrained. Each value identifies the instruction and machine location
  80. /// where the value is defined, although there may be no corresponding machine
  81. /// operand for it (ex: regmasks clobbering values). The instructions are
  82. /// one-based, and definitions that are PHIs have instruction number zero.
  83. ///
  84. /// The obvious limits of a 1M block function or 1M instruction blocks are
  85. /// problematic; but by that point we should probably have bailed out of
  86. /// trying to analyse the function.
  87. class ValueIDNum {
  88. union {
  89. struct {
  90. uint64_t BlockNo : 20; /// The block where the def happens.
  91. uint64_t InstNo : 20; /// The Instruction where the def happens.
  92. /// One based, is distance from start of block.
  93. uint64_t LocNo
  94. : NUM_LOC_BITS; /// The machine location where the def happens.
  95. } s;
  96. uint64_t Value;
  97. } u;
  98. static_assert(sizeof(u) == 8, "Badly packed ValueIDNum?");
  99. public:
  100. // Default-initialize to EmptyValue. This is necessary to make IndexedMaps
  101. // of values to work.
  102. ValueIDNum() { u.Value = EmptyValue.asU64(); }
  103. ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc) {
  104. u.s = {Block, Inst, Loc};
  105. }
  106. ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc) {
  107. u.s = {Block, Inst, Loc.asU64()};
  108. }
  109. uint64_t getBlock() const { return u.s.BlockNo; }
  110. uint64_t getInst() const { return u.s.InstNo; }
  111. uint64_t getLoc() const { return u.s.LocNo; }
  112. bool isPHI() const { return u.s.InstNo == 0; }
  113. uint64_t asU64() const { return u.Value; }
  114. static ValueIDNum fromU64(uint64_t v) {
  115. ValueIDNum Val;
  116. Val.u.Value = v;
  117. return Val;
  118. }
  119. bool operator<(const ValueIDNum &Other) const {
  120. return asU64() < Other.asU64();
  121. }
  122. bool operator==(const ValueIDNum &Other) const {
  123. return u.Value == Other.u.Value;
  124. }
  125. bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); }
  126. std::string asString(const std::string &mlocname) const {
  127. return Twine("Value{bb: ")
  128. .concat(Twine(u.s.BlockNo)
  129. .concat(Twine(", inst: ")
  130. .concat((u.s.InstNo ? Twine(u.s.InstNo)
  131. : Twine("live-in"))
  132. .concat(Twine(", loc: ").concat(
  133. Twine(mlocname)))
  134. .concat(Twine("}")))))
  135. .str();
  136. }
  137. static ValueIDNum EmptyValue;
  138. static ValueIDNum TombstoneValue;
  139. };
  140. /// Thin wrapper around an integer -- designed to give more type safety to
  141. /// spill location numbers.
  142. class SpillLocationNo {
  143. public:
  144. explicit SpillLocationNo(unsigned SpillNo) : SpillNo(SpillNo) {}
  145. unsigned SpillNo;
  146. unsigned id() const { return SpillNo; }
  147. bool operator<(const SpillLocationNo &Other) const {
  148. return SpillNo < Other.SpillNo;
  149. }
  150. bool operator==(const SpillLocationNo &Other) const {
  151. return SpillNo == Other.SpillNo;
  152. }
  153. bool operator!=(const SpillLocationNo &Other) const {
  154. return !(*this == Other);
  155. }
  156. };
  157. /// Meta qualifiers for a value. Pair of whatever expression is used to qualify
  158. /// the the value, and Boolean of whether or not it's indirect.
  159. class DbgValueProperties {
  160. public:
  161. DbgValueProperties(const DIExpression *DIExpr, bool Indirect)
  162. : DIExpr(DIExpr), Indirect(Indirect) {}
  163. /// Extract properties from an existing DBG_VALUE instruction.
  164. DbgValueProperties(const MachineInstr &MI) {
  165. assert(MI.isDebugValue());
  166. DIExpr = MI.getDebugExpression();
  167. Indirect = MI.getOperand(1).isImm();
  168. }
  169. bool operator==(const DbgValueProperties &Other) const {
  170. return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect);
  171. }
  172. bool operator!=(const DbgValueProperties &Other) const {
  173. return !(*this == Other);
  174. }
  175. const DIExpression *DIExpr;
  176. bool Indirect;
  177. };
  178. /// Class recording the (high level) _value_ of a variable. Identifies either
  179. /// the value of the variable as a ValueIDNum, or a constant MachineOperand.
  180. /// This class also stores meta-information about how the value is qualified.
  181. /// Used to reason about variable values when performing the second
  182. /// (DebugVariable specific) dataflow analysis.
  183. class DbgValue {
  184. public:
  185. /// If Kind is Def, the value number that this value is based on. VPHIs set
  186. /// this field to EmptyValue if there is no machine-value for this VPHI, or
  187. /// the corresponding machine-value if there is one.
  188. ValueIDNum ID;
  189. /// If Kind is Const, the MachineOperand defining this value.
  190. Optional<MachineOperand> MO;
  191. /// For a NoVal or VPHI DbgValue, which block it was generated in.
  192. int BlockNo;
  193. /// Qualifiers for the ValueIDNum above.
  194. DbgValueProperties Properties;
  195. typedef enum {
  196. Undef, // Represents a DBG_VALUE $noreg in the transfer function only.
  197. Def, // This value is defined by an inst, or is a PHI value.
  198. Const, // A constant value contained in the MachineOperand field.
  199. VPHI, // Incoming values to BlockNo differ, those values must be joined by
  200. // a PHI in this block.
  201. NoVal, // Empty DbgValue indicating an unknown value. Used as initializer,
  202. // before dominating blocks values are propagated in.
  203. } KindT;
  204. /// Discriminator for whether this is a constant or an in-program value.
  205. KindT Kind;
  206. DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind)
  207. : ID(Val), MO(None), BlockNo(0), Properties(Prop), Kind(Kind) {
  208. assert(Kind == Def);
  209. }
  210. DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind)
  211. : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(BlockNo),
  212. Properties(Prop), Kind(Kind) {
  213. assert(Kind == NoVal || Kind == VPHI);
  214. }
  215. DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind)
  216. : ID(ValueIDNum::EmptyValue), MO(MO), BlockNo(0), Properties(Prop),
  217. Kind(Kind) {
  218. assert(Kind == Const);
  219. }
  220. DbgValue(const DbgValueProperties &Prop, KindT Kind)
  221. : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(0), Properties(Prop),
  222. Kind(Kind) {
  223. assert(Kind == Undef &&
  224. "Empty DbgValue constructor must pass in Undef kind");
  225. }
  226. #ifndef NDEBUG
  227. void dump(const MLocTracker *MTrack) const;
  228. #endif
  229. bool operator==(const DbgValue &Other) const {
  230. if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties))
  231. return false;
  232. else if (Kind == Def && ID != Other.ID)
  233. return false;
  234. else if (Kind == NoVal && BlockNo != Other.BlockNo)
  235. return false;
  236. else if (Kind == Const)
  237. return MO->isIdenticalTo(*Other.MO);
  238. else if (Kind == VPHI && BlockNo != Other.BlockNo)
  239. return false;
  240. else if (Kind == VPHI && ID != Other.ID)
  241. return false;
  242. return true;
  243. }
  244. bool operator!=(const DbgValue &Other) const { return !(*this == Other); }
  245. };
  246. class LocIdxToIndexFunctor {
  247. public:
  248. using argument_type = LocIdx;
  249. unsigned operator()(const LocIdx &L) const { return L.asU64(); }
  250. };
  251. /// Tracker for what values are in machine locations. Listens to the Things
  252. /// being Done by various instructions, and maintains a table of what machine
  253. /// locations have what values (as defined by a ValueIDNum).
  254. ///
  255. /// There are potentially a much larger number of machine locations on the
  256. /// target machine than the actual working-set size of the function. On x86 for
  257. /// example, we're extremely unlikely to want to track values through control
  258. /// or debug registers. To avoid doing so, MLocTracker has several layers of
  259. /// indirection going on, described below, to avoid unnecessarily tracking
  260. /// any location.
  261. ///
  262. /// Here's a sort of diagram of the indexes, read from the bottom up:
  263. ///
  264. /// Size on stack Offset on stack
  265. /// \ /
  266. /// Stack Idx (Where in slot is this?)
  267. /// /
  268. /// /
  269. /// Slot Num (%stack.0) /
  270. /// FrameIdx => SpillNum /
  271. /// \ /
  272. /// SpillID (int) Register number (int)
  273. /// \ /
  274. /// LocationID => LocIdx
  275. /// |
  276. /// LocIdx => ValueIDNum
  277. ///
  278. /// The aim here is that the LocIdx => ValueIDNum vector is just an array of
  279. /// values in numbered locations, so that later analyses can ignore whether the
  280. /// location is a register or otherwise. To map a register / spill location to
  281. /// a LocIdx, you have to use the (sparse) LocationID => LocIdx map. And to
  282. /// build a LocationID for a stack slot, you need to combine identifiers for
  283. /// which stack slot it is and where within that slot is being described.
  284. ///
  285. /// Register mask operands cause trouble by technically defining every register;
  286. /// various hacks are used to avoid tracking registers that are never read and
  287. /// only written by regmasks.
  288. class MLocTracker {
  289. public:
  290. MachineFunction &MF;
  291. const TargetInstrInfo &TII;
  292. const TargetRegisterInfo &TRI;
  293. const TargetLowering &TLI;
  294. /// IndexedMap type, mapping from LocIdx to ValueIDNum.
  295. using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>;
  296. /// Map of LocIdxes to the ValueIDNums that they store. This is tightly
  297. /// packed, entries only exist for locations that are being tracked.
  298. LocToValueType LocIdxToIDNum;
  299. /// "Map" of machine location IDs (i.e., raw register or spill number) to the
  300. /// LocIdx key / number for that location. There are always at least as many
  301. /// as the number of registers on the target -- if the value in the register
  302. /// is not being tracked, then the LocIdx value will be zero. New entries are
  303. /// appended if a new spill slot begins being tracked.
  304. /// This, and the corresponding reverse map persist for the analysis of the
  305. /// whole function, and is necessarying for decoding various vectors of
  306. /// values.
  307. std::vector<LocIdx> LocIDToLocIdx;
  308. /// Inverse map of LocIDToLocIdx.
  309. IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID;
  310. /// When clobbering register masks, we chose to not believe the machine model
  311. /// and don't clobber SP. Do the same for SP aliases, and for efficiency,
  312. /// keep a set of them here.
  313. SmallSet<Register, 8> SPAliases;
  314. /// Unique-ification of spill. Used to number them -- their LocID number is
  315. /// the index in SpillLocs minus one plus NumRegs.
  316. UniqueVector<SpillLoc> SpillLocs;
  317. // If we discover a new machine location, assign it an mphi with this
  318. // block number.
  319. unsigned CurBB;
  320. /// Cached local copy of the number of registers the target has.
  321. unsigned NumRegs;
  322. /// Number of slot indexes the target has -- distinct segments of a stack
  323. /// slot that can take on the value of a subregister, when a super-register
  324. /// is written to the stack.
  325. unsigned NumSlotIdxes;
  326. /// Collection of register mask operands that have been observed. Second part
  327. /// of pair indicates the instruction that they happened in. Used to
  328. /// reconstruct where defs happened if we start tracking a location later
  329. /// on.
  330. SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks;
  331. /// Pair for describing a position within a stack slot -- first the size in
  332. /// bits, then the offset.
  333. typedef std::pair<unsigned short, unsigned short> StackSlotPos;
  334. /// Map from a size/offset pair describing a position in a stack slot, to a
  335. /// numeric identifier for that position. Allows easier identification of
  336. /// individual positions.
  337. DenseMap<StackSlotPos, unsigned> StackSlotIdxes;
  338. /// Inverse of StackSlotIdxes.
  339. DenseMap<unsigned, StackSlotPos> StackIdxesToPos;
  340. /// Iterator for locations and the values they contain. Dereferencing
  341. /// produces a struct/pair containing the LocIdx key for this location,
  342. /// and a reference to the value currently stored. Simplifies the process
  343. /// of seeking a particular location.
  344. class MLocIterator {
  345. LocToValueType &ValueMap;
  346. LocIdx Idx;
  347. public:
  348. class value_type {
  349. public:
  350. value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) {}
  351. const LocIdx Idx; /// Read-only index of this location.
  352. ValueIDNum &Value; /// Reference to the stored value at this location.
  353. };
  354. MLocIterator(LocToValueType &ValueMap, LocIdx Idx)
  355. : ValueMap(ValueMap), Idx(Idx) {}
  356. bool operator==(const MLocIterator &Other) const {
  357. assert(&ValueMap == &Other.ValueMap);
  358. return Idx == Other.Idx;
  359. }
  360. bool operator!=(const MLocIterator &Other) const {
  361. return !(*this == Other);
  362. }
  363. void operator++() { Idx = LocIdx(Idx.asU64() + 1); }
  364. value_type operator*() { return value_type(Idx, ValueMap[LocIdx(Idx)]); }
  365. };
  366. MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
  367. const TargetRegisterInfo &TRI, const TargetLowering &TLI);
  368. /// Produce location ID number for a Register. Provides some small amount of
  369. /// type safety.
  370. /// \param Reg The register we're looking up.
  371. unsigned getLocID(Register Reg) { return Reg.id(); }
  372. /// Produce location ID number for a spill position.
  373. /// \param Spill The number of the spill we're fetching the location for.
  374. /// \param SpillSubReg Subregister within the spill we're addressing.
  375. unsigned getLocID(SpillLocationNo Spill, unsigned SpillSubReg) {
  376. unsigned short Size = TRI.getSubRegIdxSize(SpillSubReg);
  377. unsigned short Offs = TRI.getSubRegIdxOffset(SpillSubReg);
  378. return getLocID(Spill, {Size, Offs});
  379. }
  380. /// Produce location ID number for a spill position.
  381. /// \param Spill The number of the spill we're fetching the location for.
  382. /// \apram SpillIdx size/offset within the spill slot to be addressed.
  383. unsigned getLocID(SpillLocationNo Spill, StackSlotPos Idx) {
  384. unsigned SlotNo = Spill.id() - 1;
  385. SlotNo *= NumSlotIdxes;
  386. assert(StackSlotIdxes.find(Idx) != StackSlotIdxes.end());
  387. SlotNo += StackSlotIdxes[Idx];
  388. SlotNo += NumRegs;
  389. return SlotNo;
  390. }
  391. /// Given a spill number, and a slot within the spill, calculate the ID number
  392. /// for that location.
  393. unsigned getSpillIDWithIdx(SpillLocationNo Spill, unsigned Idx) {
  394. unsigned SlotNo = Spill.id() - 1;
  395. SlotNo *= NumSlotIdxes;
  396. SlotNo += Idx;
  397. SlotNo += NumRegs;
  398. return SlotNo;
  399. }
  400. /// Return the spill number that a location ID corresponds to.
  401. SpillLocationNo locIDToSpill(unsigned ID) const {
  402. assert(ID >= NumRegs);
  403. ID -= NumRegs;
  404. // Truncate away the index part, leaving only the spill number.
  405. ID /= NumSlotIdxes;
  406. return SpillLocationNo(ID + 1); // The UniqueVector is one-based.
  407. }
  408. /// Returns the spill-slot size/offs that a location ID corresponds to.
  409. StackSlotPos locIDToSpillIdx(unsigned ID) const {
  410. assert(ID >= NumRegs);
  411. ID -= NumRegs;
  412. unsigned Idx = ID % NumSlotIdxes;
  413. return StackIdxesToPos.find(Idx)->second;
  414. }
  415. unsigned getNumLocs() const { return LocIdxToIDNum.size(); }
  416. /// Reset all locations to contain a PHI value at the designated block. Used
  417. /// sometimes for actual PHI values, othertimes to indicate the block entry
  418. /// value (before any more information is known).
  419. void setMPhis(unsigned NewCurBB) {
  420. CurBB = NewCurBB;
  421. for (auto Location : locations())
  422. Location.Value = {CurBB, 0, Location.Idx};
  423. }
  424. /// Load values for each location from array of ValueIDNums. Take current
  425. /// bbnum just in case we read a value from a hitherto untouched register.
  426. void loadFromArray(ValueIDNum *Locs, unsigned NewCurBB) {
  427. CurBB = NewCurBB;
  428. // Iterate over all tracked locations, and load each locations live-in
  429. // value into our local index.
  430. for (auto Location : locations())
  431. Location.Value = Locs[Location.Idx.asU64()];
  432. }
  433. /// Wipe any un-necessary location records after traversing a block.
  434. void reset() {
  435. // We could reset all the location values too; however either loadFromArray
  436. // or setMPhis should be called before this object is re-used. Just
  437. // clear Masks, they're definitely not needed.
  438. Masks.clear();
  439. }
  440. /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of
  441. /// the information in this pass uninterpretable.
  442. void clear() {
  443. reset();
  444. LocIDToLocIdx.clear();
  445. LocIdxToLocID.clear();
  446. LocIdxToIDNum.clear();
  447. // SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from
  448. // 0
  449. SpillLocs = decltype(SpillLocs)();
  450. StackSlotIdxes.clear();
  451. StackIdxesToPos.clear();
  452. LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
  453. }
  454. /// Set a locaiton to a certain value.
  455. void setMLoc(LocIdx L, ValueIDNum Num) {
  456. assert(L.asU64() < LocIdxToIDNum.size());
  457. LocIdxToIDNum[L] = Num;
  458. }
  459. /// Read the value of a particular location
  460. ValueIDNum readMLoc(LocIdx L) {
  461. assert(L.asU64() < LocIdxToIDNum.size());
  462. return LocIdxToIDNum[L];
  463. }
  464. /// Create a LocIdx for an untracked register ID. Initialize it to either an
  465. /// mphi value representing a live-in, or a recent register mask clobber.
  466. LocIdx trackRegister(unsigned ID);
  467. LocIdx lookupOrTrackRegister(unsigned ID) {
  468. LocIdx &Index = LocIDToLocIdx[ID];
  469. if (Index.isIllegal())
  470. Index = trackRegister(ID);
  471. return Index;
  472. }
  473. /// Is register R currently tracked by MLocTracker?
  474. bool isRegisterTracked(Register R) {
  475. LocIdx &Index = LocIDToLocIdx[R];
  476. return !Index.isIllegal();
  477. }
  478. /// Record a definition of the specified register at the given block / inst.
  479. /// This doesn't take a ValueIDNum, because the definition and its location
  480. /// are synonymous.
  481. void defReg(Register R, unsigned BB, unsigned Inst) {
  482. unsigned ID = getLocID(R);
  483. LocIdx Idx = lookupOrTrackRegister(ID);
  484. ValueIDNum ValueID = {BB, Inst, Idx};
  485. LocIdxToIDNum[Idx] = ValueID;
  486. }
  487. /// Set a register to a value number. To be used if the value number is
  488. /// known in advance.
  489. void setReg(Register R, ValueIDNum ValueID) {
  490. unsigned ID = getLocID(R);
  491. LocIdx Idx = lookupOrTrackRegister(ID);
  492. LocIdxToIDNum[Idx] = ValueID;
  493. }
  494. ValueIDNum readReg(Register R) {
  495. unsigned ID = getLocID(R);
  496. LocIdx Idx = lookupOrTrackRegister(ID);
  497. return LocIdxToIDNum[Idx];
  498. }
  499. /// Reset a register value to zero / empty. Needed to replicate the
  500. /// VarLoc implementation where a copy to/from a register effectively
  501. /// clears the contents of the source register. (Values can only have one
  502. /// machine location in VarLocBasedImpl).
  503. void wipeRegister(Register R) {
  504. unsigned ID = getLocID(R);
  505. LocIdx Idx = LocIDToLocIdx[ID];
  506. LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue;
  507. }
  508. /// Determine the LocIdx of an existing register.
  509. LocIdx getRegMLoc(Register R) {
  510. unsigned ID = getLocID(R);
  511. assert(ID < LocIDToLocIdx.size());
  512. assert(LocIDToLocIdx[ID] != UINT_MAX); // Sentinal for IndexedMap.
  513. return LocIDToLocIdx[ID];
  514. }
  515. /// Record a RegMask operand being executed. Defs any register we currently
  516. /// track, stores a pointer to the mask in case we have to account for it
  517. /// later.
  518. void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID);
  519. /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked.
  520. /// Returns None when in scenarios where a spill slot could be tracked, but
  521. /// we would likely run into resource limitations.
  522. Optional<SpillLocationNo> getOrTrackSpillLoc(SpillLoc L);
  523. // Get LocIdx of a spill ID.
  524. LocIdx getSpillMLoc(unsigned SpillID) {
  525. assert(LocIDToLocIdx[SpillID] != UINT_MAX); // Sentinal for IndexedMap.
  526. return LocIDToLocIdx[SpillID];
  527. }
  528. /// Return true if Idx is a spill machine location.
  529. bool isSpill(LocIdx Idx) const { return LocIdxToLocID[Idx] >= NumRegs; }
  530. MLocIterator begin() { return MLocIterator(LocIdxToIDNum, 0); }
  531. MLocIterator end() {
  532. return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size());
  533. }
  534. /// Return a range over all locations currently tracked.
  535. iterator_range<MLocIterator> locations() {
  536. return llvm::make_range(begin(), end());
  537. }
  538. std::string LocIdxToName(LocIdx Idx) const;
  539. std::string IDAsString(const ValueIDNum &Num) const;
  540. #ifndef NDEBUG
  541. LLVM_DUMP_METHOD void dump();
  542. LLVM_DUMP_METHOD void dump_mloc_map();
  543. #endif
  544. /// Create a DBG_VALUE based on machine location \p MLoc. Qualify it with the
  545. /// information in \pProperties, for variable Var. Don't insert it anywhere,
  546. /// just return the builder for it.
  547. MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var,
  548. const DbgValueProperties &Properties);
  549. };
  550. /// Types for recording sets of variable fragments that overlap. For a given
  551. /// local variable, we record all other fragments of that variable that could
  552. /// overlap it, to reduce search time.
  553. using FragmentOfVar =
  554. std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
  555. using OverlapMap =
  556. DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
  557. /// Collection of DBG_VALUEs observed when traversing a block. Records each
  558. /// variable and the value the DBG_VALUE refers to. Requires the machine value
  559. /// location dataflow algorithm to have run already, so that values can be
  560. /// identified.
  561. class VLocTracker {
  562. public:
  563. /// Map DebugVariable to the latest Value it's defined to have.
  564. /// Needs to be a MapVector because we determine order-in-the-input-MIR from
  565. /// the order in this container.
  566. /// We only retain the last DbgValue in each block for each variable, to
  567. /// determine the blocks live-out variable value. The Vars container forms the
  568. /// transfer function for this block, as part of the dataflow analysis. The
  569. /// movement of values between locations inside of a block is handled at a
  570. /// much later stage, in the TransferTracker class.
  571. MapVector<DebugVariable, DbgValue> Vars;
  572. SmallDenseMap<DebugVariable, const DILocation *, 8> Scopes;
  573. MachineBasicBlock *MBB = nullptr;
  574. const OverlapMap &OverlappingFragments;
  575. DbgValueProperties EmptyProperties;
  576. public:
  577. VLocTracker(const OverlapMap &O, const DIExpression *EmptyExpr)
  578. : OverlappingFragments(O), EmptyProperties(EmptyExpr, false) {}
  579. void defVar(const MachineInstr &MI, const DbgValueProperties &Properties,
  580. Optional<ValueIDNum> ID) {
  581. assert(MI.isDebugValue() || MI.isDebugRef());
  582. DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
  583. MI.getDebugLoc()->getInlinedAt());
  584. DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def)
  585. : DbgValue(Properties, DbgValue::Undef);
  586. // Attempt insertion; overwrite if it's already mapped.
  587. auto Result = Vars.insert(std::make_pair(Var, Rec));
  588. if (!Result.second)
  589. Result.first->second = Rec;
  590. Scopes[Var] = MI.getDebugLoc().get();
  591. considerOverlaps(Var, MI.getDebugLoc().get());
  592. }
  593. void defVar(const MachineInstr &MI, const MachineOperand &MO) {
  594. // Only DBG_VALUEs can define constant-valued variables.
  595. assert(MI.isDebugValue());
  596. DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
  597. MI.getDebugLoc()->getInlinedAt());
  598. DbgValueProperties Properties(MI);
  599. DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const);
  600. // Attempt insertion; overwrite if it's already mapped.
  601. auto Result = Vars.insert(std::make_pair(Var, Rec));
  602. if (!Result.second)
  603. Result.first->second = Rec;
  604. Scopes[Var] = MI.getDebugLoc().get();
  605. considerOverlaps(Var, MI.getDebugLoc().get());
  606. }
  607. void considerOverlaps(const DebugVariable &Var, const DILocation *Loc) {
  608. auto Overlaps = OverlappingFragments.find(
  609. {Var.getVariable(), Var.getFragmentOrDefault()});
  610. if (Overlaps == OverlappingFragments.end())
  611. return;
  612. // Otherwise: terminate any overlapped variable locations.
  613. for (auto FragmentInfo : Overlaps->second) {
  614. // The "empty" fragment is stored as DebugVariable::DefaultFragment, so
  615. // that it overlaps with everything, however its cannonical representation
  616. // in a DebugVariable is as "None".
  617. Optional<DIExpression::FragmentInfo> OptFragmentInfo = FragmentInfo;
  618. if (DebugVariable::isDefaultFragment(FragmentInfo))
  619. OptFragmentInfo = None;
  620. DebugVariable Overlapped(Var.getVariable(), OptFragmentInfo,
  621. Var.getInlinedAt());
  622. DbgValue Rec = DbgValue(EmptyProperties, DbgValue::Undef);
  623. // Attempt insertion; overwrite if it's already mapped.
  624. auto Result = Vars.insert(std::make_pair(Overlapped, Rec));
  625. if (!Result.second)
  626. Result.first->second = Rec;
  627. Scopes[Overlapped] = Loc;
  628. }
  629. }
  630. void clear() {
  631. Vars.clear();
  632. Scopes.clear();
  633. }
  634. };
  635. // XXX XXX docs
  636. class InstrRefBasedLDV : public LDVImpl {
  637. public:
  638. friend class ::InstrRefLDVTest;
  639. using FragmentInfo = DIExpression::FragmentInfo;
  640. using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
  641. // Helper while building OverlapMap, a map of all fragments seen for a given
  642. // DILocalVariable.
  643. using VarToFragments =
  644. DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
  645. /// Machine location/value transfer function, a mapping of which locations
  646. /// are assigned which new values.
  647. using MLocTransferMap = SmallDenseMap<LocIdx, ValueIDNum>;
  648. /// Live in/out structure for the variable values: a per-block map of
  649. /// variables to their values.
  650. using LiveIdxT = DenseMap<const MachineBasicBlock *, DbgValue *>;
  651. using VarAndLoc = std::pair<DebugVariable, DbgValue>;
  652. /// Type for a live-in value: the predecessor block, and its value.
  653. using InValueT = std::pair<MachineBasicBlock *, DbgValue *>;
  654. /// Vector (per block) of a collection (inner smallvector) of live-ins.
  655. /// Used as the result type for the variable value dataflow problem.
  656. using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>;
  657. /// Mapping from lexical scopes to a DILocation in that scope.
  658. using ScopeToDILocT = DenseMap<const LexicalScope *, const DILocation *>;
  659. /// Mapping from lexical scopes to variables in that scope.
  660. using ScopeToVarsT = DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>>;
  661. /// Mapping from lexical scopes to blocks where variables in that scope are
  662. /// assigned. Such blocks aren't necessarily "in" the lexical scope, it's
  663. /// just a block where an assignment happens.
  664. using ScopeToAssignBlocksT = DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>>;
  665. private:
  666. MachineDominatorTree *DomTree;
  667. const TargetRegisterInfo *TRI;
  668. const MachineRegisterInfo *MRI;
  669. const TargetInstrInfo *TII;
  670. const TargetFrameLowering *TFI;
  671. const MachineFrameInfo *MFI;
  672. BitVector CalleeSavedRegs;
  673. LexicalScopes LS;
  674. TargetPassConfig *TPC;
  675. // An empty DIExpression. Used default / placeholder DbgValueProperties
  676. // objects, as we can't have null expressions.
  677. const DIExpression *EmptyExpr;
  678. /// Object to track machine locations as we step through a block. Could
  679. /// probably be a field rather than a pointer, as it's always used.
  680. MLocTracker *MTracker = nullptr;
  681. /// Number of the current block LiveDebugValues is stepping through.
  682. unsigned CurBB;
  683. /// Number of the current instruction LiveDebugValues is evaluating.
  684. unsigned CurInst;
  685. /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl
  686. /// steps through a block. Reads the values at each location from the
  687. /// MLocTracker object.
  688. VLocTracker *VTracker = nullptr;
  689. /// Tracker for transfers, listens to DBG_VALUEs and transfers of values
  690. /// between locations during stepping, creates new DBG_VALUEs when values move
  691. /// location.
  692. TransferTracker *TTracker = nullptr;
  693. /// Blocks which are artificial, i.e. blocks which exclusively contain
  694. /// instructions without DebugLocs, or with line 0 locations.
  695. SmallPtrSet<MachineBasicBlock *, 16> ArtificialBlocks;
  696. // Mapping of blocks to and from their RPOT order.
  697. DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
  698. DenseMap<const MachineBasicBlock *, unsigned int> BBToOrder;
  699. DenseMap<unsigned, unsigned> BBNumToRPO;
  700. /// Pair of MachineInstr, and its 1-based offset into the containing block.
  701. using InstAndNum = std::pair<const MachineInstr *, unsigned>;
  702. /// Map from debug instruction number to the MachineInstr labelled with that
  703. /// number, and its location within the function. Used to transform
  704. /// instruction numbers in DBG_INSTR_REFs into machine value numbers.
  705. std::map<uint64_t, InstAndNum> DebugInstrNumToInstr;
  706. /// Record of where we observed a DBG_PHI instruction.
  707. class DebugPHIRecord {
  708. public:
  709. uint64_t InstrNum; ///< Instruction number of this DBG_PHI.
  710. MachineBasicBlock *MBB; ///< Block where DBG_PHI occurred.
  711. ValueIDNum ValueRead; ///< The value number read by the DBG_PHI.
  712. LocIdx ReadLoc; ///< Register/Stack location the DBG_PHI reads.
  713. operator unsigned() const { return InstrNum; }
  714. };
  715. /// Map from instruction numbers defined by DBG_PHIs to a record of what that
  716. /// DBG_PHI read and where. Populated and edited during the machine value
  717. /// location problem -- we use LLVMs SSA Updater to fix changes by
  718. /// optimizations that destroy PHI instructions.
  719. SmallVector<DebugPHIRecord, 32> DebugPHINumToValue;
  720. // Map of overlapping variable fragments.
  721. OverlapMap OverlapFragments;
  722. VarToFragments SeenFragments;
  723. /// Mapping of DBG_INSTR_REF instructions to their values, for those
  724. /// DBG_INSTR_REFs that call resolveDbgPHIs. These variable references solve
  725. /// a mini SSA problem caused by DBG_PHIs being cloned, this collection caches
  726. /// the result.
  727. DenseMap<MachineInstr *, Optional<ValueIDNum>> SeenDbgPHIs;
  728. /// True if we need to examine call instructions for stack clobbers. We
  729. /// normally assume that they don't clobber SP, but stack probes on Windows
  730. /// do.
  731. bool AdjustsStackInCalls = false;
  732. /// If AdjustsStackInCalls is true, this holds the name of the target's stack
  733. /// probe function, which is the function we expect will alter the stack
  734. /// pointer.
  735. StringRef StackProbeSymbolName;
  736. /// Tests whether this instruction is a spill to a stack slot.
  737. Optional<SpillLocationNo> isSpillInstruction(const MachineInstr &MI,
  738. MachineFunction *MF);
  739. /// Decide if @MI is a spill instruction and return true if it is. We use 2
  740. /// criteria to make this decision:
  741. /// - Is this instruction a store to a spill slot?
  742. /// - Is there a register operand that is both used and killed?
  743. /// TODO: Store optimization can fold spills into other stores (including
  744. /// other spills). We do not handle this yet (more than one memory operand).
  745. bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
  746. unsigned &Reg);
  747. /// If a given instruction is identified as a spill, return the spill slot
  748. /// and set \p Reg to the spilled register.
  749. Optional<SpillLocationNo> isRestoreInstruction(const MachineInstr &MI,
  750. MachineFunction *MF, unsigned &Reg);
  751. /// Given a spill instruction, extract the spill slot information, ensure it's
  752. /// tracked, and return the spill number.
  753. Optional<SpillLocationNo>
  754. extractSpillBaseRegAndOffset(const MachineInstr &MI);
  755. /// Observe a single instruction while stepping through a block.
  756. void process(MachineInstr &MI, ValueIDNum **MLiveOuts = nullptr,
  757. ValueIDNum **MLiveIns = nullptr);
  758. /// Examines whether \p MI is a DBG_VALUE and notifies trackers.
  759. /// \returns true if MI was recognized and processed.
  760. bool transferDebugValue(const MachineInstr &MI);
  761. /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers.
  762. /// \returns true if MI was recognized and processed.
  763. bool transferDebugInstrRef(MachineInstr &MI, ValueIDNum **MLiveOuts,
  764. ValueIDNum **MLiveIns);
  765. /// Stores value-information about where this PHI occurred, and what
  766. /// instruction number is associated with it.
  767. /// \returns true if MI was recognized and processed.
  768. bool transferDebugPHI(MachineInstr &MI);
  769. /// Examines whether \p MI is copy instruction, and notifies trackers.
  770. /// \returns true if MI was recognized and processed.
  771. bool transferRegisterCopy(MachineInstr &MI);
  772. /// Examines whether \p MI is stack spill or restore instruction, and
  773. /// notifies trackers. \returns true if MI was recognized and processed.
  774. bool transferSpillOrRestoreInst(MachineInstr &MI);
  775. /// Examines \p MI for any registers that it defines, and notifies trackers.
  776. void transferRegisterDef(MachineInstr &MI);
  777. /// Copy one location to the other, accounting for movement of subregisters
  778. /// too.
  779. void performCopy(Register Src, Register Dst);
  780. void accumulateFragmentMap(MachineInstr &MI);
  781. /// Determine the machine value number referred to by (potentially several)
  782. /// DBG_PHI instructions. Block duplication and tail folding can duplicate
  783. /// DBG_PHIs, shifting the position where values in registers merge, and
  784. /// forming another mini-ssa problem to solve.
  785. /// \p Here the position of a DBG_INSTR_REF seeking a machine value number
  786. /// \p InstrNum Debug instruction number defined by DBG_PHI instructions.
  787. /// \returns The machine value number at position Here, or None.
  788. Optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF,
  789. ValueIDNum **MLiveOuts,
  790. ValueIDNum **MLiveIns, MachineInstr &Here,
  791. uint64_t InstrNum);
  792. Optional<ValueIDNum> resolveDbgPHIsImpl(MachineFunction &MF,
  793. ValueIDNum **MLiveOuts,
  794. ValueIDNum **MLiveIns,
  795. MachineInstr &Here,
  796. uint64_t InstrNum);
  797. /// Step through the function, recording register definitions and movements
  798. /// in an MLocTracker. Convert the observations into a per-block transfer
  799. /// function in \p MLocTransfer, suitable for using with the machine value
  800. /// location dataflow problem.
  801. void
  802. produceMLocTransferFunction(MachineFunction &MF,
  803. SmallVectorImpl<MLocTransferMap> &MLocTransfer,
  804. unsigned MaxNumBlocks);
  805. /// Solve the machine value location dataflow problem. Takes as input the
  806. /// transfer functions in \p MLocTransfer. Writes the output live-in and
  807. /// live-out arrays to the (initialized to zero) multidimensional arrays in
  808. /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block
  809. /// number, the inner by LocIdx.
  810. void buildMLocValueMap(MachineFunction &MF, ValueIDNum **MInLocs,
  811. ValueIDNum **MOutLocs,
  812. SmallVectorImpl<MLocTransferMap> &MLocTransfer);
  813. /// Examine the stack indexes (i.e. offsets within the stack) to find the
  814. /// basic units of interference -- like reg units, but for the stack.
  815. void findStackIndexInterference(SmallVectorImpl<unsigned> &Slots);
  816. /// Install PHI values into the live-in array for each block, according to
  817. /// the IDF of each register.
  818. void placeMLocPHIs(MachineFunction &MF,
  819. SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
  820. ValueIDNum **MInLocs,
  821. SmallVectorImpl<MLocTransferMap> &MLocTransfer);
  822. /// Propagate variable values to blocks in the common case where there's
  823. /// only one value assigned to the variable. This function has better
  824. /// performance as it doesn't have to find the dominance frontier between
  825. /// different assignments.
  826. void placePHIsForSingleVarDefinition(
  827. const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
  828. MachineBasicBlock *MBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
  829. const DebugVariable &Var, LiveInsT &Output);
  830. /// Calculate the iterated-dominance-frontier for a set of defs, using the
  831. /// existing LLVM facilities for this. Works for a single "value" or
  832. /// machine/variable location.
  833. /// \p AllBlocks Set of blocks where we might consume the value.
  834. /// \p DefBlocks Set of blocks where the value/location is defined.
  835. /// \p PHIBlocks Output set of blocks where PHIs must be placed.
  836. void BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
  837. const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
  838. SmallVectorImpl<MachineBasicBlock *> &PHIBlocks);
  839. /// Perform a control flow join (lattice value meet) of the values in machine
  840. /// locations at \p MBB. Follows the algorithm described in the file-comment,
  841. /// reading live-outs of predecessors from \p OutLocs, the current live ins
  842. /// from \p InLocs, and assigning the newly computed live ins back into
  843. /// \p InLocs. \returns two bools -- the first indicates whether a change
  844. /// was made, the second whether a lattice downgrade occurred. If the latter
  845. /// is true, revisiting this block is necessary.
  846. bool mlocJoin(MachineBasicBlock &MBB,
  847. SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
  848. ValueIDNum **OutLocs, ValueIDNum *InLocs);
  849. /// Produce a set of blocks that are in the current lexical scope. This means
  850. /// those blocks that contain instructions "in" the scope, blocks where
  851. /// assignments to variables in scope occur, and artificial blocks that are
  852. /// successors to any of the earlier blocks. See https://llvm.org/PR48091 for
  853. /// more commentry on what "in scope" means.
  854. /// \p DILoc A location in the scope that we're fetching blocks for.
  855. /// \p Output Set to put in-scope-blocks into.
  856. /// \p AssignBlocks Blocks known to contain assignments of variables in scope.
  857. void
  858. getBlocksForScope(const DILocation *DILoc,
  859. SmallPtrSetImpl<const MachineBasicBlock *> &Output,
  860. const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks);
  861. /// Solve the variable value dataflow problem, for a single lexical scope.
  862. /// Uses the algorithm from the file comment to resolve control flow joins
  863. /// using PHI placement and value propagation. Reads the locations of machine
  864. /// values from the \p MInLocs and \p MOutLocs arrays (see buildMLocValueMap)
  865. /// and reads the variable values transfer function from \p AllTheVlocs.
  866. /// Live-in and Live-out variable values are stored locally, with the live-ins
  867. /// permanently stored to \p Output once a fixedpoint is reached.
  868. /// \p VarsWeCareAbout contains a collection of the variables in \p Scope
  869. /// that we should be tracking.
  870. /// \p AssignBlocks contains the set of blocks that aren't in \p DILoc's
  871. /// scope, but which do contain DBG_VALUEs, which VarLocBasedImpl tracks
  872. /// locations through.
  873. void buildVLocValueMap(const DILocation *DILoc,
  874. const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
  875. SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks,
  876. LiveInsT &Output, ValueIDNum **MOutLocs,
  877. ValueIDNum **MInLocs,
  878. SmallVectorImpl<VLocTracker> &AllTheVLocs);
  879. /// Attempt to eliminate un-necessary PHIs on entry to a block. Examines the
  880. /// live-in values coming from predecessors live-outs, and replaces any PHIs
  881. /// already present in this blocks live-ins with a live-through value if the
  882. /// PHI isn't needed.
  883. /// \p LiveIn Old live-in value, overwritten with new one if live-in changes.
  884. /// \returns true if any live-ins change value, either from value propagation
  885. /// or PHI elimination.
  886. bool vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
  887. SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
  888. DbgValue &LiveIn);
  889. /// For the given block and live-outs feeding into it, try to find a
  890. /// machine location where all the variable values join together.
  891. /// \returns Value ID of a machine PHI if an appropriate one is available.
  892. Optional<ValueIDNum>
  893. pickVPHILoc(const MachineBasicBlock &MBB, const DebugVariable &Var,
  894. const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs,
  895. const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders);
  896. /// Take collections of DBG_VALUE instructions stored in TTracker, and
  897. /// install them into their output blocks. Preserves a stable order of
  898. /// DBG_VALUEs produced (which would otherwise cause nondeterminism) through
  899. /// the AllVarsNumbering order.
  900. bool emitTransfers(DenseMap<DebugVariable, unsigned> &AllVarsNumbering);
  901. /// Boilerplate computation of some initial sets, artifical blocks and
  902. /// RPOT block ordering.
  903. void initialSetup(MachineFunction &MF);
  904. /// Produce a map of the last lexical scope that uses a block, using the
  905. /// scopes DFSOut number. Mapping is block-number to DFSOut.
  906. /// \p EjectionMap Pre-allocated vector in which to install the built ma.
  907. /// \p ScopeToDILocation Mapping of LexicalScopes to their DILocations.
  908. /// \p AssignBlocks Map of blocks where assignments happen for a scope.
  909. void makeDepthFirstEjectionMap(SmallVectorImpl<unsigned> &EjectionMap,
  910. const ScopeToDILocT &ScopeToDILocation,
  911. ScopeToAssignBlocksT &AssignBlocks);
  912. /// When determining per-block variable values and emitting to DBG_VALUEs,
  913. /// this function explores by lexical scope depth. Doing so means that per
  914. /// block information can be fully computed before exploration finishes,
  915. /// allowing us to emit it and free data structures earlier than otherwise.
  916. /// It's also good for locality.
  917. bool depthFirstVLocAndEmit(
  918. unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
  919. const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToBlocks,
  920. LiveInsT &Output, ValueIDNum **MOutLocs, ValueIDNum **MInLocs,
  921. SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
  922. DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
  923. const TargetPassConfig &TPC);
  924. bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree,
  925. TargetPassConfig *TPC, unsigned InputBBLimit,
  926. unsigned InputDbgValLimit) override;
  927. public:
  928. /// Default construct and initialize the pass.
  929. InstrRefBasedLDV();
  930. LLVM_DUMP_METHOD
  931. void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const;
  932. bool isCalleeSaved(LocIdx L) const;
  933. bool hasFoldedStackStore(const MachineInstr &MI) {
  934. // Instruction must have a memory operand that's a stack slot, and isn't
  935. // aliased, meaning it's a spill from regalloc instead of a variable.
  936. // If it's aliased, we can't guarantee its value.
  937. if (!MI.hasOneMemOperand())
  938. return false;
  939. auto *MemOperand = *MI.memoperands_begin();
  940. return MemOperand->isStore() &&
  941. MemOperand->getPseudoValue() &&
  942. MemOperand->getPseudoValue()->kind() == PseudoSourceValue::FixedStack
  943. && !MemOperand->getPseudoValue()->isAliased(MFI);
  944. }
  945. Optional<LocIdx> findLocationForMemOperand(const MachineInstr &MI);
  946. };
  947. } // namespace LiveDebugValues
  948. namespace llvm {
  949. using namespace LiveDebugValues;
  950. template <> struct DenseMapInfo<LocIdx> {
  951. static inline LocIdx getEmptyKey() { return LocIdx::MakeIllegalLoc(); }
  952. static inline LocIdx getTombstoneKey() { return LocIdx::MakeTombstoneLoc(); }
  953. static unsigned getHashValue(const LocIdx &Loc) { return Loc.asU64(); }
  954. static bool isEqual(const LocIdx &A, const LocIdx &B) { return A == B; }
  955. };
  956. template <> struct DenseMapInfo<ValueIDNum> {
  957. static inline ValueIDNum getEmptyKey() { return ValueIDNum::EmptyValue; }
  958. static inline ValueIDNum getTombstoneKey() {
  959. return ValueIDNum::TombstoneValue;
  960. }
  961. static unsigned getHashValue(const ValueIDNum &Val) {
  962. return hash_value(Val.asU64());
  963. }
  964. static bool isEqual(const ValueIDNum &A, const ValueIDNum &B) {
  965. return A == B;
  966. }
  967. };
  968. } // end namespace llvm
  969. #endif /* LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H */