1//===-- llvm/Support/CFG.h - Process LLVM structures as graphs --*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines specializations of GraphTraits that allow Function and
11// BasicBlock graphs to be treated as proper graphs for generic algorithms.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CFG_H
16#define LLVM_SUPPORT_CFG_H
17
18#include "llvm/ADT/GraphTraits.h"
19#include "llvm/Function.h"
20#include "llvm/InstrTypes.h"
21
22namespace llvm {
23
24//===----------------------------------------------------------------------===//
25// BasicBlock pred_iterator definition
26//===----------------------------------------------------------------------===//
27
28template <class Ptr, class USE_iterator> // Predecessor Iterator
29class PredIterator : public std::iterator<std::forward_iterator_tag,
30                                          Ptr, ptrdiff_t, Ptr*, Ptr*> {
31  typedef std::iterator<std::forward_iterator_tag, Ptr, ptrdiff_t, Ptr*,
32                                                                    Ptr*> super;
33  typedef PredIterator<Ptr, USE_iterator> Self;
34  USE_iterator It;
35
36  inline void advancePastNonTerminators() {
37    // Loop to ignore non terminator uses (for example BlockAddresses).
38    while (!It.atEnd() && !isa<TerminatorInst>(*It))
39      ++It;
40  }
41
42public:
43  typedef typename super::pointer pointer;
44  typedef typename super::reference reference;
45
46  PredIterator() {}
47  explicit inline PredIterator(Ptr *bb) : It(bb->use_begin()) {
48    advancePastNonTerminators();
49  }
50  inline PredIterator(Ptr *bb, bool) : It(bb->use_end()) {}
51
52  inline bool operator==(const Self& x) const { return It == x.It; }
53  inline bool operator!=(const Self& x) const { return !operator==(x); }
54
55  inline reference operator*() const {
56    assert(!It.atEnd() && "pred_iterator out of range!");
57    return cast<TerminatorInst>(*It)->getParent();
58  }
59  inline pointer *operator->() const { return &operator*(); }
60
61  inline Self& operator++() {   // Preincrement
62    assert(!It.atEnd() && "pred_iterator out of range!");
63    ++It; advancePastNonTerminators();
64    return *this;
65  }
66
67  inline Self operator++(int) { // Postincrement
68    Self tmp = *this; ++*this; return tmp;
69  }
70
71  /// getOperandNo - Return the operand number in the predecessor's
72  /// terminator of the successor.
73  unsigned getOperandNo() const {
74    return It.getOperandNo();
75  }
76
77  /// getUse - Return the operand Use in the predecessor's terminator
78  /// of the successor.
79  Use &getUse() const {
80    return It.getUse();
81  }
82};
83
84typedef PredIterator<BasicBlock, Value::use_iterator> pred_iterator;
85typedef PredIterator<const BasicBlock,
86                     Value::const_use_iterator> const_pred_iterator;
87
88inline pred_iterator pred_begin(BasicBlock *BB) { return pred_iterator(BB); }
89inline const_pred_iterator pred_begin(const BasicBlock *BB) {
90  return const_pred_iterator(BB);
91}
92inline pred_iterator pred_end(BasicBlock *BB) { return pred_iterator(BB, true);}
93inline const_pred_iterator pred_end(const BasicBlock *BB) {
94  return const_pred_iterator(BB, true);
95}
96
97
98
99//===----------------------------------------------------------------------===//
100// BasicBlock succ_iterator definition
101//===----------------------------------------------------------------------===//
102
103template <class Term_, class BB_>           // Successor Iterator
104class SuccIterator : public std::iterator<std::bidirectional_iterator_tag,
105                                          BB_, ptrdiff_t, BB_*, BB_*> {
106  const Term_ Term;
107  unsigned idx;
108  typedef std::iterator<std::bidirectional_iterator_tag, BB_, ptrdiff_t, BB_*,
109                                                                    BB_*> super;
110  typedef SuccIterator<Term_, BB_> Self;
111
112  inline bool index_is_valid(int idx) {
113    return idx >= 0 && (unsigned) idx < Term->getNumSuccessors();
114  }
115
116public:
117  typedef typename super::pointer pointer;
118  typedef typename super::reference reference;
119  // TODO: This can be random access iterator, only operator[] missing.
120
121  explicit inline SuccIterator(Term_ T) : Term(T), idx(0) {// begin iterator
122  }
123  inline SuccIterator(Term_ T, bool)                       // end iterator
124    : Term(T) {
125    if (Term)
126      idx = Term->getNumSuccessors();
127    else
128      // Term == NULL happens, if a basic block is not fully constructed and
129      // consequently getTerminator() returns NULL. In this case we construct a
130      // SuccIterator which describes a basic block that has zero successors.
131      // Defining SuccIterator for incomplete and malformed CFGs is especially
132      // useful for debugging.
133      idx = 0;
134  }
135
136  inline const Self &operator=(const Self &I) {
137    assert(Term == I.Term &&"Cannot assign iterators to two different blocks!");
138    idx = I.idx;
139    return *this;
140  }
141
142  /// getSuccessorIndex - This is used to interface between code that wants to
143  /// operate on terminator instructions directly.
144  unsigned getSuccessorIndex() const { return idx; }
145
146  inline bool operator==(const Self& x) const { return idx == x.idx; }
147  inline bool operator!=(const Self& x) const { return !operator==(x); }
148
149  inline reference operator*() const { return Term->getSuccessor(idx); }
150  inline pointer operator->() const { return operator*(); }
151
152  inline Self& operator++() { ++idx; return *this; } // Preincrement
153
154  inline Self operator++(int) { // Postincrement
155    Self tmp = *this; ++*this; return tmp;
156  }
157
158  inline Self& operator--() { --idx; return *this; }  // Predecrement
159  inline Self operator--(int) { // Postdecrement
160    Self tmp = *this; --*this; return tmp;
161  }
162
163  inline bool operator<(const Self& x) const {
164    assert(Term == x.Term && "Cannot compare iterators of different blocks!");
165    return idx < x.idx;
166  }
167
168  inline bool operator<=(const Self& x) const {
169    assert(Term == x.Term && "Cannot compare iterators of different blocks!");
170    return idx <= x.idx;
171  }
172  inline bool operator>=(const Self& x) const {
173    assert(Term == x.Term && "Cannot compare iterators of different blocks!");
174    return idx >= x.idx;
175  }
176
177  inline bool operator>(const Self& x) const {
178    assert(Term == x.Term && "Cannot compare iterators of different blocks!");
179    return idx > x.idx;
180  }
181
182  inline Self& operator+=(int Right) {
183    unsigned new_idx = idx + Right;
184    assert(index_is_valid(new_idx) && "Iterator index out of bound");
185    idx = new_idx;
186    return *this;
187  }
188
189  inline Self operator+(int Right) {
190    Self tmp = *this;
191    tmp += Right;
192    return tmp;
193  }
194
195  inline Self& operator-=(int Right) {
196    return operator+=(-Right);
197  }
198
199  inline Self operator-(int Right) {
200    return operator+(-Right);
201  }
202
203  inline int operator-(const Self& x) {
204    assert(Term == x.Term && "Cannot work on iterators of different blocks!");
205    int distance = idx - x.idx;
206    return distance;
207  }
208
209  // This works for read access, however write access is difficult as changes
210  // to Term are only possible with Term->setSuccessor(idx). Pointers that can
211  // be modified are not available.
212  //
213  // inline pointer operator[](int offset) {
214  //  Self tmp = *this;
215  //  tmp += offset;
216  //  return tmp.operator*();
217  // }
218
219  /// Get the source BB of this iterator.
220  inline BB_ *getSource() {
221    assert(Term && "Source not available, if basic block was malformed");
222    return Term->getParent();
223  }
224};
225
226typedef SuccIterator<TerminatorInst*, BasicBlock> succ_iterator;
227typedef SuccIterator<const TerminatorInst*,
228                     const BasicBlock> succ_const_iterator;
229
230inline succ_iterator succ_begin(BasicBlock *BB) {
231  return succ_iterator(BB->getTerminator());
232}
233inline succ_const_iterator succ_begin(const BasicBlock *BB) {
234  return succ_const_iterator(BB->getTerminator());
235}
236inline succ_iterator succ_end(BasicBlock *BB) {
237  return succ_iterator(BB->getTerminator(), true);
238}
239inline succ_const_iterator succ_end(const BasicBlock *BB) {
240  return succ_const_iterator(BB->getTerminator(), true);
241}
242
243
244
245//===--------------------------------------------------------------------===//
246// GraphTraits specializations for basic block graphs (CFGs)
247//===--------------------------------------------------------------------===//
248
249// Provide specializations of GraphTraits to be able to treat a function as a
250// graph of basic blocks...
251
252template <> struct GraphTraits<BasicBlock*> {
253  typedef BasicBlock NodeType;
254  typedef succ_iterator ChildIteratorType;
255
256  static NodeType *getEntryNode(BasicBlock *BB) { return BB; }
257  static inline ChildIteratorType child_begin(NodeType *N) {
258    return succ_begin(N);
259  }
260  static inline ChildIteratorType child_end(NodeType *N) {
261    return succ_end(N);
262  }
263};
264
265template <> struct GraphTraits<const BasicBlock*> {
266  typedef const BasicBlock NodeType;
267  typedef succ_const_iterator ChildIteratorType;
268
269  static NodeType *getEntryNode(const BasicBlock *BB) { return BB; }
270
271  static inline ChildIteratorType child_begin(NodeType *N) {
272    return succ_begin(N);
273  }
274  static inline ChildIteratorType child_end(NodeType *N) {
275    return succ_end(N);
276  }
277};
278
279// Provide specializations of GraphTraits to be able to treat a function as a
280// graph of basic blocks... and to walk it in inverse order.  Inverse order for
281// a function is considered to be when traversing the predecessor edges of a BB
282// instead of the successor edges.
283//
284template <> struct GraphTraits<Inverse<BasicBlock*> > {
285  typedef BasicBlock NodeType;
286  typedef pred_iterator ChildIteratorType;
287  static NodeType *getEntryNode(Inverse<BasicBlock *> G) { return G.Graph; }
288  static inline ChildIteratorType child_begin(NodeType *N) {
289    return pred_begin(N);
290  }
291  static inline ChildIteratorType child_end(NodeType *N) {
292    return pred_end(N);
293  }
294};
295
296template <> struct GraphTraits<Inverse<const BasicBlock*> > {
297  typedef const BasicBlock NodeType;
298  typedef const_pred_iterator ChildIteratorType;
299  static NodeType *getEntryNode(Inverse<const BasicBlock*> G) {
300    return G.Graph;
301  }
302  static inline ChildIteratorType child_begin(NodeType *N) {
303    return pred_begin(N);
304  }
305  static inline ChildIteratorType child_end(NodeType *N) {
306    return pred_end(N);
307  }
308};
309
310
311
312//===--------------------------------------------------------------------===//
313// GraphTraits specializations for function basic block graphs (CFGs)
314//===--------------------------------------------------------------------===//
315
316// Provide specializations of GraphTraits to be able to treat a function as a
317// graph of basic blocks... these are the same as the basic block iterators,
318// except that the root node is implicitly the first node of the function.
319//
320template <> struct GraphTraits<Function*> : public GraphTraits<BasicBlock*> {
321  static NodeType *getEntryNode(Function *F) { return &F->getEntryBlock(); }
322
323  // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
324  typedef Function::iterator nodes_iterator;
325  static nodes_iterator nodes_begin(Function *F) { return F->begin(); }
326  static nodes_iterator nodes_end  (Function *F) { return F->end(); }
327  static unsigned       size       (Function *F) { return F->size(); }
328};
329template <> struct GraphTraits<const Function*> :
330  public GraphTraits<const BasicBlock*> {
331  static NodeType *getEntryNode(const Function *F) {return &F->getEntryBlock();}
332
333  // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
334  typedef Function::const_iterator nodes_iterator;
335  static nodes_iterator nodes_begin(const Function *F) { return F->begin(); }
336  static nodes_iterator nodes_end  (const Function *F) { return F->end(); }
337  static unsigned       size       (const Function *F) { return F->size(); }
338};
339
340
341// Provide specializations of GraphTraits to be able to treat a function as a
342// graph of basic blocks... and to walk it in inverse order.  Inverse order for
343// a function is considered to be when traversing the predecessor edges of a BB
344// instead of the successor edges.
345//
346template <> struct GraphTraits<Inverse<Function*> > :
347  public GraphTraits<Inverse<BasicBlock*> > {
348  static NodeType *getEntryNode(Inverse<Function*> G) {
349    return &G.Graph->getEntryBlock();
350  }
351};
352template <> struct GraphTraits<Inverse<const Function*> > :
353  public GraphTraits<Inverse<const BasicBlock*> > {
354  static NodeType *getEntryNode(Inverse<const Function *> G) {
355    return &G.Graph->getEntryBlock();
356  }
357};
358
359} // End llvm namespace
360
361#endif
362