LLVM  10.0.0
DDG.cpp
Go to the documentation of this file.
1 //===- DDG.cpp - Data Dependence Graph -------------------------------------==//
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 // The implementation for the data dependence graph.
10 //===----------------------------------------------------------------------===//
11 #include "llvm/Analysis/DDG.h"
12 #include "llvm/ADT/SCCIterator.h"
13 #include "llvm/Analysis/LoopInfo.h"
16 
17 using namespace llvm;
18 
19 static cl::opt<bool>
20  CreatePiBlocks("ddg-pi-blocks", cl::init(true), cl::Hidden, cl::ZeroOrMore,
21  cl::desc("Create pi-block nodes."));
22 
23 #define DEBUG_TYPE "ddg"
24 
25 template class llvm::DGEdge<DDGNode, DDGEdge>;
26 template class llvm::DGNode<DDGNode, DDGEdge>;
28 
29 //===--------------------------------------------------------------------===//
30 // DDGNode implementation
31 //===--------------------------------------------------------------------===//
33 
35  llvm::function_ref<bool(Instruction *)> const &Pred,
36  InstructionListType &IList) const {
37  assert(IList.empty() && "Expected the IList to be empty on entry.");
38  if (isa<SimpleDDGNode>(this)) {
39  for (Instruction *I : cast<const SimpleDDGNode>(this)->getInstructions())
40  if (Pred(I))
41  IList.push_back(I);
42  } else if (isa<PiBlockDDGNode>(this)) {
43  for (const DDGNode *PN : cast<const PiBlockDDGNode>(this)->getNodes()) {
44  assert(!isa<PiBlockDDGNode>(PN) && "Nested PiBlocks are not supported.");
46  PN->collectInstructions(Pred, TmpIList);
47  IList.insert(IList.end(), TmpIList.begin(), TmpIList.end());
48  }
49  } else
50  llvm_unreachable("unimplemented type of node");
51  return !IList.empty();
52 }
53 
55  const char *Out;
56  switch (K) {
58  Out = "single-instruction";
59  break;
61  Out = "multi-instruction";
62  break;
64  Out = "pi-block";
65  break;
67  Out = "root";
68  break;
70  Out = "?? (error)";
71  break;
72  }
73  OS << Out;
74  return OS;
75 }
76 
78  OS << "Node Address:" << &N << ":" << N.getKind() << "\n";
79  if (isa<SimpleDDGNode>(N)) {
80  OS << " Instructions:\n";
81  for (const Instruction *I : cast<const SimpleDDGNode>(N).getInstructions())
82  OS.indent(2) << *I << "\n";
83  } else if (isa<PiBlockDDGNode>(&N)) {
84  OS << "--- start of nodes in pi-block ---\n";
85  auto &Nodes = cast<const PiBlockDDGNode>(&N)->getNodes();
86  unsigned Count = 0;
87  for (const DDGNode *N : Nodes)
88  OS << *N << (++Count == Nodes.size() ? "" : "\n");
89  OS << "--- end of nodes in pi-block ---\n";
90  } else if (!isa<RootDDGNode>(N))
91  llvm_unreachable("unimplemented type of node");
92 
93  OS << (N.getEdges().empty() ? " Edges:none!\n" : " Edges:\n");
94  for (auto &E : N.getEdges())
95  OS.indent(2) << *E;
96  return OS;
97 }
98 
99 //===--------------------------------------------------------------------===//
100 // SimpleDDGNode implementation
101 //===--------------------------------------------------------------------===//
102 
104  : DDGNode(NodeKind::SingleInstruction), InstList() {
105  assert(InstList.empty() && "Expected empty list.");
106  InstList.push_back(&I);
107 }
108 
110  : DDGNode(N), InstList(N.InstList) {
111  assert(((getKind() == NodeKind::SingleInstruction && InstList.size() == 1) ||
112  (getKind() == NodeKind::MultiInstruction && InstList.size() > 1)) &&
113  "constructing from invalid simple node.");
114 }
115 
117  : DDGNode(std::move(N)), InstList(std::move(N.InstList)) {
118  assert(((getKind() == NodeKind::SingleInstruction && InstList.size() == 1) ||
119  (getKind() == NodeKind::MultiInstruction && InstList.size() > 1)) &&
120  "constructing from invalid simple node.");
121 }
122 
123 SimpleDDGNode::~SimpleDDGNode() { InstList.clear(); }
124 
125 //===--------------------------------------------------------------------===//
126 // PiBlockDDGNode implementation
127 //===--------------------------------------------------------------------===//
128 
130  : DDGNode(NodeKind::PiBlock), NodeList(List) {
131  assert(!NodeList.empty() && "pi-block node constructed with an empty list.");
132 }
133 
135  : DDGNode(N), NodeList(N.NodeList) {
136  assert(getKind() == NodeKind::PiBlock && !NodeList.empty() &&
137  "constructing from invalid pi-block node.");
138 }
139 
141  : DDGNode(std::move(N)), NodeList(std::move(N.NodeList)) {
142  assert(getKind() == NodeKind::PiBlock && !NodeList.empty() &&
143  "constructing from invalid pi-block node.");
144 }
145 
147 
148 //===--------------------------------------------------------------------===//
149 // DDGEdge implementation
150 //===--------------------------------------------------------------------===//
151 
153  const char *Out;
154  switch (K) {
156  Out = "def-use";
157  break;
159  Out = "memory";
160  break;
162  Out = "rooted";
163  break;
165  Out = "?? (error)";
166  break;
167  }
168  OS << Out;
169  return OS;
170 }
171 
173  OS << "[" << E.getKind() << "] to " << &E.getTargetNode() << "\n";
174  return OS;
175 }
176 
177 //===--------------------------------------------------------------------===//
178 // DataDependenceGraph implementation
179 //===--------------------------------------------------------------------===//
181 
183  : DependenceGraphInfo(F.getName().str(), D) {
184  // Put the basic blocks in program order for correct dependence
185  // directions.
186  BasicBlockListType BBList;
187  for (auto &SCC : make_range(scc_begin(&F), scc_end(&F)))
188  for (BasicBlock * BB : SCC)
189  BBList.push_back(BB);
190  std::reverse(BBList.begin(), BBList.end());
191  DDGBuilder(*this, D, BBList).populate();
192 }
193 
195  DependenceInfo &D)
196  : DependenceGraphInfo(Twine(L.getHeader()->getParent()->getName() + "." +
197  L.getHeader()->getName())
198  .str(),
199  D) {
200  // Put the basic blocks in program order for correct dependence
201  // directions.
202  LoopBlocksDFS DFS(&L);
203  DFS.perform(&LI);
204  BasicBlockListType BBList;
205  for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
206  BBList.push_back(BB);
207  DDGBuilder(*this, D, BBList).populate();
208 }
209 
211  for (auto *N : Nodes) {
212  for (auto *E : *N)
213  delete E;
214  delete N;
215  }
216 }
217 
219  if (!DDGBase::addNode(N))
220  return false;
221 
222  // In general, if the root node is already created and linked, it is not safe
223  // to add new nodes since they may be unreachable by the root. However,
224  // pi-block nodes need to be added after the root node is linked, and they are
225  // always reachable by the root, because they represent components that are
226  // already reachable by root.
227  auto *Pi = dyn_cast<PiBlockDDGNode>(&N);
228  assert((!Root || Pi) &&
229  "Root node is already added. No more nodes can be added.");
230 
231  if (isa<RootDDGNode>(N))
232  Root = &N;
233 
234  if (Pi)
235  for (DDGNode *NI : Pi->getNodes())
236  PiBlockMap.insert(std::make_pair(NI, Pi));
237 
238  return true;
239 }
240 
242  if (PiBlockMap.find(&N) == PiBlockMap.end())
243  return nullptr;
244  auto *Pi = PiBlockMap.find(&N)->second;
245  assert(PiBlockMap.find(Pi) == PiBlockMap.end() &&
246  "Nested pi-blocks detected.");
247  return Pi;
248 }
249 
251  for (DDGNode *Node : G)
252  // Avoid printing nodes that are part of a pi-block twice. They will get
253  // printed when the pi-block is printed.
254  if (!G.getPiBlock(*Node))
255  OS << *Node << "\n";
256  OS << "\n";
257  return OS;
258 }
259 
261  return CreatePiBlocks;
262 }
263 
264 //===--------------------------------------------------------------------===//
265 // DDG Analysis Passes
266 //===--------------------------------------------------------------------===//
267 
268 /// DDG as a loop pass.
271  Function *F = L.getHeader()->getParent();
272  DependenceInfo DI(F, &AR.AA, &AR.SE, &AR.LI);
273  return std::make_unique<DataDependenceGraph>(L, AR.LI, DI);
274 }
275 AnalysisKey DDGAnalysis::Key;
276 
279  LPMUpdater &U) {
280  OS << "'DDG' for loop '" << L.getHeader()->getName() << "':\n";
281  OS << *AM.getResult<DDGAnalysis>(L, AR);
282  return PreservedAnalyses::all();
283 }
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
Data Dependency Graph.
Definition: DDG.h:302
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:777
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Data Dependency Graph Edge.
Definition: DDG.h:217
Data Dependence Graph Node The graph can represent the following types of nodes:
Definition: DDG.h:42
void push_back(const T &Elt)
Definition: SmallVector.h:211
const NodeType & getTargetNode() const
Retrieve the target node this edge connects to.
Definition: DirectedGraph.h:45
raw_ostream & indent(unsigned NumSpaces)
indent - Insert &#39;NumSpaces&#39; spaces.
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:99
virtual ~DDGNode()=0
Definition: DDG.cpp:32
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
F(f)
DependenceInfo - This class is the main dependence-analysis driver.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:195
Definition: BitVector.h:937
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
static StringRef getName(Value *V)
RPOIterator endRPO() const
Definition: LoopIterator.h:140
BlockT * getHeader() const
Definition: LoopInfo.h:105
Subclass of DDGNode representing a pi-block.
Definition: DDG.h:170
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
Definition: SCCIterator.h:228
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:265
const EdgeListTy & getEdges() const
Retrieve the outgoing edges for the node.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Definition: DDG.cpp:277
EdgeKind getKind() const
Get the edge kind.
Definition: DDG.h:245
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Definition: LoopInfo.cpp:1108
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
NodeType * Root
Definition: DDG.h:296
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
Represent an edge in the directed graph.
Definition: DirectedGraph.h:27
scc_iterator< T > scc_end(const T &G)
Construct the end iterator for a deduced graph type T.
Definition: SCCIterator.h:233
EdgeKind
The kind of edge in the DDG.
Definition: DDG.h:220
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const StringRef getName() const
Return the label that is used to name this graph.
Definition: DDG.h:276
NodeKind getKind() const
Getter for the kind of this node.
Definition: DDG.h:73
Determine the kind of a node from its type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
bool addNode(NodeType &N)
Add node N to the graph, if it&#39;s not added yet, and keep track of the root node as well as pi-blocks ...
Definition: DDG.cpp:218
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
std::unique_ptr< DataDependenceGraph > Result
Definition: DDG.h:407
Directed graph.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Encapsulate some common data and functionality needed for different variations of data dependence gra...
Definition: DDG.h:263
Represent a node in the directed graph.
Definition: DirectedGraph.h:70
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
friend class DDGBuilder
Definition: DDG.h:304
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
bool shouldCreatePiBlocks() const final override
Return true if creation of pi-blocks are supported and desired, and false otherwise.
Definition: DDG.cpp:260
Result run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR)
DDG as a loop pass.
Definition: DDG.cpp:269
Store the result of a depth first search within basic blocks contained by a single loop...
Definition: LoopIterator.h:97
const DependenceInfo DI
Definition: DDG.h:292
static void DFS(BasicBlock *Root, SetVector< BasicBlock *> &Set)
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:467
Analysis pass that builds the DDG for a loop.
Definition: DDG.h:405
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:509
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
const NodeList & List
Definition: RDFGraph.cpp:201
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:72
iterator end()
Definition: DenseMap.h:82
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
Definition: APInt.h:2096
Subclass of DDGNode representing single or multi-instruction nodes.
Definition: DDG.h:106
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool addNode(NodeType &N)
Add the given node N to the graph if it is not already present.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
Definition: LoopIterator.h:136
static const Function * getParent(const Value *V)
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
const PiBlockDDGNode * getPiBlock(const NodeType &N) const
If node N belongs to a pi-block return a pointer to the pi-block, otherwise return null...
Definition: DDG.cpp:241
A container for analyses that lazily runs them and caches their results.
static cl::opt< bool > CreatePiBlocks("ddg-pi-blocks", cl::init(true), cl::Hidden, cl::ZeroOrMore, cl::desc("Create pi-block nodes."))
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:71
bool collectInstructions(llvm::function_ref< bool(Instruction *)> const &Pred, InstructionListType &IList) const
Collect a list of instructions, in IList, for which predicate Pred evaluates to true when iterating o...
Definition: DDG.cpp:34