RDFGraph.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. //===- RDFGraph.h -----------------------------------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Target-independent, SSA-based data flow graph for register data flow (RDF)
  10. // for a non-SSA program representation (e.g. post-RA machine code).
  11. //
  12. //
  13. // *** Introduction
  14. //
  15. // The RDF graph is a collection of nodes, each of which denotes some element
  16. // of the program. There are two main types of such elements: code and refe-
  17. // rences. Conceptually, "code" is something that represents the structure
  18. // of the program, e.g. basic block or a statement, while "reference" is an
  19. // instance of accessing a register, e.g. a definition or a use. Nodes are
  20. // connected with each other based on the structure of the program (such as
  21. // blocks, instructions, etc.), and based on the data flow (e.g. reaching
  22. // definitions, reached uses, etc.). The single-reaching-definition principle
  23. // of SSA is generally observed, although, due to the non-SSA representation
  24. // of the program, there are some differences between the graph and a "pure"
  25. // SSA representation.
  26. //
  27. //
  28. // *** Implementation remarks
  29. //
  30. // Since the graph can contain a large number of nodes, memory consumption
  31. // was one of the major design considerations. As a result, there is a single
  32. // base class NodeBase which defines all members used by all possible derived
  33. // classes. The members are arranged in a union, and a derived class cannot
  34. // add any data members of its own. Each derived class only defines the
  35. // functional interface, i.e. member functions. NodeBase must be a POD,
  36. // which implies that all of its members must also be PODs.
  37. // Since nodes need to be connected with other nodes, pointers have been
  38. // replaced with 32-bit identifiers: each node has an id of type NodeId.
  39. // There are mapping functions in the graph that translate between actual
  40. // memory addresses and the corresponding identifiers.
  41. // A node id of 0 is equivalent to nullptr.
  42. //
  43. //
  44. // *** Structure of the graph
  45. //
  46. // A code node is always a collection of other nodes. For example, a code
  47. // node corresponding to a basic block will contain code nodes corresponding
  48. // to instructions. In turn, a code node corresponding to an instruction will
  49. // contain a list of reference nodes that correspond to the definitions and
  50. // uses of registers in that instruction. The members are arranged into a
  51. // circular list, which is yet another consequence of the effort to save
  52. // memory: for each member node it should be possible to obtain its owner,
  53. // and it should be possible to access all other members. There are other
  54. // ways to accomplish that, but the circular list seemed the most natural.
  55. //
  56. // +- CodeNode -+
  57. // | | <---------------------------------------------------+
  58. // +-+--------+-+ |
  59. // |FirstM |LastM |
  60. // | +-------------------------------------+ |
  61. // | | |
  62. // V V |
  63. // +----------+ Next +----------+ Next Next +----------+ Next |
  64. // | |----->| |-----> ... ----->| |----->-+
  65. // +- Member -+ +- Member -+ +- Member -+
  66. //
  67. // The order of members is such that related reference nodes (see below)
  68. // should be contiguous on the member list.
  69. //
  70. // A reference node is a node that encapsulates an access to a register,
  71. // in other words, data flowing into or out of a register. There are two
  72. // major kinds of reference nodes: defs and uses. A def node will contain
  73. // the id of the first reached use, and the id of the first reached def.
  74. // Each def and use will contain the id of the reaching def, and also the
  75. // id of the next reached def (for def nodes) or use (for use nodes).
  76. // The "next node sharing the same reaching def" is denoted as "sibling".
  77. // In summary:
  78. // - Def node contains: reaching def, sibling, first reached def, and first
  79. // reached use.
  80. // - Use node contains: reaching def and sibling.
  81. //
  82. // +-- DefNode --+
  83. // | R2 = ... | <---+--------------------+
  84. // ++---------+--+ | |
  85. // |Reached |Reached | |
  86. // |Def |Use | |
  87. // | | |Reaching |Reaching
  88. // | V |Def |Def
  89. // | +-- UseNode --+ Sib +-- UseNode --+ Sib Sib
  90. // | | ... = R2 |----->| ... = R2 |----> ... ----> 0
  91. // | +-------------+ +-------------+
  92. // V
  93. // +-- DefNode --+ Sib
  94. // | R2 = ... |----> ...
  95. // ++---------+--+
  96. // | |
  97. // | |
  98. // ... ...
  99. //
  100. // To get a full picture, the circular lists connecting blocks within a
  101. // function, instructions within a block, etc. should be superimposed with
  102. // the def-def, def-use links shown above.
  103. // To illustrate this, consider a small example in a pseudo-assembly:
  104. // foo:
  105. // add r2, r0, r1 ; r2 = r0+r1
  106. // addi r0, r2, 1 ; r0 = r2+1
  107. // ret r0 ; return value in r0
  108. //
  109. // The graph (in a format used by the debugging functions) would look like:
  110. //
  111. // DFG dump:[
  112. // f1: Function foo
  113. // b2: === %bb.0 === preds(0), succs(0):
  114. // p3: phi [d4<r0>(,d12,u9):]
  115. // p5: phi [d6<r1>(,,u10):]
  116. // s7: add [d8<r2>(,,u13):, u9<r0>(d4):, u10<r1>(d6):]
  117. // s11: addi [d12<r0>(d4,,u15):, u13<r2>(d8):]
  118. // s14: ret [u15<r0>(d12):]
  119. // ]
  120. //
  121. // The f1, b2, p3, etc. are node ids. The letter is prepended to indicate the
  122. // kind of the node (i.e. f - function, b - basic block, p - phi, s - state-
  123. // ment, d - def, u - use).
  124. // The format of a def node is:
  125. // dN<R>(rd,d,u):sib,
  126. // where
  127. // N - numeric node id,
  128. // R - register being defined
  129. // rd - reaching def,
  130. // d - reached def,
  131. // u - reached use,
  132. // sib - sibling.
  133. // The format of a use node is:
  134. // uN<R>[!](rd):sib,
  135. // where
  136. // N - numeric node id,
  137. // R - register being used,
  138. // rd - reaching def,
  139. // sib - sibling.
  140. // Possible annotations (usually preceding the node id):
  141. // + - preserving def,
  142. // ~ - clobbering def,
  143. // " - shadow ref (follows the node id),
  144. // ! - fixed register (appears after register name).
  145. //
  146. // The circular lists are not explicit in the dump.
  147. //
  148. //
  149. // *** Node attributes
  150. //
  151. // NodeBase has a member "Attrs", which is the primary way of determining
  152. // the node's characteristics. The fields in this member decide whether
  153. // the node is a code node or a reference node (i.e. node's "type"), then
  154. // within each type, the "kind" determines what specifically this node
  155. // represents. The remaining bits, "flags", contain additional information
  156. // that is even more detailed than the "kind".
  157. // CodeNode's kinds are:
  158. // - Phi: Phi node, members are reference nodes.
  159. // - Stmt: Statement, members are reference nodes.
  160. // - Block: Basic block, members are instruction nodes (i.e. Phi or Stmt).
  161. // - Func: The whole function. The members are basic block nodes.
  162. // RefNode's kinds are:
  163. // - Use.
  164. // - Def.
  165. //
  166. // Meaning of flags:
  167. // - Preserving: applies only to defs. A preserving def is one that can
  168. // preserve some of the original bits among those that are included in
  169. // the register associated with that def. For example, if R0 is a 32-bit
  170. // register, but a def can only change the lower 16 bits, then it will
  171. // be marked as preserving.
  172. // - Shadow: a reference that has duplicates holding additional reaching
  173. // defs (see more below).
  174. // - Clobbering: applied only to defs, indicates that the value generated
  175. // by this def is unspecified. A typical example would be volatile registers
  176. // after function calls.
  177. // - Fixed: the register in this def/use cannot be replaced with any other
  178. // register. A typical case would be a parameter register to a call, or
  179. // the register with the return value from a function.
  180. // - Undef: the register in this reference the register is assumed to have
  181. // no pre-existing value, even if it appears to be reached by some def.
  182. // This is typically used to prevent keeping registers artificially live
  183. // in cases when they are defined via predicated instructions. For example:
  184. // r0 = add-if-true cond, r10, r11 (1)
  185. // r0 = add-if-false cond, r12, r13, implicit r0 (2)
  186. // ... = r0 (3)
  187. // Before (1), r0 is not intended to be live, and the use of r0 in (3) is
  188. // not meant to be reached by any def preceding (1). However, since the
  189. // defs in (1) and (2) are both preserving, these properties alone would
  190. // imply that the use in (3) may indeed be reached by some prior def.
  191. // Adding Undef flag to the def in (1) prevents that. The Undef flag
  192. // may be applied to both defs and uses.
  193. // - Dead: applies only to defs. The value coming out of a "dead" def is
  194. // assumed to be unused, even if the def appears to be reaching other defs
  195. // or uses. The motivation for this flag comes from dead defs on function
  196. // calls: there is no way to determine if such a def is dead without
  197. // analyzing the target's ABI. Hence the graph should contain this info,
  198. // as it is unavailable otherwise. On the other hand, a def without any
  199. // uses on a typical instruction is not the intended target for this flag.
  200. //
  201. // *** Shadow references
  202. //
  203. // It may happen that a super-register can have two (or more) non-overlapping
  204. // sub-registers. When both of these sub-registers are defined and followed
  205. // by a use of the super-register, the use of the super-register will not
  206. // have a unique reaching def: both defs of the sub-registers need to be
  207. // accounted for. In such cases, a duplicate use of the super-register is
  208. // added and it points to the extra reaching def. Both uses are marked with
  209. // a flag "shadow". Example:
  210. // Assume t0 is a super-register of r0 and r1, r0 and r1 do not overlap:
  211. // set r0, 1 ; r0 = 1
  212. // set r1, 1 ; r1 = 1
  213. // addi t1, t0, 1 ; t1 = t0+1
  214. //
  215. // The DFG:
  216. // s1: set [d2<r0>(,,u9):]
  217. // s3: set [d4<r1>(,,u10):]
  218. // s5: addi [d6<t1>(,,):, u7"<t0>(d2):, u8"<t0>(d4):]
  219. //
  220. // The statement s5 has two use nodes for t0: u7" and u9". The quotation
  221. // mark " indicates that the node is a shadow.
  222. //
  223. #ifndef LLVM_CODEGEN_RDFGRAPH_H
  224. #define LLVM_CODEGEN_RDFGRAPH_H
  225. #include "RDFRegisters.h"
  226. #include "llvm/ADT/SmallVector.h"
  227. #include "llvm/MC/LaneBitmask.h"
  228. #include "llvm/Support/Allocator.h"
  229. #include "llvm/Support/MathExtras.h"
  230. #include <cassert>
  231. #include <cstdint>
  232. #include <cstring>
  233. #include <map>
  234. #include <set>
  235. #include <unordered_map>
  236. #include <utility>
  237. #include <vector>
  238. // RDF uses uint32_t to refer to registers. This is to ensure that the type
  239. // size remains specific. In other places, registers are often stored using
  240. // unsigned.
  241. static_assert(sizeof(uint32_t) == sizeof(unsigned), "Those should be equal");
  242. namespace llvm {
  243. class MachineBasicBlock;
  244. class MachineDominanceFrontier;
  245. class MachineDominatorTree;
  246. class MachineFunction;
  247. class MachineInstr;
  248. class MachineOperand;
  249. class raw_ostream;
  250. class TargetInstrInfo;
  251. class TargetRegisterInfo;
  252. namespace rdf {
  253. using NodeId = uint32_t;
  254. struct DataFlowGraph;
  255. struct NodeAttrs {
  256. enum : uint16_t {
  257. None = 0x0000, // Nothing
  258. // Types: 2 bits
  259. TypeMask = 0x0003,
  260. Code = 0x0001, // 01, Container
  261. Ref = 0x0002, // 10, Reference
  262. // Kind: 3 bits
  263. KindMask = 0x0007 << 2,
  264. Def = 0x0001 << 2, // 001
  265. Use = 0x0002 << 2, // 010
  266. Phi = 0x0003 << 2, // 011
  267. Stmt = 0x0004 << 2, // 100
  268. Block = 0x0005 << 2, // 101
  269. Func = 0x0006 << 2, // 110
  270. // Flags: 7 bits for now
  271. FlagMask = 0x007F << 5,
  272. Shadow = 0x0001 << 5, // 0000001, Has extra reaching defs.
  273. Clobbering = 0x0002 << 5, // 0000010, Produces unspecified values.
  274. PhiRef = 0x0004 << 5, // 0000100, Member of PhiNode.
  275. Preserving = 0x0008 << 5, // 0001000, Def can keep original bits.
  276. Fixed = 0x0010 << 5, // 0010000, Fixed register.
  277. Undef = 0x0020 << 5, // 0100000, Has no pre-existing value.
  278. Dead = 0x0040 << 5, // 1000000, Does not define a value.
  279. };
  280. static uint16_t type(uint16_t T) { return T & TypeMask; }
  281. static uint16_t kind(uint16_t T) { return T & KindMask; }
  282. static uint16_t flags(uint16_t T) { return T & FlagMask; }
  283. static uint16_t set_type(uint16_t A, uint16_t T) {
  284. return (A & ~TypeMask) | T;
  285. }
  286. static uint16_t set_kind(uint16_t A, uint16_t K) {
  287. return (A & ~KindMask) | K;
  288. }
  289. static uint16_t set_flags(uint16_t A, uint16_t F) {
  290. return (A & ~FlagMask) | F;
  291. }
  292. // Test if A contains B.
  293. static bool contains(uint16_t A, uint16_t B) {
  294. if (type(A) != Code)
  295. return false;
  296. uint16_t KB = kind(B);
  297. switch (kind(A)) {
  298. case Func:
  299. return KB == Block;
  300. case Block:
  301. return KB == Phi || KB == Stmt;
  302. case Phi:
  303. case Stmt:
  304. return type(B) == Ref;
  305. }
  306. return false;
  307. }
  308. };
  309. struct BuildOptions {
  310. enum : unsigned {
  311. None = 0x00,
  312. KeepDeadPhis = 0x01, // Do not remove dead phis during build.
  313. };
  314. };
  315. template <typename T> struct NodeAddr {
  316. NodeAddr() = default;
  317. NodeAddr(T A, NodeId I) : Addr(A), Id(I) {}
  318. // Type cast (casting constructor). The reason for having this class
  319. // instead of std::pair.
  320. template <typename S> NodeAddr(const NodeAddr<S> &NA)
  321. : Addr(static_cast<T>(NA.Addr)), Id(NA.Id) {}
  322. bool operator== (const NodeAddr<T> &NA) const {
  323. assert((Addr == NA.Addr) == (Id == NA.Id));
  324. return Addr == NA.Addr;
  325. }
  326. bool operator!= (const NodeAddr<T> &NA) const {
  327. return !operator==(NA);
  328. }
  329. T Addr = nullptr;
  330. NodeId Id = 0;
  331. };
  332. struct NodeBase;
  333. // Fast memory allocation and translation between node id and node address.
  334. // This is really the same idea as the one underlying the "bump pointer
  335. // allocator", the difference being in the translation. A node id is
  336. // composed of two components: the index of the block in which it was
  337. // allocated, and the index within the block. With the default settings,
  338. // where the number of nodes per block is 4096, the node id (minus 1) is:
  339. //
  340. // bit position: 11 0
  341. // +----------------------------+--------------+
  342. // | Index of the block |Index in block|
  343. // +----------------------------+--------------+
  344. //
  345. // The actual node id is the above plus 1, to avoid creating a node id of 0.
  346. //
  347. // This method significantly improved the build time, compared to using maps
  348. // (std::unordered_map or DenseMap) to translate between pointers and ids.
  349. struct NodeAllocator {
  350. // Amount of storage for a single node.
  351. enum { NodeMemSize = 32 };
  352. NodeAllocator(uint32_t NPB = 4096)
  353. : NodesPerBlock(NPB), BitsPerIndex(Log2_32(NPB)),
  354. IndexMask((1 << BitsPerIndex)-1) {
  355. assert(isPowerOf2_32(NPB));
  356. }
  357. NodeBase *ptr(NodeId N) const {
  358. uint32_t N1 = N-1;
  359. uint32_t BlockN = N1 >> BitsPerIndex;
  360. uint32_t Offset = (N1 & IndexMask) * NodeMemSize;
  361. return reinterpret_cast<NodeBase*>(Blocks[BlockN]+Offset);
  362. }
  363. NodeId id(const NodeBase *P) const;
  364. NodeAddr<NodeBase*> New();
  365. void clear();
  366. private:
  367. void startNewBlock();
  368. bool needNewBlock();
  369. uint32_t makeId(uint32_t Block, uint32_t Index) const {
  370. // Add 1 to the id, to avoid the id of 0, which is treated as "null".
  371. return ((Block << BitsPerIndex) | Index) + 1;
  372. }
  373. const uint32_t NodesPerBlock;
  374. const uint32_t BitsPerIndex;
  375. const uint32_t IndexMask;
  376. char *ActiveEnd = nullptr;
  377. std::vector<char*> Blocks;
  378. using AllocatorTy = BumpPtrAllocatorImpl<MallocAllocator, 65536>;
  379. AllocatorTy MemPool;
  380. };
  381. using RegisterSet = std::set<RegisterRef>;
  382. struct TargetOperandInfo {
  383. TargetOperandInfo(const TargetInstrInfo &tii) : TII(tii) {}
  384. virtual ~TargetOperandInfo() = default;
  385. virtual bool isPreserving(const MachineInstr &In, unsigned OpNum) const;
  386. virtual bool isClobbering(const MachineInstr &In, unsigned OpNum) const;
  387. virtual bool isFixedReg(const MachineInstr &In, unsigned OpNum) const;
  388. const TargetInstrInfo &TII;
  389. };
  390. // Packed register reference. Only used for storage.
  391. struct PackedRegisterRef {
  392. RegisterId Reg;
  393. uint32_t MaskId;
  394. };
  395. struct LaneMaskIndex : private IndexedSet<LaneBitmask> {
  396. LaneMaskIndex() = default;
  397. LaneBitmask getLaneMaskForIndex(uint32_t K) const {
  398. return K == 0 ? LaneBitmask::getAll() : get(K);
  399. }
  400. uint32_t getIndexForLaneMask(LaneBitmask LM) {
  401. assert(LM.any());
  402. return LM.all() ? 0 : insert(LM);
  403. }
  404. uint32_t getIndexForLaneMask(LaneBitmask LM) const {
  405. assert(LM.any());
  406. return LM.all() ? 0 : find(LM);
  407. }
  408. };
  409. struct NodeBase {
  410. public:
  411. // Make sure this is a POD.
  412. NodeBase() = default;
  413. uint16_t getType() const { return NodeAttrs::type(Attrs); }
  414. uint16_t getKind() const { return NodeAttrs::kind(Attrs); }
  415. uint16_t getFlags() const { return NodeAttrs::flags(Attrs); }
  416. NodeId getNext() const { return Next; }
  417. uint16_t getAttrs() const { return Attrs; }
  418. void setAttrs(uint16_t A) { Attrs = A; }
  419. void setFlags(uint16_t F) { setAttrs(NodeAttrs::set_flags(getAttrs(), F)); }
  420. // Insert node NA after "this" in the circular chain.
  421. void append(NodeAddr<NodeBase*> NA);
  422. // Initialize all members to 0.
  423. void init() { memset(this, 0, sizeof *this); }
  424. void setNext(NodeId N) { Next = N; }
  425. protected:
  426. uint16_t Attrs;
  427. uint16_t Reserved;
  428. NodeId Next; // Id of the next node in the circular chain.
  429. // Definitions of nested types. Using anonymous nested structs would make
  430. // this class definition clearer, but unnamed structs are not a part of
  431. // the standard.
  432. struct Def_struct {
  433. NodeId DD, DU; // Ids of the first reached def and use.
  434. };
  435. struct PhiU_struct {
  436. NodeId PredB; // Id of the predecessor block for a phi use.
  437. };
  438. struct Code_struct {
  439. void *CP; // Pointer to the actual code.
  440. NodeId FirstM, LastM; // Id of the first member and last.
  441. };
  442. struct Ref_struct {
  443. NodeId RD, Sib; // Ids of the reaching def and the sibling.
  444. union {
  445. Def_struct Def;
  446. PhiU_struct PhiU;
  447. };
  448. union {
  449. MachineOperand *Op; // Non-phi refs point to a machine operand.
  450. PackedRegisterRef PR; // Phi refs store register info directly.
  451. };
  452. };
  453. // The actual payload.
  454. union {
  455. Ref_struct Ref;
  456. Code_struct Code;
  457. };
  458. };
  459. // The allocator allocates chunks of 32 bytes for each node. The fact that
  460. // each node takes 32 bytes in memory is used for fast translation between
  461. // the node id and the node address.
  462. static_assert(sizeof(NodeBase) <= NodeAllocator::NodeMemSize,
  463. "NodeBase must be at most NodeAllocator::NodeMemSize bytes");
  464. using NodeList = SmallVector<NodeAddr<NodeBase *>, 4>;
  465. using NodeSet = std::set<NodeId>;
  466. struct RefNode : public NodeBase {
  467. RefNode() = default;
  468. RegisterRef getRegRef(const DataFlowGraph &G) const;
  469. MachineOperand &getOp() {
  470. assert(!(getFlags() & NodeAttrs::PhiRef));
  471. return *Ref.Op;
  472. }
  473. void setRegRef(RegisterRef RR, DataFlowGraph &G);
  474. void setRegRef(MachineOperand *Op, DataFlowGraph &G);
  475. NodeId getReachingDef() const {
  476. return Ref.RD;
  477. }
  478. void setReachingDef(NodeId RD) {
  479. Ref.RD = RD;
  480. }
  481. NodeId getSibling() const {
  482. return Ref.Sib;
  483. }
  484. void setSibling(NodeId Sib) {
  485. Ref.Sib = Sib;
  486. }
  487. bool isUse() const {
  488. assert(getType() == NodeAttrs::Ref);
  489. return getKind() == NodeAttrs::Use;
  490. }
  491. bool isDef() const {
  492. assert(getType() == NodeAttrs::Ref);
  493. return getKind() == NodeAttrs::Def;
  494. }
  495. template <typename Predicate>
  496. NodeAddr<RefNode*> getNextRef(RegisterRef RR, Predicate P, bool NextOnly,
  497. const DataFlowGraph &G);
  498. NodeAddr<NodeBase*> getOwner(const DataFlowGraph &G);
  499. };
  500. struct DefNode : public RefNode {
  501. NodeId getReachedDef() const {
  502. return Ref.Def.DD;
  503. }
  504. void setReachedDef(NodeId D) {
  505. Ref.Def.DD = D;
  506. }
  507. NodeId getReachedUse() const {
  508. return Ref.Def.DU;
  509. }
  510. void setReachedUse(NodeId U) {
  511. Ref.Def.DU = U;
  512. }
  513. void linkToDef(NodeId Self, NodeAddr<DefNode*> DA);
  514. };
  515. struct UseNode : public RefNode {
  516. void linkToDef(NodeId Self, NodeAddr<DefNode*> DA);
  517. };
  518. struct PhiUseNode : public UseNode {
  519. NodeId getPredecessor() const {
  520. assert(getFlags() & NodeAttrs::PhiRef);
  521. return Ref.PhiU.PredB;
  522. }
  523. void setPredecessor(NodeId B) {
  524. assert(getFlags() & NodeAttrs::PhiRef);
  525. Ref.PhiU.PredB = B;
  526. }
  527. };
  528. struct CodeNode : public NodeBase {
  529. template <typename T> T getCode() const {
  530. return static_cast<T>(Code.CP);
  531. }
  532. void setCode(void *C) {
  533. Code.CP = C;
  534. }
  535. NodeAddr<NodeBase*> getFirstMember(const DataFlowGraph &G) const;
  536. NodeAddr<NodeBase*> getLastMember(const DataFlowGraph &G) const;
  537. void addMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G);
  538. void addMemberAfter(NodeAddr<NodeBase*> MA, NodeAddr<NodeBase*> NA,
  539. const DataFlowGraph &G);
  540. void removeMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G);
  541. NodeList members(const DataFlowGraph &G) const;
  542. template <typename Predicate>
  543. NodeList members_if(Predicate P, const DataFlowGraph &G) const;
  544. };
  545. struct InstrNode : public CodeNode {
  546. NodeAddr<NodeBase*> getOwner(const DataFlowGraph &G);
  547. };
  548. struct PhiNode : public InstrNode {
  549. MachineInstr *getCode() const {
  550. return nullptr;
  551. }
  552. };
  553. struct StmtNode : public InstrNode {
  554. MachineInstr *getCode() const {
  555. return CodeNode::getCode<MachineInstr*>();
  556. }
  557. };
  558. struct BlockNode : public CodeNode {
  559. MachineBasicBlock *getCode() const {
  560. return CodeNode::getCode<MachineBasicBlock*>();
  561. }
  562. void addPhi(NodeAddr<PhiNode*> PA, const DataFlowGraph &G);
  563. };
  564. struct FuncNode : public CodeNode {
  565. MachineFunction *getCode() const {
  566. return CodeNode::getCode<MachineFunction*>();
  567. }
  568. NodeAddr<BlockNode*> findBlock(const MachineBasicBlock *BB,
  569. const DataFlowGraph &G) const;
  570. NodeAddr<BlockNode*> getEntryBlock(const DataFlowGraph &G);
  571. };
  572. struct DataFlowGraph {
  573. DataFlowGraph(MachineFunction &mf, const TargetInstrInfo &tii,
  574. const TargetRegisterInfo &tri, const MachineDominatorTree &mdt,
  575. const MachineDominanceFrontier &mdf, const TargetOperandInfo &toi);
  576. NodeBase *ptr(NodeId N) const;
  577. template <typename T> T ptr(NodeId N) const {
  578. return static_cast<T>(ptr(N));
  579. }
  580. NodeId id(const NodeBase *P) const;
  581. template <typename T> NodeAddr<T> addr(NodeId N) const {
  582. return { ptr<T>(N), N };
  583. }
  584. NodeAddr<FuncNode*> getFunc() const { return Func; }
  585. MachineFunction &getMF() const { return MF; }
  586. const TargetInstrInfo &getTII() const { return TII; }
  587. const TargetRegisterInfo &getTRI() const { return TRI; }
  588. const PhysicalRegisterInfo &getPRI() const { return PRI; }
  589. const MachineDominatorTree &getDT() const { return MDT; }
  590. const MachineDominanceFrontier &getDF() const { return MDF; }
  591. const RegisterAggr &getLiveIns() const { return LiveIns; }
  592. struct DefStack {
  593. DefStack() = default;
  594. bool empty() const { return Stack.empty() || top() == bottom(); }
  595. private:
  596. using value_type = NodeAddr<DefNode *>;
  597. struct Iterator {
  598. using value_type = DefStack::value_type;
  599. Iterator &up() { Pos = DS.nextUp(Pos); return *this; }
  600. Iterator &down() { Pos = DS.nextDown(Pos); return *this; }
  601. value_type operator*() const {
  602. assert(Pos >= 1);
  603. return DS.Stack[Pos-1];
  604. }
  605. const value_type *operator->() const {
  606. assert(Pos >= 1);
  607. return &DS.Stack[Pos-1];
  608. }
  609. bool operator==(const Iterator &It) const { return Pos == It.Pos; }
  610. bool operator!=(const Iterator &It) const { return Pos != It.Pos; }
  611. private:
  612. friend struct DefStack;
  613. Iterator(const DefStack &S, bool Top);
  614. // Pos-1 is the index in the StorageType object that corresponds to
  615. // the top of the DefStack.
  616. const DefStack &DS;
  617. unsigned Pos;
  618. };
  619. public:
  620. using iterator = Iterator;
  621. iterator top() const { return Iterator(*this, true); }
  622. iterator bottom() const { return Iterator(*this, false); }
  623. unsigned size() const;
  624. void push(NodeAddr<DefNode*> DA) { Stack.push_back(DA); }
  625. void pop();
  626. void start_block(NodeId N);
  627. void clear_block(NodeId N);
  628. private:
  629. friend struct Iterator;
  630. using StorageType = std::vector<value_type>;
  631. bool isDelimiter(const StorageType::value_type &P, NodeId N = 0) const {
  632. return (P.Addr == nullptr) && (N == 0 || P.Id == N);
  633. }
  634. unsigned nextUp(unsigned P) const;
  635. unsigned nextDown(unsigned P) const;
  636. StorageType Stack;
  637. };
  638. // Make this std::unordered_map for speed of accessing elements.
  639. // Map: Register (physical or virtual) -> DefStack
  640. using DefStackMap = std::unordered_map<RegisterId, DefStack>;
  641. void build(unsigned Options = BuildOptions::None);
  642. void pushAllDefs(NodeAddr<InstrNode*> IA, DefStackMap &DM);
  643. void markBlock(NodeId B, DefStackMap &DefM);
  644. void releaseBlock(NodeId B, DefStackMap &DefM);
  645. PackedRegisterRef pack(RegisterRef RR) {
  646. return { RR.Reg, LMI.getIndexForLaneMask(RR.Mask) };
  647. }
  648. PackedRegisterRef pack(RegisterRef RR) const {
  649. return { RR.Reg, LMI.getIndexForLaneMask(RR.Mask) };
  650. }
  651. RegisterRef unpack(PackedRegisterRef PR) const {
  652. return RegisterRef(PR.Reg, LMI.getLaneMaskForIndex(PR.MaskId));
  653. }
  654. RegisterRef makeRegRef(unsigned Reg, unsigned Sub) const;
  655. RegisterRef makeRegRef(const MachineOperand &Op) const;
  656. RegisterRef restrictRef(RegisterRef AR, RegisterRef BR) const;
  657. NodeAddr<RefNode*> getNextRelated(NodeAddr<InstrNode*> IA,
  658. NodeAddr<RefNode*> RA) const;
  659. NodeAddr<RefNode*> getNextShadow(NodeAddr<InstrNode*> IA,
  660. NodeAddr<RefNode*> RA, bool Create);
  661. NodeAddr<RefNode*> getNextShadow(NodeAddr<InstrNode*> IA,
  662. NodeAddr<RefNode*> RA) const;
  663. NodeList getRelatedRefs(NodeAddr<InstrNode*> IA,
  664. NodeAddr<RefNode*> RA) const;
  665. NodeAddr<BlockNode*> findBlock(MachineBasicBlock *BB) const {
  666. return BlockNodes.at(BB);
  667. }
  668. void unlinkUse(NodeAddr<UseNode*> UA, bool RemoveFromOwner) {
  669. unlinkUseDF(UA);
  670. if (RemoveFromOwner)
  671. removeFromOwner(UA);
  672. }
  673. void unlinkDef(NodeAddr<DefNode*> DA, bool RemoveFromOwner) {
  674. unlinkDefDF(DA);
  675. if (RemoveFromOwner)
  676. removeFromOwner(DA);
  677. }
  678. // Some useful filters.
  679. template <uint16_t Kind>
  680. static bool IsRef(const NodeAddr<NodeBase*> BA) {
  681. return BA.Addr->getType() == NodeAttrs::Ref &&
  682. BA.Addr->getKind() == Kind;
  683. }
  684. template <uint16_t Kind>
  685. static bool IsCode(const NodeAddr<NodeBase*> BA) {
  686. return BA.Addr->getType() == NodeAttrs::Code &&
  687. BA.Addr->getKind() == Kind;
  688. }
  689. static bool IsDef(const NodeAddr<NodeBase*> BA) {
  690. return BA.Addr->getType() == NodeAttrs::Ref &&
  691. BA.Addr->getKind() == NodeAttrs::Def;
  692. }
  693. static bool IsUse(const NodeAddr<NodeBase*> BA) {
  694. return BA.Addr->getType() == NodeAttrs::Ref &&
  695. BA.Addr->getKind() == NodeAttrs::Use;
  696. }
  697. static bool IsPhi(const NodeAddr<NodeBase*> BA) {
  698. return BA.Addr->getType() == NodeAttrs::Code &&
  699. BA.Addr->getKind() == NodeAttrs::Phi;
  700. }
  701. static bool IsPreservingDef(const NodeAddr<DefNode*> DA) {
  702. uint16_t Flags = DA.Addr->getFlags();
  703. return (Flags & NodeAttrs::Preserving) && !(Flags & NodeAttrs::Undef);
  704. }
  705. private:
  706. void reset();
  707. RegisterSet getLandingPadLiveIns() const;
  708. NodeAddr<NodeBase*> newNode(uint16_t Attrs);
  709. NodeAddr<NodeBase*> cloneNode(const NodeAddr<NodeBase*> B);
  710. NodeAddr<UseNode*> newUse(NodeAddr<InstrNode*> Owner,
  711. MachineOperand &Op, uint16_t Flags = NodeAttrs::None);
  712. NodeAddr<PhiUseNode*> newPhiUse(NodeAddr<PhiNode*> Owner,
  713. RegisterRef RR, NodeAddr<BlockNode*> PredB,
  714. uint16_t Flags = NodeAttrs::PhiRef);
  715. NodeAddr<DefNode*> newDef(NodeAddr<InstrNode*> Owner,
  716. MachineOperand &Op, uint16_t Flags = NodeAttrs::None);
  717. NodeAddr<DefNode*> newDef(NodeAddr<InstrNode*> Owner,
  718. RegisterRef RR, uint16_t Flags = NodeAttrs::PhiRef);
  719. NodeAddr<PhiNode*> newPhi(NodeAddr<BlockNode*> Owner);
  720. NodeAddr<StmtNode*> newStmt(NodeAddr<BlockNode*> Owner,
  721. MachineInstr *MI);
  722. NodeAddr<BlockNode*> newBlock(NodeAddr<FuncNode*> Owner,
  723. MachineBasicBlock *BB);
  724. NodeAddr<FuncNode*> newFunc(MachineFunction *MF);
  725. template <typename Predicate>
  726. std::pair<NodeAddr<RefNode*>,NodeAddr<RefNode*>>
  727. locateNextRef(NodeAddr<InstrNode*> IA, NodeAddr<RefNode*> RA,
  728. Predicate P) const;
  729. using BlockRefsMap = std::map<NodeId, RegisterSet>;
  730. void buildStmt(NodeAddr<BlockNode*> BA, MachineInstr &In);
  731. void recordDefsForDF(BlockRefsMap &PhiM, NodeAddr<BlockNode*> BA);
  732. void buildPhis(BlockRefsMap &PhiM, RegisterSet &AllRefs,
  733. NodeAddr<BlockNode*> BA);
  734. void removeUnusedPhis();
  735. void pushClobbers(NodeAddr<InstrNode*> IA, DefStackMap &DM);
  736. void pushDefs(NodeAddr<InstrNode*> IA, DefStackMap &DM);
  737. template <typename T> void linkRefUp(NodeAddr<InstrNode*> IA,
  738. NodeAddr<T> TA, DefStack &DS);
  739. template <typename Predicate> void linkStmtRefs(DefStackMap &DefM,
  740. NodeAddr<StmtNode*> SA, Predicate P);
  741. void linkBlockRefs(DefStackMap &DefM, NodeAddr<BlockNode*> BA);
  742. void unlinkUseDF(NodeAddr<UseNode*> UA);
  743. void unlinkDefDF(NodeAddr<DefNode*> DA);
  744. void removeFromOwner(NodeAddr<RefNode*> RA) {
  745. NodeAddr<InstrNode*> IA = RA.Addr->getOwner(*this);
  746. IA.Addr->removeMember(RA, *this);
  747. }
  748. MachineFunction &MF;
  749. const TargetInstrInfo &TII;
  750. const TargetRegisterInfo &TRI;
  751. const PhysicalRegisterInfo PRI;
  752. const MachineDominatorTree &MDT;
  753. const MachineDominanceFrontier &MDF;
  754. const TargetOperandInfo &TOI;
  755. RegisterAggr LiveIns;
  756. NodeAddr<FuncNode*> Func;
  757. NodeAllocator Memory;
  758. // Local map: MachineBasicBlock -> NodeAddr<BlockNode*>
  759. std::map<MachineBasicBlock*,NodeAddr<BlockNode*>> BlockNodes;
  760. // Lane mask map.
  761. LaneMaskIndex LMI;
  762. }; // struct DataFlowGraph
  763. template <typename Predicate>
  764. NodeAddr<RefNode*> RefNode::getNextRef(RegisterRef RR, Predicate P,
  765. bool NextOnly, const DataFlowGraph &G) {
  766. // Get the "Next" reference in the circular list that references RR and
  767. // satisfies predicate "Pred".
  768. auto NA = G.addr<NodeBase*>(getNext());
  769. while (NA.Addr != this) {
  770. if (NA.Addr->getType() == NodeAttrs::Ref) {
  771. NodeAddr<RefNode*> RA = NA;
  772. if (RA.Addr->getRegRef(G) == RR && P(NA))
  773. return NA;
  774. if (NextOnly)
  775. break;
  776. NA = G.addr<NodeBase*>(NA.Addr->getNext());
  777. } else {
  778. // We've hit the beginning of the chain.
  779. assert(NA.Addr->getType() == NodeAttrs::Code);
  780. NodeAddr<CodeNode*> CA = NA;
  781. NA = CA.Addr->getFirstMember(G);
  782. }
  783. }
  784. // Return the equivalent of "nullptr" if such a node was not found.
  785. return NodeAddr<RefNode*>();
  786. }
  787. template <typename Predicate>
  788. NodeList CodeNode::members_if(Predicate P, const DataFlowGraph &G) const {
  789. NodeList MM;
  790. auto M = getFirstMember(G);
  791. if (M.Id == 0)
  792. return MM;
  793. while (M.Addr != this) {
  794. if (P(M))
  795. MM.push_back(M);
  796. M = G.addr<NodeBase*>(M.Addr->getNext());
  797. }
  798. return MM;
  799. }
  800. template <typename T>
  801. struct Print {
  802. Print(const T &x, const DataFlowGraph &g) : Obj(x), G(g) {}
  803. const T &Obj;
  804. const DataFlowGraph &G;
  805. };
  806. template <typename T>
  807. struct PrintNode : Print<NodeAddr<T>> {
  808. PrintNode(const NodeAddr<T> &x, const DataFlowGraph &g)
  809. : Print<NodeAddr<T>>(x, g) {}
  810. };
  811. raw_ostream &operator<<(raw_ostream &OS, const Print<RegisterRef> &P);
  812. raw_ostream &operator<<(raw_ostream &OS, const Print<NodeId> &P);
  813. raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<DefNode *>> &P);
  814. raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<UseNode *>> &P);
  815. raw_ostream &operator<<(raw_ostream &OS,
  816. const Print<NodeAddr<PhiUseNode *>> &P);
  817. raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<RefNode *>> &P);
  818. raw_ostream &operator<<(raw_ostream &OS, const Print<NodeList> &P);
  819. raw_ostream &operator<<(raw_ostream &OS, const Print<NodeSet> &P);
  820. raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<PhiNode *>> &P);
  821. raw_ostream &operator<<(raw_ostream &OS,
  822. const Print<NodeAddr<StmtNode *>> &P);
  823. raw_ostream &operator<<(raw_ostream &OS,
  824. const Print<NodeAddr<InstrNode *>> &P);
  825. raw_ostream &operator<<(raw_ostream &OS,
  826. const Print<NodeAddr<BlockNode *>> &P);
  827. raw_ostream &operator<<(raw_ostream &OS,
  828. const Print<NodeAddr<FuncNode *>> &P);
  829. raw_ostream &operator<<(raw_ostream &OS, const Print<RegisterSet> &P);
  830. raw_ostream &operator<<(raw_ostream &OS, const Print<RegisterAggr> &P);
  831. raw_ostream &operator<<(raw_ostream &OS,
  832. const Print<DataFlowGraph::DefStack> &P);
  833. } // end namespace rdf
  834. } // end namespace llvm
  835. #endif // LLVM_CODEGEN_RDFGRAPH_H