1//===- RDFGraph.cpp -------------------------------------------------------===// 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 7//===----------------------------------------------------------------------===// 9// Target-independent, SSA-based data flow graph for register data flow (RDF). 40// Printing functions. Have them here first, so that the rest of the code 45P.G.getPRI().print(
OS,
P.Obj);
120if (
NodeIdN =
P.Obj.Addr->getReachingDef())
123if (
NodeIdN =
P.Obj.Addr->getReachedDef())
126if (
NodeIdN =
P.Obj.Addr->getReachedUse())
129if (
NodeIdN =
P.Obj.Addr->getSibling())
137if (
NodeIdN =
P.Obj.Addr->getReachingDef())
140if (
NodeIdN =
P.Obj.Addr->getSibling())
148if (
NodeIdN =
P.Obj.Addr->getReachingDef())
151if (
NodeIdN =
P.Obj.Addr->getPredecessor())
154if (
NodeIdN =
P.Obj.Addr->getSibling())
160switch (
P.Obj.Addr->getKind()) {
162 OS << PrintNode<DefNode *>(
P.Obj,
P.G);
166 OS << PrintNode<PhiUseNode *>(
P.Obj,
P.G);
168 OS << PrintNode<UseNode *>(
P.Obj,
P.G);
175unsignedN =
P.Obj.size();
185unsignedN =
P.Obj.size();
196template <
typename T>
structPrintListV {
197 PrintListV(
constNodeList &L,
const DataFlowGraph &G) :
List(L),
G(
G) {}
201const DataFlowGraph &
G;
205raw_ostream &
operator<<(raw_ostream &
OS,
const PrintListV<T> &
P) {
206unsignedN =
P.List.size();
207for (NodeAddr<T>
A :
P.List) {
208 OS << PrintNode<T>(
A,
P.G);
215}
// end anonymous namespace 219 << PrintListV<RefNode *>(
P.Obj.Addr->members(
P.G),
P.G) <<
']';
225unsigned Opc =
MI.getOpcode();
226OS <<
Print(
P.Obj.Id,
P.G) <<
": " <<
P.G.getTII().getName(Opc);
227// Print the target for calls and branches (for readability). 228if (
MI.isCall() ||
MI.isBranch()) {
231 return Op.isMBB() || Op.isGlobal() || Op.isSymbol();
233if (
T !=
MI.operands_end()) {
237elseif (
T->isGlobal())
238OS <<
T->getGlobal()->getName();
239elseif (
T->isSymbol())
240OS <<
T->getSymbolName();
243OS <<
" [" << PrintListV<RefNode *>(
P.Obj.Addr->members(
P.G),
P.G) <<
']';
248switch (
P.Obj.Addr->getKind()) {
250 OS << PrintNode<PhiNode *>(
P.Obj,
P.G);
253 OS << PrintNode<StmtNode *>(
P.Obj,
P.G);
266auto PrintBBs = [&
OS](
const std::vector<int> &Ns) ->
void {
267unsignedN = Ns.size();
276 <<
" --- preds(" << NP <<
"): ";
278 Ns.push_back(
B->getNumber());
282OS <<
" succs(" << NS <<
"): ";
285 Ns.push_back(
B->getNumber());
289for (
autoI :
P.Obj.Addr->members(
P.G))
290 OS << PrintNode<InstrNode *>(
I,
P.G) <<
'\n';
297 <<
": Function: " <<
P.Obj.Addr->getCode()->getName() <<
'\n';
298for (
autoI :
P.Obj.Addr->members(
P.G))
299 OS << PrintNode<BlockNode *>(
I,
P.G) <<
'\n';
319for (
autoI =
P.Obj.top(),
E =
P.Obj.bottom();
I !=
E;) {
329// Node allocation functions. 331// Node allocator is like a slab memory allocator: it allocates blocks of 332// memory in sizes that are multiples of the size of a node. Each block has 333// the same size. Nodes are allocated from the currently active block, and 334// when it becomes full, a new one is created. 335// There is a mapping scheme between node id and its location in a block, 336// and within that block is described in the header file. 338void NodeAllocator::startNewBlock() {
340char *
P =
static_cast<char *
>(
T);
342// Check if the block index is still within the allowed range, i.e. less 343// than 2^N, where N is the number of bits in NodeId for the block index. 344// BitsPerIndex is the number of bits per node index. 345assert((Blocks.size() < ((
size_t)1 << (8 *
sizeof(
NodeId) - BitsPerIndex))) &&
346"Out of bits for block index");
350bool NodeAllocator::needNewBlock() {
354char *ActiveBegin = Blocks.back();
356returnIndex >= NodesPerBlock;
363uint32_t ActiveB = Blocks.size() - 1;
371 uintptr_t
A =
reinterpret_cast<uintptr_t
>(
P);
372for (
unsigned i = 0, n = Blocks.size(); i != n; ++i) {
373 uintptr_t
B =
reinterpret_cast<uintptr_t
>(Blocks[i]);
388// Insert node NA after "this" in the circular chain. 391// If NA is already "next", do nothing. 398// Fundamental node manipulator functions. 400// Obtain the register reference from a reference node. 409// Set the register reference in the reference node directly (for references 417// Set the register reference in the reference node based on a machine 418// operand (for references in statement nodes). 426// Get the owner of a given reference node. 430while (NA.
Addr !=
this) {
438// Connect the def node to the reaching def node. 442 DA.Addr->setReachedDef(Self);
445// Connect the use node to the reaching def node. 449 DA.Addr->setReachedUse(Self);
452// Get the first member of the code node. 459// Get the last member of the code node. 466// Add node NA at the end of the member list of the given code node. 474 NA.
Addr->setNext(Self);
479// Add node NA after member node MA in the given code node. 486// Remove member node NA from the given code node. 491// Special handling if the member to remove is the first member. 494// If it is the only member, set both first and last to 0. 497// Otherwise, advance the first member. 503while (MA.
Addr !=
this) {
506 MA.
Addr->setNext(NA.
Addr->getNext());
507// If the member to remove happens to be the last one, update the 518// Return the list of all members of the code node. 520staticauto True = [](
Node) ->
bool {
returntrue; };
524// Return the owner of the given instr node. 528while (NA.
Addr !=
this) {
537// Add the phi node PA to the given block node. 547// If the first member of the block is a statement, insert the phi as 550 PA.
Addr->setNext(M.Id);
552// If the first member is a phi, find the last phi, and append PA to it. 557 MN =
G.addr<
NodeBase *>(M.Addr->getNext());
566// Find the block node corresponding to the machine basic block BB in the 570auto EqBB = [BB](
Node NA) ->
bool {
returnBlock(NA).Addr->getCode() == BB; };
577// Get the block node for the entry block in the given function. 583// Target operand information. 586// For a given instruction, check if there are any bits of RR that can remain 587// unchanged across this def. 589unsigned OpNum)
const{
593// Check if the definition of RR produces an unspecified value. 595unsigned OpNum)
const{
601if (
Op.isDef() &&
Op.isDead())
606// Check if the given instruction specifically requires 608unsigned OpNum)
const{
609if (In.isCall() || In.isReturn() || In.isInlineAsm())
611// Check for a tail call. 614if (O.isGlobal() || O.isSymbol())
618if (
D.implicit_defs().empty() &&
D.implicit_uses().empty())
621// If there is a sub-register, treat the operand as non-fixed. Currently, 622// fixed registers are those that are listed in the descriptor as implicit 623// uses or defs, and those lists do not allow sub-registers. 624if (
Op.getSubReg() != 0)
628Op.isDef() ?
D.implicit_defs() :
D.implicit_uses();
633// The data flow graph construction. 641TRI(tri), PRI(tri, mf), MDT(mdt), MDF(mdf), TOI(*DefaultTOI),
649 : MF(mf),
TII(tii),
TRI(tri), PRI(tri, mf), MDT(mdt), MDF(mdf), TOI(toi),
652// The implementation of the definition stack. 653// Each register reference has its own definition stack. In particular, 654// for a register references "Reg" and "Reg:subreg" will each have their 655// own definition stacks. 657// Construct a stack iterator. 662// Initialize to bottom. 666// Initialize to the top, i.e. top-most non-delimiter (or 0, if empty). 667 Pos = DS.Stack.size();
668while (Pos > 0 && DS.isDelimiter(DS.Stack[Pos - 1]))
672// Return the size of the stack, including block delimiters. 680// Remove the top entry from the stack. Remove all intervening delimiters 681// so that after this, the stack is either empty, or the top of the stack 682// is a non-delimiter. 685unsignedP = nextDown(Stack.size());
689// Push a delimiter for block node N on the stack. 692 Stack.push_back(
Def(
nullptr,
N));
695// Remove all nodes from the top of the stack, until the delimited for 696// block node N is encountered. Remove the delimiter as well. In effect, 697// this will remove from the stack all definitions from block N. 700unsignedP = Stack.size();
702bool Found = isDelimiter(Stack[
P - 1],
N);
707// This will also remove the delimiter, if found. 711// Move the stack iterator up by one. 712unsigned DataFlowGraph::DefStack::nextUp(
unsignedP)
const{
713// Get the next valid position after P (skipping all delimiters). 714// The input position P does not have to point to a non-delimiter. 715unsigned SS = Stack.size();
720 IsDelim = isDelimiter(Stack[
P - 1]);
721 }
while (
P < SS && IsDelim);
726// Move the stack iterator down by one. 727unsigned DataFlowGraph::DefStack::nextDown(
unsignedP)
const{
728// Get the preceding valid position before P (skipping all delimiters). 729// The input position P does not have to point to a non-delimiter. 731bool IsDelim = isDelimiter(Stack[
P - 1]);
735 IsDelim = isDelimiter(Stack[
P - 1]);
736 }
while (
P > 0 && IsDelim);
741// Register information. 743RegisterAggr DataFlowGraph::getLandingPadLiveIns()
const{
744 RegisterAggr LR(
getPRI());
746constConstant *PF =
F.hasPersonalityFn() ?
F.getPersonalityFn() :
nullptr;
748if (
RegisterId R = TLI.getExceptionPointerRegister(PF))
749 LR.insert(RegisterRef(R));
751if (
RegisterId R = TLI.getExceptionSelectorRegister(PF))
752 LR.insert(RegisterRef(R));
757// Node management functions. 759// Get the pointer to the node with the id N. 766// Get the id of the node at the address P. 773// Allocate a new node and set the attributes to Attrs. 777P.Addr->setAttrs(Attrs);
781// Make a copy of the given node B, except for the data-flow links, which 783Node DataFlowGraph::cloneNode(
constNodeB) {
785 memcpy(NA.Addr,
B.Addr,
sizeof(NodeBase));
786// Ref nodes need to have the data-flow links reset. 789RA.Addr->setReachingDef(0);
790RA.Addr->setSibling(0);
793 DA.Addr->setReachedDef(0);
794 DA.Addr->setReachedUse(0);
800// Allocation routines for specific node types/kinds. 804 UA.Addr->setRegRef(&
Op, *
this);
808PhiUse DataFlowGraph::newPhiUse(
Phi Owner, RegisterRef RR,
Block PredB,
812 PUA.Addr->setRegRef(RR, *
this);
813 PUA.Addr->setPredecessor(PredB.Id);
819DA.Addr->setRegRef(&
Op, *
this);
826DA.Addr->setRegRef(RR, *
this);
830Phi DataFlowGraph::newPhi(
Block Owner) {
832 Owner.Addr->addPhi(PA, *
this);
836Stmt DataFlowGraph::newStmt(
Block Owner, MachineInstr *
MI) {
838 SA.Addr->setCode(
MI);
839 Owner.Addr->addMember(SA, *
this);
843Block DataFlowGraph::newBlock(
Func Owner, MachineBasicBlock *BB) {
845 BA.Addr->setCode(BB);
846 Owner.Addr->addMember(BA, *
this);
850Func DataFlowGraph::newFunc(MachineFunction *MF) {
852 FA.Addr->setCode(MF);
856// Build the data flow graph. 861 ReservedRegs =
MRI.getReservedRegs();
864auto Insert = [](
auto &Set,
auto &&
Range) {
869 std::set<RegisterId> BaseSet;
871// Insert every register. 881if (SkipReserved && ReservedRegs[R])
886// Track set in Config overrides everything. 888if (SkipReserved && ReservedRegs[R])
894 TheFunc = newFunc(&MF);
900Block BA = newBlock(TheFunc, &
B);
901 BlockNodes.insert(std::make_pair(&
B, BA));
912// Collect function live-ins and entry block live-ins. 915for (std::pair<MCRegister, Register>
P :
MRI.liveins())
917if (
MRI.tracksLiveness()) {
922// Add function-entry phi nodes for the live-in registers. 924if (RR.isReg() && !
isTracked(RR))
// isReg is likely guaranteed 928Def DA = newDef(PA, RR, PhiFlags);
929 PA.
Addr->addMember(DA, *
this);
932// Add phis for landing pads. 933// Landing pads, unlike usual backs blocks, are not entered through 934// branches in the program, or fall-throughs from other blocks. They 935// are entered from the exception handling runtime and target's ABI 936// may define certain registers as defined on entry to such a block. 938if (!EHRegs.
empty()) {
944// Prepare a list of NodeIds of the block's predecessors. 949// Build phi nodes for each live-in. 956Def DA = newDef(PA, RR, PhiFlags);
957 PA.
Addr->addMember(DA, *
this);
958// Add uses (no reaching defs for phi uses): 959for (
Block PBA : Preds) {
960PhiUse PUA = newPhiUse(PA, RR, PBA);
961 PA.
Addr->addMember(PUA, *
this);
967// Build a map "PhiM" which will contain, for each block, the set 968// of references that will require phi definitions in that block. 971 recordDefsForDF(PhiM, BA);
975// Link all the refs. This will recursively traverse the dominator tree. 977 linkBlockRefs(
DM, EA);
979// Finally, remove all unused phi nodes. 1000// For each stack in the map DefM, push the delimiter for block B on it. 1002// Push block delimiters. 1004P.second.start_block(
B);
1007// Remove all definitions coming from block B from each stack in DefM. 1009// Pop all defs from this block from the definition stack. Defs that were 1010// added to the map during the traversal of instructions will not have a 1011// delimiter, but for those, the whole stack will be emptied. 1013P.second.clear_block(
B);
1015// Finally, remove empty stacks from the map. 1016for (
autoI = DefM.begin(),
E = DefM.end(), NextI =
I;
I !=
E;
I = NextI) {
1017 NextI = std::next(
I);
1018// This preserves the validity of iterators other than I. 1019if (
I->second.empty())
1024// Push all definitions from the instruction node IA to an appropriate 1027 pushClobbers(IA, DefM);
1031// Push all definitions from the instruction node IA to an appropriate 1035 std::set<RegisterId> Defined;
1037// The important objectives of this function are: 1038// - to be able to handle instructions both while the graph is being 1039// constructed, and after the graph has been constructed, and 1040// - maintain proper ordering of definitions on the stack for each 1041// register reference: 1042// - if there are two or more related defs in IA (i.e. coming from 1043// the same machine operand), then only push one def on the stack, 1044// - if there are multiple unrelated defs of non-overlapping 1045// subregisters of S, then the stack for S will have both (in an 1046// unspecified order), but the order does not matter from the data- 1047// -flow perspective. 1049for (
Def DA : IA.Addr->members_if(
IsDef, *
this)) {
1050if (Visited.count(DA.Id))
1059// Push the definition on the stack for the register and all aliases. 1060// The def stack traversal in linkNodeUp will check the exact aliasing. 1061 DefM[RR.
Reg].push(DA);
1062 Defined.insert(RR.
Reg);
1066// Check that we don't push the same def twice. 1068if (!Defined.count(
A))
1071// Mark all the related defs as visited. 1073 Visited.insert(
T.Id);
1077// Push all definitions from the instruction node IA to an appropriate 1082 std::set<RegisterId> Defined;
1085// The important objectives of this function are: 1086// - to be able to handle instructions both while the graph is being 1087// constructed, and after the graph has been constructed, and 1088// - maintain proper ordering of definitions on the stack for each 1089// register reference: 1090// - if there are two or more related defs in IA (i.e. coming from 1091// the same machine operand), then only push one def on the stack, 1092// - if there are multiple unrelated defs of non-overlapping 1093// subregisters of S, then the stack for S will have both (in an 1094// unspecified order), but the order does not matter from the data- 1095// -flow perspective. 1097for (
Def DA :
IA.Addr->members_if(
IsDef, *
this)) {
1098if (Visited.count(
DA.Id))
1104Def PDA = Rel.front();
1105 RegisterRef RR = PDA.Addr->getRegRef(*
this);
1107// Assert if the register is defined in two or more unrelated defs. 1108// This could happen if there are two or more def operands defining it. 1109if (!Defined.insert(RR.Reg).second) {
1110 MachineInstr *
MI =
Stmt(IA).Addr->getCode();
1111dbgs() <<
"Multiple definitions of register: " <<
Print(RR, *
this)
1117// Push the definition on the stack for the register and all aliases. 1118// The def stack traversal in linkNodeUp will check the exact aliasing. 1119 DefM[RR.Reg].push(DA);
1123// Check that we don't push the same def twice. 1127// Mark all the related defs as visited. 1129 Visited.insert(
T.Id);
1133// Return the list of all reference nodes related to RA, including RA itself. 1134// See "getNextRelated" for the meaning of a "related reference". 1143 }
while (
RA.Id != 0 &&
RA.Id != Start);
1147// Clear all information in the graph. 1148void DataFlowGraph::reset() {
1151 TrackedUnits.clear();
1152 ReservedRegs.
clear();
1156// Return the next reference node in the instruction node IA that is related 1157// to RA. Conceptually, two reference nodes are related if they refer to the 1158// same instance of a register access, but differ in flags or other minor 1159// characteristics. Specific examples of related nodes are shadow reference 1161// Return the equivalent of nullptr if there are no more related references. 1165auto IsRelated = [
this,
RA](
Ref TA) ->
bool {
1166if (TA.Addr->getKind() !=
RA.Addr->getKind())
1169RA.Addr->getRegRef(*
this))) {
1177autoCond = [&IsRelated,
RA](
Ref TA) ->
bool {
1178return IsRelated(TA) && &
RA.Addr->getOp() == &TA.Addr->getOp();
1180returnRA.Addr->getNextRef(RR,
Cond,
true, *
this);
1184autoCond = [&IsRelated,
RA](
Ref TA) ->
bool {
1189// For phi uses, compare predecessor blocks. 1190returnPhiUse(TA).Addr->getPredecessor() ==
1193returnRA.Addr->getNextRef(RR,
Cond,
true, *
this);
1196// Find the next node related to RA in IA that satisfies condition P. 1197// If such a node was found, return a pair where the second element is the 1198// located node. If such a node does not exist, return a pair where the 1199// first element is the element after which such a node should be inserted, 1200// and the second element is a null-address. 1201template <
typename Predicate>
1202std::pair<Ref, Ref> DataFlowGraph::locateNextRef(
Instr IA,
RefRA,
1210if (NA.
Id == 0 || NA.
Id == Start)
1217if (NA.
Id != 0 && NA.
Id != Start)
1218return std::make_pair(
RA, NA);
1219return std::make_pair(
RA,
Ref());
1222// Get the next shadow node in IA corresponding to RA, and optionally create 1223// such a node if it does not exist. 1228auto IsShadow = [Flags](
Ref TA) ->
bool {
1229return TA.Addr->getFlags() == Flags;
1231auto Loc = locateNextRef(IA,
RA, IsShadow);
1232if (Loc.second.Id != 0 || !Create)
1235// Create a copy of RA and mark is as shadow. 1236Ref NA = cloneNode(
RA);
1238 IA.Addr->addMemberAfter(Loc.first, NA, *
this);
1242// Create a new statement node in the block node BA that corresponds to 1243// the machine instruction MI. 1245Stmt SA = newStmt(BA, &In);
1253if (
Op.isGlobal() ||
Op.isSymbol())
1255// Assume indirect branches are calls. This is for the purpose of 1256// keeping implicit operands, and so it won't hurt on intra-function 1257// indirect branches. 1258if (In.isIndirectBranch())
1264auto isDefUndef = [
this](
const MachineInstr &In, RegisterRef DR) ->
bool {
1265// This instruction defines DR. Check if there is a use operand that 1266// would make DR live on entry to the instruction. 1267for (
const MachineOperand &
Op : In.all_uses()) {
1268if (
Op.getReg() == 0 ||
Op.isUndef())
1271if (
getPRI().alias(DR, UR))
1277bool IsCall = isCall(In);
1278unsigned NumOps =
In.getNumOperands();
1280// Avoid duplicate implicit defs. This will not detect cases of implicit 1281// defs that define registers that overlap, but it is not clear how to 1282// interpret that in the absence of explicit defs. Overlapping explicit 1283// defs are likely illegal already. 1285// Process explicit defs first. 1286for (
unsigned OpN = 0; OpN < NumOps; ++OpN) {
1287 MachineOperand &
Op =
In.getOperand(OpN);
1288if (!
Op.isReg() || !
Op.isDef() ||
Op.isImplicit())
1291if (!R || !
R.isPhysical() || !
isTracked(RegisterRef(R)))
1296// If the def is preserving, check if it is also undefined. 1304if (IsCall &&
Op.isDead())
1307 SA.
Addr->addMember(DA, *
this);
1308assert(!DoneDefs.test(R));
1312// Process reg-masks (as clobbers). 1314for (
unsigned OpN = 0; OpN < NumOps; ++OpN) {
1315 MachineOperand &
Op =
In.getOperand(OpN);
1320 SA.
Addr->addMember(DA, *
this);
1321// Record all clobbered registers in DoneDefs. 1323for (
unsigned i = 1, e = TRI.
getNumRegs(); i != e; ++i) {
1326if (!(RM[i / 32] & (1u << (i % 32))))
1327 DoneClobbers.set(i);
1331// Process implicit defs, skipping those that have already been added 1333for (
unsigned OpN = 0; OpN < NumOps; ++OpN) {
1334 MachineOperand &
Op =
In.getOperand(OpN);
1335if (!
Op.isReg() || !
Op.isDef() || !
Op.isImplicit())
1338if (!R || !
R.isPhysical() || !
isTracked(RegisterRef(R)) || DoneDefs.test(R))
1344// If the def is preserving, check if it is also undefined. 1345if (isDefUndef(In, RR))
1352if (IsCall &&
Op.isDead()) {
1353if (DoneClobbers.test(R))
1358 SA.
Addr->addMember(DA, *
this);
1362for (
unsigned OpN = 0; OpN < NumOps; ++OpN) {
1363 MachineOperand &
Op =
In.getOperand(OpN);
1364if (!
Op.isReg() || !
Op.isUse())
1367if (!R || !
R.isPhysical() || !
isTracked(RegisterRef(R)))
1374Use UA = newUse(SA,
Op, Flags);
1375 SA.
Addr->addMember(UA, *
this);
1379// Scan all defs in the block node BA and record in PhiM the locations of 1380// phi nodes corresponding to these defs. 1381void DataFlowGraph::recordDefsForDF(BlockRefsMap &PhiM,
Block BA) {
1382// Check all defs from block BA and record them in each block in BA's 1383// iterated dominance frontier. This information will later be used to 1385 MachineBasicBlock *BB = BA.Addr->getCode();
1387auto DFLoc = MDF.
find(BB);
1388if (DFLoc == MDF.
end() || DFLoc->second.empty())
1391// Traverse all instructions in the block and collect the set of all 1392// defined references. For each reference there will be a phi created 1393// in the block's iterated dominance frontier. 1394// This is done to make sure that each defined reference gets only one 1395// phi node, even if it is defined multiple times. 1396 RegisterAggr Defs(
getPRI());
1397for (
Instr IA : BA.Addr->members(*
this)) {
1399 RegisterRef RR =
RA.Addr->getRegRef(*
this);
1405// Calculate the iterated dominance frontier of BB. 1407 SetVector<MachineBasicBlock *> IDF(
DF.begin(),
DF.end());
1408for (
unsigned i = 0; i < IDF.size(); ++i) {
1409autoF = MDF.
find(IDF[i]);
1411 IDF.insert(
F->second.begin(),
F->second.end());
1414// Finally, add the set of defs to each block in the iterated dominance 1416for (
auto *DB : IDF) {
1418 PhiM[DBA.Id].insert(Defs);
1422// Given the locations of phi nodes in the map PhiM, create the phi nodes 1423// that are located in the block node BA. 1424void DataFlowGraph::buildPhis(BlockRefsMap &PhiM,
Block BA) {
1425// Check if this blocks has any DF defs, i.e. if there are any defs 1426// that this block is in the iterated dominance frontier of. 1427auto HasDF = PhiM.find(BA.Id);
1428if (HasDF == PhiM.end() || HasDF->second.empty())
1431// Prepare a list of NodeIds of the block's predecessors. 1433const MachineBasicBlock *
MBB = BA.Addr->getCode();
1434for (MachineBasicBlock *
PB :
MBB->predecessors())
1437const RegisterAggr &Defs = PhiM[BA.Id];
1440for (RegisterRef RR : Defs.refs()) {
1442 PA.Addr->addMember(newDef(PA, RR, PhiFlags), *
this);
1445for (
Block PBA : Preds) {
1446 PA.Addr->addMember(newPhiUse(PA, RR, PBA), *
this);
1451// Remove any unneeded phi nodes that were created during the build process. 1452void DataFlowGraph::removeUnusedPhis() {
1453// This will remove unused phis, i.e. phis where each def does not reach 1454// any uses or other defs. This will not detect or remove circular phi 1455// chains that are otherwise dead. Unused/dead phis are created during 1456// the build process and this function is intended to remove these cases 1457// that are easily determinable to be unnecessary. 1459 SetVector<NodeId> PhiQ;
1461for (
autoP : BA.Addr->members_if(
IsPhi, *
this))
1465staticauto HasUsedDef = [](
NodeList &Ms) ->
bool {
1470if (
DA.Addr->getReachedDef() != 0 ||
DA.Addr->getReachedUse() != 0)
1476// Any phi, if it is removed, may affect other phis (make them dead). 1477// For each removed phi, collect the potentially affected phis and add 1478// them back to the queue. 1479while (!PhiQ.empty()) {
1480auto PA = addr<PhiNode *>(PhiQ[0]);
1482NodeList Refs = PA.Addr->members(*
this);
1483if (HasUsedDef(Refs))
1486if (
NodeId RD =
RA.Addr->getReachingDef()) {
1487autoRDA = addr<DefNode *>(RD);
1488Instr OA =
RDA.Addr->getOwner(*
this);
1492if (
RA.Addr->isDef())
1497Block BA = PA.Addr->getOwner(*
this);
1498 BA.Addr->removeMember(PA, *
this);
1502// For a given reference node TA in an instruction node IA, connect the 1503// reaching def of TA to the appropriate def node. Create any shadow nodes 1505template <
typename T>
1506void DataFlowGraph::linkRefUp(
Instr IA, NodeAddr<T> TA, DefStack &DS) {
1509 RegisterRef RR =
TA.Addr->getRegRef(*
this);
1512// References from the def stack that have been examined so far. 1513 RegisterAggr Defs(
getPRI());
1515for (
autoI =
DS.top(),
E =
DS.bottom();
I !=
E;
I.down()) {
1516 RegisterRef QR =
I->Addr->getRegRef(*
this);
1518// Skip all defs that we have already seen. 1519// If this completes a cover of RR, stop the stack traversal. 1520bool Seen = Defs.hasCoverOf(QR);
1524bool Cover = Defs.insert(QR).hasCoverOf(RR);
1529// Pick the reached node. 1533// Mark the existing ref as "shadow" and create a new shadow. 1539 TAP.Addr->linkToDef(TAP.Id,
RDA);
1546// Create data-flow links for all reference nodes in the statement node SA. 1547template <
typename Predicate>
1553// Link all nodes (upwards in the data-flow) with their reaching defs. 1554for (
RefRA : SA.Addr->members_if(
P, *
this)) {
1557 RegisterRef RR =
RA.Addr->getRegRef(*
this);
1559// Do not expect multiple defs of the same reference. 1564autoF = DefM.find(RR.Reg);
1567 DefStack &
DS =
F->second;
1569 linkRefUp<UseNode *>(SA,
RA, DS);
1571 linkRefUp<DefNode *>(SA,
RA, DS);
1577// Create data-flow links for all instructions in the block node BA. This 1578// will include updating any phi nodes in BA. 1580// Push block delimiters. 1583auto IsClobber = [](
RefRA) ->
bool {
1586auto IsNoClobber = [](
RefRA) ->
bool {
1590assert(BA.Addr &&
"block node address is needed to create a data-flow link");
1591// For each non-phi instruction in the block, link all the defs and uses 1592// to their reaching defs. For any member of the block (including phis), 1593// push the defs on the corresponding stacks. 1594for (
Instr IA : BA.Addr->members(*
this)) {
1595// Ignore phi nodes here. They will be linked part by part from the 1598 linkStmtRefs(DefM, IA,
IsUse);
1599 linkStmtRefs(DefM, IA, IsClobber);
1602// Push the definitions on the stack. 1603 pushClobbers(IA, DefM);
1606 linkStmtRefs(DefM, IA, IsNoClobber);
1611// Recursively process all children in the dominator tree. 1614 MachineBasicBlock *SB =
I->getBlock();
1616 linkBlockRefs(DefM, SBA);
1619// Link the phi uses from the successor blocks. 1620auto IsUseForBA = [BA](
Node NA) ->
bool {
1624returnPhiUse(NA).Addr->getPredecessor() == BA.Id;
1627 RegisterAggr EHLiveIns = getLandingPadLiveIns();
1628 MachineBasicBlock *
MBB = BA.Addr->getCode();
1630for (MachineBasicBlock *SB :
MBB->successors()) {
1631bool IsEHPad = SB->isEHPad();
1633for (
Instr IA : SBA.Addr->members_if(
IsPhi, *
this)) {
1634// Do not link phi uses for landing pad live-ins. 1636// Find what register this phi is for. 1637RefRA =
IA.Addr->getFirstMember(*
this);
1639if (EHLiveIns.hasCoverOf(
RA.Addr->getRegRef(*
this)))
1642// Go over each phi use associated with MBB, and link it. 1643for (
auto U :
IA.Addr->members_if(IsUseForBA, *
this)) {
1645 RegisterRef RR = PUA.Addr->getRegRef(*
this);
1646 linkRefUp<UseNode *>(IA, PUA, DefM[RR.Reg]);
1651// Pop all defs from this block from the definition stacks. 1655// Remove the use node UA from any data-flow and structural links. 1656void DataFlowGraph::unlinkUseDF(
Use UA) {
1657NodeId RD = UA.Addr->getReachingDef();
1658NodeId Sib = UA.Addr->getSibling();
1665autoRDA = addr<DefNode *>(RD);
1666autoTA = addr<UseNode *>(
RDA.Addr->getReachedUse());
1667if (
TA.Id == UA.Id) {
1668RDA.Addr->setReachedUse(Sib);
1675TA.Addr->setSibling(UA.Addr->getSibling());
1678TA = addr<UseNode *>(S);
1682// Remove the def node DA from any data-flow and structural links. 1683void DataFlowGraph::unlinkDefDF(
Def DA) {
1691// ... -- | DA | -- ... -- 0 : sibling chain of DA 1696// | ... : Siblings (defs) 1700// ... : sibling chain of reached uses 1702NodeId RD =
DA.Addr->getReachingDef();
1704// Visit all siblings of the reached def and reset their reaching defs. 1705// Also, defs reached by DA are now "promoted" to being reached by RD, 1706// so all of them will need to be spliced into the sibling chain where 1711autoRA = addr<RefNode *>(
N);
1712// Keep the nodes in the exact sibling order. 1714N =
RA.Addr->getSibling();
1718NodeList ReachedDefs = getAllNodes(
DA.Addr->getReachedDef());
1719NodeList ReachedUses = getAllNodes(
DA.Addr->getReachedUse());
1722for (
RefI : ReachedDefs)
1723I.Addr->setSibling(0);
1724for (
RefI : ReachedUses)
1725I.Addr->setSibling(0);
1727for (
DefI : ReachedDefs)
1728I.Addr->setReachingDef(RD);
1729for (
UseI : ReachedUses)
1730I.Addr->setReachingDef(RD);
1738// Update the reaching def node and remove DA from the sibling list. 1739autoRDA = addr<DefNode *>(RD);
1740autoTA = addr<DefNode *>(
RDA.Addr->getReachedDef());
1742// If DA is the first reached def, just update the RD's reached def 1743// to the DA's sibling. 1744RDA.Addr->setReachedDef(Sib);
1746// Otherwise, traverse the sibling list of the reached defs and remove 1751TA.Addr->setSibling(Sib);
1754TA = addr<DefNode *>(S);
1758// Splice the DA's reached defs into the RDA's reached def chain. 1759if (!ReachedDefs.empty()) {
1760autoLast =
Def(ReachedDefs.back());
1761Last.Addr->setSibling(
RDA.Addr->getReachedDef());
1762RDA.Addr->setReachedDef(ReachedDefs.front().Id);
1764// Splice the DA's reached uses into the RDA's reached use chain. 1765if (!ReachedUses.empty()) {
1766autoLast =
Use(ReachedUses.back());
1767Last.Addr->setSibling(
RDA.Addr->getReachedUse());
1768RDA.Addr->setReachedUse(ReachedUses.front().Id);
1779for (
Ref R : S.
Addr->members(*
this)) {
1782if (IgnoreReserved && RR.
isReg() && ReservedRegs[RR.
idx()])
1788if (!
Op.isReg() && !
Op.isRegMask())
1796}
// end namespace llvm::rdf unsigned const MachineRegisterInfo * MRI
ReachingDefAnalysis & RDA
This file implements the BitVector class.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
DenseMap< Block *, BlockRelaxAux > Blocks
const HexagonInstrInfo * TII
A common definition of LaneBitmask for use in TableGen and CodeGen.
unsigned const TargetRegisterInfo * TRI
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SI optimize exec mask operations pre RA
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file describes how to lower LLVM code to machine code.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
void clear()
clear - Removes all bits from the bitvector.
LLVM_ATTRIBUTE_RETURNS_NONNULL void * Allocate(size_t Size, Align Alignment)
Allocate space at the specified alignment.
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it,...
This class represents an Operation in the Expression.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Describe properties that are true of each instruction in the target description file.
unsigned getNumRegs() const
Return the number of registers this target has (useful for sizing arrays holding per register informa...
unsigned pred_size() const
iterator_range< livein_iterator > liveins() const
unsigned succ_size() const
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
iterator find(MachineBasicBlock *B)
DominanceFrontierBase< MachineBasicBlock, false >::DomSetType DomSetType
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & front() const
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Wrapper class representing virtual and physical registers.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
virtual bool isPredicated(const MachineInstr &MI) const
Returns true if the instruction is already predicated.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
MCRegister getSubReg(MCRegister Reg, unsigned Idx) const
Returns the physical register number of sub-register "Index" for physical register RegNo.
virtual const TargetLowering * getTargetLowering() const
This class implements an extremely fast bulk output stream that can only output to a stream.
This class provides various memory handling functions that manipulate MemoryBlock instances.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
NodeAddr< InstrNode * > Instr
NodeAddr< StmtNode * > Stmt
NodeAddr< RefNode * > Ref
NodeAddr< PhiNode * > Phi
std::set< RegisterRef > RegisterSet
Print(const T &, const DataFlowGraph &) -> Print< T >
NodeAddr< PhiUseNode * > PhiUse
NodeAddr< DefNode * > Def
NodeAddr< FuncNode * > Func
NodeAddr< BlockNode * > Block
NodeAddr< NodeBase * > Node
static void printRefHeader(raw_ostream &OS, const Ref RA, const DataFlowGraph &G)
raw_ostream & operator<<(raw_ostream &OS, const Print< RegisterRef > &P)
NodeAddr< UseNode * > Use
bool disjoint(const std::set< T > &A, const std::set< T > &B)
std::set< NodeId > NodeSet
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
DWARFExpression::Operation Op
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
Implement std::hash so that hash_code can be used in STL containers.
static constexpr LaneBitmask getAll()
void addPhi(Phi PA, const DataFlowGraph &G)
NodeList members_if(Predicate P, const DataFlowGraph &G) const
void removeMember(Node NA, const DataFlowGraph &G)
NodeList members(const DataFlowGraph &G) const
void addMember(Node NA, const DataFlowGraph &G)
Node getFirstMember(const DataFlowGraph &G) const
void addMemberAfter(Node MA, Node NA, const DataFlowGraph &G)
Node getLastMember(const DataFlowGraph &G) const
SmallVector< const TargetRegisterClass * > Classes
std::set< RegisterId > TrackRegs
void clear_block(NodeId N)
void start_block(NodeId N)
NodeId id(const NodeBase *P) const
void unlinkUse(Use UA, bool RemoveFromOwner)
void releaseBlock(NodeId B, DefStackMap &DefM)
Ref getNextRelated(Instr IA, Ref RA) const
bool isTracked(RegisterRef RR) const
RegisterRef makeRegRef(unsigned Reg, unsigned Sub) const
static bool IsDef(const Node BA)
DataFlowGraph(MachineFunction &mf, const TargetInstrInfo &tii, const TargetRegisterInfo &tri, const MachineDominatorTree &mdt, const MachineDominanceFrontier &mdf)
Ref getNextShadow(Instr IA, Ref RA, bool Create)
static bool IsPhi(const Node BA)
NodeList getRelatedRefs(Instr IA, Ref RA) const
void unlinkDef(Def DA, bool RemoveFromOwner)
static bool IsUse(const Node BA)
const PhysicalRegisterInfo & getPRI() const
void markBlock(NodeId B, DefStackMap &DefM)
NodeBase * ptr(NodeId N) const
Block findBlock(MachineBasicBlock *BB) const
bool hasUntrackedRef(Stmt S, bool IgnoreReserved=true) const
std::unordered_map< RegisterId, DefStack > DefStackMap
void pushAllDefs(Instr IA, DefStackMap &DM)
void linkToDef(NodeId Self, Def DA)
MachineFunction * getCode() const
Block findBlock(const MachineBasicBlock *BB, const DataFlowGraph &G) const
Block getEntryBlock(const DataFlowGraph &G)
Node getOwner(const DataFlowGraph &G)
NodeId id(const NodeBase *P) const
static uint16_t flags(uint16_t T)
static uint16_t kind(uint16_t T)
static uint16_t type(uint16_t T)
const TargetRegisterInfo & getTRI() const
bool equal_to(RegisterRef A, RegisterRef B) const
void setRegRef(RegisterRef RR, DataFlowGraph &G)
RegisterRef getRegRef(const DataFlowGraph &G) const
Node getOwner(const DataFlowGraph &G)
iterator_range< ref_iterator > refs() const
RegisterAggr & insert(RegisterRef RR)
constexpr unsigned idx() const
constexpr bool isReg() const
static constexpr bool isMaskId(unsigned Id)
static constexpr bool isRegId(unsigned Id)
virtual bool isFixedReg(const MachineInstr &In, unsigned OpNum) const
const TargetInstrInfo & TII
virtual bool isPreserving(const MachineInstr &In, unsigned OpNum) const
virtual bool isClobbering(const MachineInstr &In, unsigned OpNum) const
void linkToDef(NodeId Self, Def DA)