#ifndef LLVM_CODEGEN_RDFGRAPH_H
#define LLVM_CODEGEN_RDFGRAPH_H
#include "RDFRegisters.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/MC/LaneBitmask.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/MathExtras.h"
#include <cassert>
#include <cstdint>
#include <cstring>
#include <map>
#include <set>
#include <unordered_map>
#include <utility>
#include <vector>
static_assert(sizeof(uint32_t) == sizeof(unsigned), "Those should be equal");
namespace llvm {
class MachineBasicBlock;
class MachineDominanceFrontier;
class MachineDominatorTree;
class MachineFunction;
class MachineInstr;
class MachineOperand;
class raw_ostream;
class TargetInstrInfo;
class TargetRegisterInfo;
namespace rdf {
using NodeId = uint32_t;
struct DataFlowGraph;
struct NodeAttrs {
enum : uint16_t {
None = 0x0000,
TypeMask = 0x0003,
Code = 0x0001, Ref = 0x0002,
KindMask = 0x0007 << 2,
Def = 0x0001 << 2, Use = 0x0002 << 2, Phi = 0x0003 << 2, Stmt = 0x0004 << 2, Block = 0x0005 << 2, Func = 0x0006 << 2,
FlagMask = 0x007F << 5,
Shadow = 0x0001 << 5, Clobbering = 0x0002 << 5, PhiRef = 0x0004 << 5, Preserving = 0x0008 << 5, Fixed = 0x0010 << 5, Undef = 0x0020 << 5, Dead = 0x0040 << 5, };
static uint16_t type(uint16_t T) { return T & TypeMask; }
static uint16_t kind(uint16_t T) { return T & KindMask; }
static uint16_t flags(uint16_t T) { return T & FlagMask; }
static uint16_t set_type(uint16_t A, uint16_t T) {
return (A & ~TypeMask) | T;
}
static uint16_t set_kind(uint16_t A, uint16_t K) {
return (A & ~KindMask) | K;
}
static uint16_t set_flags(uint16_t A, uint16_t F) {
return (A & ~FlagMask) | F;
}
static bool contains(uint16_t A, uint16_t B) {
if (type(A) != Code)
return false;
uint16_t KB = kind(B);
switch (kind(A)) {
case Func:
return KB == Block;
case Block:
return KB == Phi || KB == Stmt;
case Phi:
case Stmt:
return type(B) == Ref;
}
return false;
}
};
struct BuildOptions {
enum : unsigned {
None = 0x00,
KeepDeadPhis = 0x01, };
};
template <typename T> struct NodeAddr {
NodeAddr() = default;
NodeAddr(T A, NodeId I) : Addr(A), Id(I) {}
template <typename S> NodeAddr(const NodeAddr<S> &NA)
: Addr(static_cast<T>(NA.Addr)), Id(NA.Id) {}
bool operator== (const NodeAddr<T> &NA) const {
assert((Addr == NA.Addr) == (Id == NA.Id));
return Addr == NA.Addr;
}
bool operator!= (const NodeAddr<T> &NA) const {
return !operator==(NA);
}
T Addr = nullptr;
NodeId Id = 0;
};
struct NodeBase;
struct NodeAllocator {
enum { NodeMemSize = 32 };
NodeAllocator(uint32_t NPB = 4096)
: NodesPerBlock(NPB), BitsPerIndex(Log2_32(NPB)),
IndexMask((1 << BitsPerIndex)-1) {
assert(isPowerOf2_32(NPB));
}
NodeBase *ptr(NodeId N) const {
uint32_t N1 = N-1;
uint32_t BlockN = N1 >> BitsPerIndex;
uint32_t Offset = (N1 & IndexMask) * NodeMemSize;
return reinterpret_cast<NodeBase*>(Blocks[BlockN]+Offset);
}
NodeId id(const NodeBase *P) const;
NodeAddr<NodeBase*> New();
void clear();
private:
void startNewBlock();
bool needNewBlock();
uint32_t makeId(uint32_t Block, uint32_t Index) const {
return ((Block << BitsPerIndex) | Index) + 1;
}
const uint32_t NodesPerBlock;
const uint32_t BitsPerIndex;
const uint32_t IndexMask;
char *ActiveEnd = nullptr;
std::vector<char*> Blocks;
using AllocatorTy = BumpPtrAllocatorImpl<MallocAllocator, 65536>;
AllocatorTy MemPool;
};
using RegisterSet = std::set<RegisterRef>;
struct TargetOperandInfo {
TargetOperandInfo(const TargetInstrInfo &tii) : TII(tii) {}
virtual ~TargetOperandInfo() = default;
virtual bool isPreserving(const MachineInstr &In, unsigned OpNum) const;
virtual bool isClobbering(const MachineInstr &In, unsigned OpNum) const;
virtual bool isFixedReg(const MachineInstr &In, unsigned OpNum) const;
const TargetInstrInfo &TII;
};
struct PackedRegisterRef {
RegisterId Reg;
uint32_t MaskId;
};
struct LaneMaskIndex : private IndexedSet<LaneBitmask> {
LaneMaskIndex() = default;
LaneBitmask getLaneMaskForIndex(uint32_t K) const {
return K == 0 ? LaneBitmask::getAll() : get(K);
}
uint32_t getIndexForLaneMask(LaneBitmask LM) {
assert(LM.any());
return LM.all() ? 0 : insert(LM);
}
uint32_t getIndexForLaneMask(LaneBitmask LM) const {
assert(LM.any());
return LM.all() ? 0 : find(LM);
}
};
struct NodeBase {
public:
NodeBase() = default;
uint16_t getType() const { return NodeAttrs::type(Attrs); }
uint16_t getKind() const { return NodeAttrs::kind(Attrs); }
uint16_t getFlags() const { return NodeAttrs::flags(Attrs); }
NodeId getNext() const { return Next; }
uint16_t getAttrs() const { return Attrs; }
void setAttrs(uint16_t A) { Attrs = A; }
void setFlags(uint16_t F) { setAttrs(NodeAttrs::set_flags(getAttrs(), F)); }
void append(NodeAddr<NodeBase*> NA);
void init() { memset(this, 0, sizeof *this); }
void setNext(NodeId N) { Next = N; }
protected:
uint16_t Attrs;
uint16_t Reserved;
NodeId Next; struct Def_struct {
NodeId DD, DU; };
struct PhiU_struct {
NodeId PredB; };
struct Code_struct {
void *CP; NodeId FirstM, LastM; };
struct Ref_struct {
NodeId RD, Sib; union {
Def_struct Def;
PhiU_struct PhiU;
};
union {
MachineOperand *Op; PackedRegisterRef PR; };
};
union {
Ref_struct Ref;
Code_struct Code;
};
};
static_assert(sizeof(NodeBase) <= NodeAllocator::NodeMemSize,
"NodeBase must be at most NodeAllocator::NodeMemSize bytes");
using NodeList = SmallVector<NodeAddr<NodeBase *>, 4>;
using NodeSet = std::set<NodeId>;
struct RefNode : public NodeBase {
RefNode() = default;
RegisterRef getRegRef(const DataFlowGraph &G) const;
MachineOperand &getOp() {
assert(!(getFlags() & NodeAttrs::PhiRef));
return *Ref.Op;
}
void setRegRef(RegisterRef RR, DataFlowGraph &G);
void setRegRef(MachineOperand *Op, DataFlowGraph &G);
NodeId getReachingDef() const {
return Ref.RD;
}
void setReachingDef(NodeId RD) {
Ref.RD = RD;
}
NodeId getSibling() const {
return Ref.Sib;
}
void setSibling(NodeId Sib) {
Ref.Sib = Sib;
}
bool isUse() const {
assert(getType() == NodeAttrs::Ref);
return getKind() == NodeAttrs::Use;
}
bool isDef() const {
assert(getType() == NodeAttrs::Ref);
return getKind() == NodeAttrs::Def;
}
template <typename Predicate>
NodeAddr<RefNode*> getNextRef(RegisterRef RR, Predicate P, bool NextOnly,
const DataFlowGraph &G);
NodeAddr<NodeBase*> getOwner(const DataFlowGraph &G);
};
struct DefNode : public RefNode {
NodeId getReachedDef() const {
return Ref.Def.DD;
}
void setReachedDef(NodeId D) {
Ref.Def.DD = D;
}
NodeId getReachedUse() const {
return Ref.Def.DU;
}
void setReachedUse(NodeId U) {
Ref.Def.DU = U;
}
void linkToDef(NodeId Self, NodeAddr<DefNode*> DA);
};
struct UseNode : public RefNode {
void linkToDef(NodeId Self, NodeAddr<DefNode*> DA);
};
struct PhiUseNode : public UseNode {
NodeId getPredecessor() const {
assert(getFlags() & NodeAttrs::PhiRef);
return Ref.PhiU.PredB;
}
void setPredecessor(NodeId B) {
assert(getFlags() & NodeAttrs::PhiRef);
Ref.PhiU.PredB = B;
}
};
struct CodeNode : public NodeBase {
template <typename T> T getCode() const {
return static_cast<T>(Code.CP);
}
void setCode(void *C) {
Code.CP = C;
}
NodeAddr<NodeBase*> getFirstMember(const DataFlowGraph &G) const;
NodeAddr<NodeBase*> getLastMember(const DataFlowGraph &G) const;
void addMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G);
void addMemberAfter(NodeAddr<NodeBase*> MA, NodeAddr<NodeBase*> NA,
const DataFlowGraph &G);
void removeMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G);
NodeList members(const DataFlowGraph &G) const;
template <typename Predicate>
NodeList members_if(Predicate P, const DataFlowGraph &G) const;
};
struct InstrNode : public CodeNode {
NodeAddr<NodeBase*> getOwner(const DataFlowGraph &G);
};
struct PhiNode : public InstrNode {
MachineInstr *getCode() const {
return nullptr;
}
};
struct StmtNode : public InstrNode {
MachineInstr *getCode() const {
return CodeNode::getCode<MachineInstr*>();
}
};
struct BlockNode : public CodeNode {
MachineBasicBlock *getCode() const {
return CodeNode::getCode<MachineBasicBlock*>();
}
void addPhi(NodeAddr<PhiNode*> PA, const DataFlowGraph &G);
};
struct FuncNode : public CodeNode {
MachineFunction *getCode() const {
return CodeNode::getCode<MachineFunction*>();
}
NodeAddr<BlockNode*> findBlock(const MachineBasicBlock *BB,
const DataFlowGraph &G) const;
NodeAddr<BlockNode*> getEntryBlock(const DataFlowGraph &G);
};
struct DataFlowGraph {
DataFlowGraph(MachineFunction &mf, const TargetInstrInfo &tii,
const TargetRegisterInfo &tri, const MachineDominatorTree &mdt,
const MachineDominanceFrontier &mdf, const TargetOperandInfo &toi);
NodeBase *ptr(NodeId N) const;
template <typename T> T ptr(NodeId N) const {
return static_cast<T>(ptr(N));
}
NodeId id(const NodeBase *P) const;
template <typename T> NodeAddr<T> addr(NodeId N) const {
return { ptr<T>(N), N };
}
NodeAddr<FuncNode*> getFunc() const { return Func; }
MachineFunction &getMF() const { return MF; }
const TargetInstrInfo &getTII() const { return TII; }
const TargetRegisterInfo &getTRI() const { return TRI; }
const PhysicalRegisterInfo &getPRI() const { return PRI; }
const MachineDominatorTree &getDT() const { return MDT; }
const MachineDominanceFrontier &getDF() const { return MDF; }
const RegisterAggr &getLiveIns() const { return LiveIns; }
struct DefStack {
DefStack() = default;
bool empty() const { return Stack.empty() || top() == bottom(); }
private:
using value_type = NodeAddr<DefNode *>;
struct Iterator {
using value_type = DefStack::value_type;
Iterator &up() { Pos = DS.nextUp(Pos); return *this; }
Iterator &down() { Pos = DS.nextDown(Pos); return *this; }
value_type operator*() const {
assert(Pos >= 1);
return DS.Stack[Pos-1];
}
const value_type *operator->() const {
assert(Pos >= 1);
return &DS.Stack[Pos-1];
}
bool operator==(const Iterator &It) const { return Pos == It.Pos; }
bool operator!=(const Iterator &It) const { return Pos != It.Pos; }
private:
friend struct DefStack;
Iterator(const DefStack &S, bool Top);
const DefStack &DS;
unsigned Pos;
};
public:
using iterator = Iterator;
iterator top() const { return Iterator(*this, true); }
iterator bottom() const { return Iterator(*this, false); }
unsigned size() const;
void push(NodeAddr<DefNode*> DA) { Stack.push_back(DA); }
void pop();
void start_block(NodeId N);
void clear_block(NodeId N);
private:
friend struct Iterator;
using StorageType = std::vector<value_type>;
bool isDelimiter(const StorageType::value_type &P, NodeId N = 0) const {
return (P.Addr == nullptr) && (N == 0 || P.Id == N);
}
unsigned nextUp(unsigned P) const;
unsigned nextDown(unsigned P) const;
StorageType Stack;
};
using DefStackMap = std::unordered_map<RegisterId, DefStack>;
void build(unsigned Options = BuildOptions::None);
void pushAllDefs(NodeAddr<InstrNode*> IA, DefStackMap &DM);
void markBlock(NodeId B, DefStackMap &DefM);
void releaseBlock(NodeId B, DefStackMap &DefM);
PackedRegisterRef pack(RegisterRef RR) {
return { RR.Reg, LMI.getIndexForLaneMask(RR.Mask) };
}
PackedRegisterRef pack(RegisterRef RR) const {
return { RR.Reg, LMI.getIndexForLaneMask(RR.Mask) };
}
RegisterRef unpack(PackedRegisterRef PR) const {
return RegisterRef(PR.Reg, LMI.getLaneMaskForIndex(PR.MaskId));
}
RegisterRef makeRegRef(unsigned Reg, unsigned Sub) const;
RegisterRef makeRegRef(const MachineOperand &Op) const;
NodeAddr<RefNode*> getNextRelated(NodeAddr<InstrNode*> IA,
NodeAddr<RefNode*> RA) const;
NodeAddr<RefNode*> getNextShadow(NodeAddr<InstrNode*> IA,
NodeAddr<RefNode*> RA, bool Create);
NodeAddr<RefNode*> getNextShadow(NodeAddr<InstrNode*> IA,
NodeAddr<RefNode*> RA) const;
NodeList getRelatedRefs(NodeAddr<InstrNode*> IA,
NodeAddr<RefNode*> RA) const;
NodeAddr<BlockNode*> findBlock(MachineBasicBlock *BB) const {
return BlockNodes.at(BB);
}
void unlinkUse(NodeAddr<UseNode*> UA, bool RemoveFromOwner) {
unlinkUseDF(UA);
if (RemoveFromOwner)
removeFromOwner(UA);
}
void unlinkDef(NodeAddr<DefNode*> DA, bool RemoveFromOwner) {
unlinkDefDF(DA);
if (RemoveFromOwner)
removeFromOwner(DA);
}
template <uint16_t Kind>
static bool IsRef(const NodeAddr<NodeBase*> BA) {
return BA.Addr->getType() == NodeAttrs::Ref &&
BA.Addr->getKind() == Kind;
}
template <uint16_t Kind>
static bool IsCode(const NodeAddr<NodeBase*> BA) {
return BA.Addr->getType() == NodeAttrs::Code &&
BA.Addr->getKind() == Kind;
}
static bool IsDef(const NodeAddr<NodeBase*> BA) {
return BA.Addr->getType() == NodeAttrs::Ref &&
BA.Addr->getKind() == NodeAttrs::Def;
}
static bool IsUse(const NodeAddr<NodeBase*> BA) {
return BA.Addr->getType() == NodeAttrs::Ref &&
BA.Addr->getKind() == NodeAttrs::Use;
}
static bool IsPhi(const NodeAddr<NodeBase*> BA) {
return BA.Addr->getType() == NodeAttrs::Code &&
BA.Addr->getKind() == NodeAttrs::Phi;
}
static bool IsPreservingDef(const NodeAddr<DefNode*> DA) {
uint16_t Flags = DA.Addr->getFlags();
return (Flags & NodeAttrs::Preserving) && !(Flags & NodeAttrs::Undef);
}
private:
void reset();
RegisterSet getLandingPadLiveIns() const;
NodeAddr<NodeBase*> newNode(uint16_t Attrs);
NodeAddr<NodeBase*> cloneNode(const NodeAddr<NodeBase*> B);
NodeAddr<UseNode*> newUse(NodeAddr<InstrNode*> Owner,
MachineOperand &Op, uint16_t Flags = NodeAttrs::None);
NodeAddr<PhiUseNode*> newPhiUse(NodeAddr<PhiNode*> Owner,
RegisterRef RR, NodeAddr<BlockNode*> PredB,
uint16_t Flags = NodeAttrs::PhiRef);
NodeAddr<DefNode*> newDef(NodeAddr<InstrNode*> Owner,
MachineOperand &Op, uint16_t Flags = NodeAttrs::None);
NodeAddr<DefNode*> newDef(NodeAddr<InstrNode*> Owner,
RegisterRef RR, uint16_t Flags = NodeAttrs::PhiRef);
NodeAddr<PhiNode*> newPhi(NodeAddr<BlockNode*> Owner);
NodeAddr<StmtNode*> newStmt(NodeAddr<BlockNode*> Owner,
MachineInstr *MI);
NodeAddr<BlockNode*> newBlock(NodeAddr<FuncNode*> Owner,
MachineBasicBlock *BB);
NodeAddr<FuncNode*> newFunc(MachineFunction *MF);
template <typename Predicate>
std::pair<NodeAddr<RefNode*>,NodeAddr<RefNode*>>
locateNextRef(NodeAddr<InstrNode*> IA, NodeAddr<RefNode*> RA,
Predicate P) const;
using BlockRefsMap = std::map<NodeId, RegisterSet>;
void buildStmt(NodeAddr<BlockNode*> BA, MachineInstr &In);
void recordDefsForDF(BlockRefsMap &PhiM, NodeAddr<BlockNode*> BA);
void buildPhis(BlockRefsMap &PhiM, RegisterSet &AllRefs,
NodeAddr<BlockNode*> BA);
void removeUnusedPhis();
void pushClobbers(NodeAddr<InstrNode*> IA, DefStackMap &DM);
void pushDefs(NodeAddr<InstrNode*> IA, DefStackMap &DM);
template <typename T> void linkRefUp(NodeAddr<InstrNode*> IA,
NodeAddr<T> TA, DefStack &DS);
template <typename Predicate> void linkStmtRefs(DefStackMap &DefM,
NodeAddr<StmtNode*> SA, Predicate P);
void linkBlockRefs(DefStackMap &DefM, NodeAddr<BlockNode*> BA);
void unlinkUseDF(NodeAddr<UseNode*> UA);
void unlinkDefDF(NodeAddr<DefNode*> DA);
void removeFromOwner(NodeAddr<RefNode*> RA) {
NodeAddr<InstrNode*> IA = RA.Addr->getOwner(*this);
IA.Addr->removeMember(RA, *this);
}
MachineFunction &MF;
const TargetInstrInfo &TII;
const TargetRegisterInfo &TRI;
const PhysicalRegisterInfo PRI;
const MachineDominatorTree &MDT;
const MachineDominanceFrontier &MDF;
const TargetOperandInfo &TOI;
RegisterAggr LiveIns;
NodeAddr<FuncNode*> Func;
NodeAllocator Memory;
std::map<MachineBasicBlock*,NodeAddr<BlockNode*>> BlockNodes;
LaneMaskIndex LMI;
};
template <typename Predicate>
NodeAddr<RefNode*> RefNode::getNextRef(RegisterRef RR, Predicate P,
bool NextOnly, const DataFlowGraph &G) {
auto NA = G.addr<NodeBase*>(getNext());
while (NA.Addr != this) {
if (NA.Addr->getType() == NodeAttrs::Ref) {
NodeAddr<RefNode*> RA = NA;
if (RA.Addr->getRegRef(G) == RR && P(NA))
return NA;
if (NextOnly)
break;
NA = G.addr<NodeBase*>(NA.Addr->getNext());
} else {
assert(NA.Addr->getType() == NodeAttrs::Code);
NodeAddr<CodeNode*> CA = NA;
NA = CA.Addr->getFirstMember(G);
}
}
return NodeAddr<RefNode*>();
}
template <typename Predicate>
NodeList CodeNode::members_if(Predicate P, const DataFlowGraph &G) const {
NodeList MM;
auto M = getFirstMember(G);
if (M.Id == 0)
return MM;
while (M.Addr != this) {
if (P(M))
MM.push_back(M);
M = G.addr<NodeBase*>(M.Addr->getNext());
}
return MM;
}
template <typename T>
struct Print {
Print(const T &x, const DataFlowGraph &g) : Obj(x), G(g) {}
const T &Obj;
const DataFlowGraph &G;
};
template <typename T>
struct PrintNode : Print<NodeAddr<T>> {
PrintNode(const NodeAddr<T> &x, const DataFlowGraph &g)
: Print<NodeAddr<T>>(x, g) {}
};
raw_ostream &operator<<(raw_ostream &OS, const Print<RegisterRef> &P);
raw_ostream &operator<<(raw_ostream &OS, const Print<NodeId> &P);
raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<DefNode *>> &P);
raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<UseNode *>> &P);
raw_ostream &operator<<(raw_ostream &OS,
const Print<NodeAddr<PhiUseNode *>> &P);
raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<RefNode *>> &P);
raw_ostream &operator<<(raw_ostream &OS, const Print<NodeList> &P);
raw_ostream &operator<<(raw_ostream &OS, const Print<NodeSet> &P);
raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<PhiNode *>> &P);
raw_ostream &operator<<(raw_ostream &OS,
const Print<NodeAddr<StmtNode *>> &P);
raw_ostream &operator<<(raw_ostream &OS,
const Print<NodeAddr<InstrNode *>> &P);
raw_ostream &operator<<(raw_ostream &OS,
const Print<NodeAddr<BlockNode *>> &P);
raw_ostream &operator<<(raw_ostream &OS,
const Print<NodeAddr<FuncNode *>> &P);
raw_ostream &operator<<(raw_ostream &OS, const Print<RegisterSet> &P);
raw_ostream &operator<<(raw_ostream &OS, const Print<RegisterAggr> &P);
raw_ostream &operator<<(raw_ostream &OS,
const Print<DataFlowGraph::DefStack> &P);
}
}
#endif