InstrRefBasedImpl.h 56 KB

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