]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Support/GenericDomTree.h
Merge llvm trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / Support / GenericDomTree.h
1 //===- GenericDomTree.h - Generic dominator trees for 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 /// \file
10 ///
11 /// This file defines a set of templates that efficiently compute a dominator
12 /// tree over a generic graph. This is used typically in LLVM for fast
13 /// dominance queries on the CFG, but is fully generic w.r.t. the underlying
14 /// graph types.
15 ///
16 /// Unlike ADT/* graph algorithms, generic dominator tree has more requirements
17 /// on the graph's NodeRef. The NodeRef should be a pointer and, depending on
18 /// the implementation, e.g. NodeRef->getParent() return the parent node.
19 ///
20 /// FIXME: Maybe GenericDomTree needs a TreeTraits, instead of GraphTraits.
21 ///
22 //===----------------------------------------------------------------------===//
23
24 #ifndef LLVM_SUPPORT_GENERICDOMTREE_H
25 #define LLVM_SUPPORT_GENERICDOMTREE_H
26
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/GraphTraits.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34 #include <cassert>
35 #include <cstddef>
36 #include <iterator>
37 #include <memory>
38 #include <type_traits>
39 #include <utility>
40 #include <vector>
41
42 namespace llvm {
43
44 template <class NodeT> class DominatorTreeBase;
45
46 namespace detail {
47
48 template <typename GT> struct DominatorTreeBaseTraits {
49   static_assert(std::is_pointer<typename GT::NodeRef>::value,
50                 "Currently NodeRef must be a pointer type.");
51   using type = DominatorTreeBase<
52       typename std::remove_pointer<typename GT::NodeRef>::type>;
53 };
54
55 } // end namespace detail
56
57 template <typename GT>
58 using DominatorTreeBaseByGraphTraits =
59     typename detail::DominatorTreeBaseTraits<GT>::type;
60
61 /// \brief Base class that other, more interesting dominator analyses
62 /// inherit from.
63 template <class NodeT> class DominatorBase {
64 protected:
65   std::vector<NodeT *> Roots;
66   bool IsPostDominators;
67
68   explicit DominatorBase(bool isPostDom)
69       : Roots(), IsPostDominators(isPostDom) {}
70
71   DominatorBase(DominatorBase &&Arg)
72       : Roots(std::move(Arg.Roots)),
73         IsPostDominators(std::move(Arg.IsPostDominators)) {
74     Arg.Roots.clear();
75   }
76
77   DominatorBase &operator=(DominatorBase &&RHS) {
78     Roots = std::move(RHS.Roots);
79     IsPostDominators = std::move(RHS.IsPostDominators);
80     RHS.Roots.clear();
81     return *this;
82   }
83
84 public:
85   /// getRoots - Return the root blocks of the current CFG.  This may include
86   /// multiple blocks if we are computing post dominators.  For forward
87   /// dominators, this will always be a single block (the entry node).
88   ///
89   const std::vector<NodeT *> &getRoots() const { return Roots; }
90
91   /// isPostDominator - Returns true if analysis based of postdoms
92   ///
93   bool isPostDominator() const { return IsPostDominators; }
94 };
95
96 /// \brief Base class for the actual dominator tree node.
97 template <class NodeT> class DomTreeNodeBase {
98   friend struct PostDominatorTree;
99   template <class N> friend class DominatorTreeBase;
100
101   NodeT *TheBB;
102   DomTreeNodeBase<NodeT> *IDom;
103   std::vector<DomTreeNodeBase<NodeT> *> Children;
104   mutable int DFSNumIn = -1;
105   mutable int DFSNumOut = -1;
106
107 public:
108   DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
109       : TheBB(BB), IDom(iDom) {}
110
111   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
112   typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
113       const_iterator;
114
115   iterator begin() { return Children.begin(); }
116   iterator end() { return Children.end(); }
117   const_iterator begin() const { return Children.begin(); }
118   const_iterator end() const { return Children.end(); }
119
120   NodeT *getBlock() const { return TheBB; }
121   DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
122
123   const std::vector<DomTreeNodeBase<NodeT> *> &getChildren() const {
124     return Children;
125   }
126
127   std::unique_ptr<DomTreeNodeBase<NodeT>>
128   addChild(std::unique_ptr<DomTreeNodeBase<NodeT>> C) {
129     Children.push_back(C.get());
130     return C;
131   }
132
133   size_t getNumChildren() const { return Children.size(); }
134
135   void clearAllChildren() { Children.clear(); }
136
137   bool compare(const DomTreeNodeBase<NodeT> *Other) const {
138     if (getNumChildren() != Other->getNumChildren())
139       return true;
140
141     SmallPtrSet<const NodeT *, 4> OtherChildren;
142     for (const DomTreeNodeBase *I : *Other) {
143       const NodeT *Nd = I->getBlock();
144       OtherChildren.insert(Nd);
145     }
146
147     for (const DomTreeNodeBase *I : *this) {
148       const NodeT *N = I->getBlock();
149       if (OtherChildren.count(N) == 0)
150         return true;
151     }
152     return false;
153   }
154
155   void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
156     assert(IDom && "No immediate dominator?");
157     if (IDom != NewIDom) {
158       typename std::vector<DomTreeNodeBase<NodeT> *>::iterator I =
159           find(IDom->Children, this);
160       assert(I != IDom->Children.end() &&
161              "Not in immediate dominator children set!");
162       // I am no longer your child...
163       IDom->Children.erase(I);
164
165       // Switch to new dominator
166       IDom = NewIDom;
167       IDom->Children.push_back(this);
168     }
169   }
170
171   /// getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes
172   /// in the dominator tree. They are only guaranteed valid if
173   /// updateDFSNumbers() has been called.
174   unsigned getDFSNumIn() const { return DFSNumIn; }
175   unsigned getDFSNumOut() const { return DFSNumOut; }
176
177 private:
178   // Return true if this node is dominated by other. Use this only if DFS info
179   // is valid.
180   bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
181     return this->DFSNumIn >= other->DFSNumIn &&
182            this->DFSNumOut <= other->DFSNumOut;
183   }
184 };
185
186 template <class NodeT>
187 raw_ostream &operator<<(raw_ostream &o, const DomTreeNodeBase<NodeT> *Node) {
188   if (Node->getBlock())
189     Node->getBlock()->printAsOperand(o, false);
190   else
191     o << " <<exit node>>";
192
193   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
194
195   return o << "\n";
196 }
197
198 template <class NodeT>
199 void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
200                   unsigned Lev) {
201   o.indent(2 * Lev) << "[" << Lev << "] " << N;
202   for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
203                                                        E = N->end();
204        I != E; ++I)
205     PrintDomTree<NodeT>(*I, o, Lev + 1);
206 }
207
208 // The calculate routine is provided in a separate header but referenced here.
209 template <class FuncT, class N>
210 void Calculate(DominatorTreeBaseByGraphTraits<GraphTraits<N>> &DT, FuncT &F);
211
212 /// \brief Core dominator tree base class.
213 ///
214 /// This class is a generic template over graph nodes. It is instantiated for
215 /// various graphs in the LLVM IR or in the code generator.
216 template <class NodeT> class DominatorTreeBase : public DominatorBase<NodeT> {
217   bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
218                                const DomTreeNodeBase<NodeT> *B) const {
219     assert(A != B);
220     assert(isReachableFromEntry(B));
221     assert(isReachableFromEntry(A));
222
223     const DomTreeNodeBase<NodeT> *IDom;
224     while ((IDom = B->getIDom()) != nullptr && IDom != A && IDom != B)
225       B = IDom; // Walk up the tree
226     return IDom != nullptr;
227   }
228
229   /// \brief Wipe this tree's state without releasing any resources.
230   ///
231   /// This is essentially a post-move helper only. It leaves the object in an
232   /// assignable and destroyable state, but otherwise invalid.
233   void wipe() {
234     DomTreeNodes.clear();
235     IDoms.clear();
236     Vertex.clear();
237     Info.clear();
238     RootNode = nullptr;
239   }
240
241 protected:
242   typedef DenseMap<NodeT *, std::unique_ptr<DomTreeNodeBase<NodeT>>>
243       DomTreeNodeMapType;
244   DomTreeNodeMapType DomTreeNodes;
245   DomTreeNodeBase<NodeT> *RootNode;
246
247   mutable bool DFSInfoValid = false;
248   mutable unsigned int SlowQueries = 0;
249   // Information record used during immediate dominators computation.
250   struct InfoRec {
251     unsigned DFSNum = 0;
252     unsigned Parent = 0;
253     unsigned Semi = 0;
254     NodeT *Label = nullptr;
255
256     InfoRec() = default;
257   };
258
259   DenseMap<NodeT *, NodeT *> IDoms;
260
261   // Vertex - Map the DFS number to the NodeT*
262   std::vector<NodeT *> Vertex;
263
264   // Info - Collection of information used during the computation of idoms.
265   DenseMap<NodeT *, InfoRec> Info;
266
267   void reset() {
268     DomTreeNodes.clear();
269     IDoms.clear();
270     this->Roots.clear();
271     Vertex.clear();
272     RootNode = nullptr;
273     DFSInfoValid = false;
274     SlowQueries = 0;
275   }
276
277   // NewBB is split and now it has one successor. Update dominator tree to
278   // reflect this change.
279   template <class N, class GraphT>
280   void Split(DominatorTreeBaseByGraphTraits<GraphT> &DT,
281              typename GraphT::NodeRef NewBB) {
282     assert(std::distance(GraphT::child_begin(NewBB),
283                          GraphT::child_end(NewBB)) == 1 &&
284            "NewBB should have a single successor!");
285     typename GraphT::NodeRef NewBBSucc = *GraphT::child_begin(NewBB);
286
287     std::vector<typename GraphT::NodeRef> PredBlocks;
288     typedef GraphTraits<Inverse<N>> InvTraits;
289     for (typename InvTraits::ChildIteratorType
290              PI = InvTraits::child_begin(NewBB),
291              PE = InvTraits::child_end(NewBB);
292          PI != PE; ++PI)
293       PredBlocks.push_back(*PI);
294
295     assert(!PredBlocks.empty() && "No predblocks?");
296
297     bool NewBBDominatesNewBBSucc = true;
298     for (typename InvTraits::ChildIteratorType
299              PI = InvTraits::child_begin(NewBBSucc),
300              E = InvTraits::child_end(NewBBSucc);
301          PI != E; ++PI) {
302       typename InvTraits::NodeRef ND = *PI;
303       if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
304           DT.isReachableFromEntry(ND)) {
305         NewBBDominatesNewBBSucc = false;
306         break;
307       }
308     }
309
310     // Find NewBB's immediate dominator and create new dominator tree node for
311     // NewBB.
312     NodeT *NewBBIDom = nullptr;
313     unsigned i = 0;
314     for (i = 0; i < PredBlocks.size(); ++i)
315       if (DT.isReachableFromEntry(PredBlocks[i])) {
316         NewBBIDom = PredBlocks[i];
317         break;
318       }
319
320     // It's possible that none of the predecessors of NewBB are reachable;
321     // in that case, NewBB itself is unreachable, so nothing needs to be
322     // changed.
323     if (!NewBBIDom)
324       return;
325
326     for (i = i + 1; i < PredBlocks.size(); ++i) {
327       if (DT.isReachableFromEntry(PredBlocks[i]))
328         NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
329     }
330
331     // Create the new dominator tree node... and set the idom of NewBB.
332     DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
333
334     // If NewBB strictly dominates other blocks, then it is now the immediate
335     // dominator of NewBBSucc.  Update the dominator tree as appropriate.
336     if (NewBBDominatesNewBBSucc) {
337       DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
338       DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
339     }
340   }
341
342 public:
343   explicit DominatorTreeBase(bool isPostDom)
344       : DominatorBase<NodeT>(isPostDom) {}
345
346   DominatorTreeBase(DominatorTreeBase &&Arg)
347       : DominatorBase<NodeT>(
348             std::move(static_cast<DominatorBase<NodeT> &>(Arg))),
349         DomTreeNodes(std::move(Arg.DomTreeNodes)),
350         RootNode(std::move(Arg.RootNode)),
351         DFSInfoValid(std::move(Arg.DFSInfoValid)),
352         SlowQueries(std::move(Arg.SlowQueries)), IDoms(std::move(Arg.IDoms)),
353         Vertex(std::move(Arg.Vertex)), Info(std::move(Arg.Info)) {
354     Arg.wipe();
355   }
356
357   DominatorTreeBase &operator=(DominatorTreeBase &&RHS) {
358     DominatorBase<NodeT>::operator=(
359         std::move(static_cast<DominatorBase<NodeT> &>(RHS)));
360     DomTreeNodes = std::move(RHS.DomTreeNodes);
361     RootNode = std::move(RHS.RootNode);
362     DFSInfoValid = std::move(RHS.DFSInfoValid);
363     SlowQueries = std::move(RHS.SlowQueries);
364     IDoms = std::move(RHS.IDoms);
365     Vertex = std::move(RHS.Vertex);
366     Info = std::move(RHS.Info);
367     RHS.wipe();
368     return *this;
369   }
370
371   DominatorTreeBase(const DominatorTreeBase &) = delete;
372   DominatorTreeBase &operator=(const DominatorTreeBase &) = delete;
373
374   /// compare - Return false if the other dominator tree base matches this
375   /// dominator tree base. Otherwise return true.
376   bool compare(const DominatorTreeBase &Other) const {
377
378     const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
379     if (DomTreeNodes.size() != OtherDomTreeNodes.size())
380       return true;
381
382     for (const auto &DomTreeNode : this->DomTreeNodes) {
383       NodeT *BB = DomTreeNode.first;
384       typename DomTreeNodeMapType::const_iterator OI =
385           OtherDomTreeNodes.find(BB);
386       if (OI == OtherDomTreeNodes.end())
387         return true;
388
389       DomTreeNodeBase<NodeT> &MyNd = *DomTreeNode.second;
390       DomTreeNodeBase<NodeT> &OtherNd = *OI->second;
391
392       if (MyNd.compare(&OtherNd))
393         return true;
394     }
395
396     return false;
397   }
398
399   void releaseMemory() { reset(); }
400
401   /// getNode - return the (Post)DominatorTree node for the specified basic
402   /// block.  This is the same as using operator[] on this class.  The result
403   /// may (but is not required to) be null for a forward (backwards)
404   /// statically unreachable block.
405   DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
406     auto I = DomTreeNodes.find(BB);
407     if (I != DomTreeNodes.end())
408       return I->second.get();
409     return nullptr;
410   }
411
412   /// See getNode.
413   DomTreeNodeBase<NodeT> *operator[](NodeT *BB) const { return getNode(BB); }
414
415   /// getRootNode - This returns the entry node for the CFG of the function.  If
416   /// this tree represents the post-dominance relations for a function, however,
417   /// this root may be a node with the block == NULL.  This is the case when
418   /// there are multiple exit nodes from a particular function.  Consumers of
419   /// post-dominance information must be capable of dealing with this
420   /// possibility.
421   ///
422   DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
423   const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
424
425   /// Get all nodes dominated by R, including R itself.
426   void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
427     Result.clear();
428     const DomTreeNodeBase<NodeT> *RN = getNode(R);
429     if (!RN)
430       return; // If R is unreachable, it will not be present in the DOM tree.
431     SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL;
432     WL.push_back(RN);
433
434     while (!WL.empty()) {
435       const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
436       Result.push_back(N->getBlock());
437       WL.append(N->begin(), N->end());
438     }
439   }
440
441   /// properlyDominates - Returns true iff A dominates B and A != B.
442   /// Note that this is not a constant time operation!
443   ///
444   bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
445                          const DomTreeNodeBase<NodeT> *B) const {
446     if (!A || !B)
447       return false;
448     if (A == B)
449       return false;
450     return dominates(A, B);
451   }
452
453   bool properlyDominates(const NodeT *A, const NodeT *B) const;
454
455   /// isReachableFromEntry - Return true if A is dominated by the entry
456   /// block of the function containing it.
457   bool isReachableFromEntry(const NodeT *A) const {
458     assert(!this->isPostDominator() &&
459            "This is not implemented for post dominators");
460     return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
461   }
462
463   bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const { return A; }
464
465   /// dominates - Returns true iff A dominates B.  Note that this is not a
466   /// constant time operation!
467   ///
468   bool dominates(const DomTreeNodeBase<NodeT> *A,
469                  const DomTreeNodeBase<NodeT> *B) const {
470     // A node trivially dominates itself.
471     if (B == A)
472       return true;
473
474     // An unreachable node is dominated by anything.
475     if (!isReachableFromEntry(B))
476       return true;
477
478     // And dominates nothing.
479     if (!isReachableFromEntry(A))
480       return false;
481
482     // Compare the result of the tree walk and the dfs numbers, if expensive
483     // checks are enabled.
484 #ifdef EXPENSIVE_CHECKS
485     assert((!DFSInfoValid ||
486             (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
487            "Tree walk disagrees with dfs numbers!");
488 #endif
489
490     if (DFSInfoValid)
491       return B->DominatedBy(A);
492
493     // If we end up with too many slow queries, just update the
494     // DFS numbers on the theory that we are going to keep querying.
495     SlowQueries++;
496     if (SlowQueries > 32) {
497       updateDFSNumbers();
498       return B->DominatedBy(A);
499     }
500
501     return dominatedBySlowTreeWalk(A, B);
502   }
503
504   bool dominates(const NodeT *A, const NodeT *B) const;
505
506   NodeT *getRoot() const {
507     assert(this->Roots.size() == 1 && "Should always have entry node!");
508     return this->Roots[0];
509   }
510
511   /// findNearestCommonDominator - Find nearest common dominator basic block
512   /// for basic block A and B. If there is no such block then return NULL.
513   NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
514     assert(A->getParent() == B->getParent() &&
515            "Two blocks are not in same function");
516
517     // If either A or B is a entry block then it is nearest common dominator
518     // (for forward-dominators).
519     if (!this->isPostDominator()) {
520       NodeT &Entry = A->getParent()->front();
521       if (A == &Entry || B == &Entry)
522         return &Entry;
523     }
524
525     // If B dominates A then B is nearest common dominator.
526     if (dominates(B, A))
527       return B;
528
529     // If A dominates B then A is nearest common dominator.
530     if (dominates(A, B))
531       return A;
532
533     DomTreeNodeBase<NodeT> *NodeA = getNode(A);
534     DomTreeNodeBase<NodeT> *NodeB = getNode(B);
535
536     // If we have DFS info, then we can avoid all allocations by just querying
537     // it from each IDom. Note that because we call 'dominates' twice above, we
538     // expect to call through this code at most 16 times in a row without
539     // building valid DFS information. This is important as below is a *very*
540     // slow tree walk.
541     if (DFSInfoValid) {
542       DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
543       while (IDomA) {
544         if (NodeB->DominatedBy(IDomA))
545           return IDomA->getBlock();
546         IDomA = IDomA->getIDom();
547       }
548       return nullptr;
549     }
550
551     // Collect NodeA dominators set.
552     SmallPtrSet<DomTreeNodeBase<NodeT> *, 16> NodeADoms;
553     NodeADoms.insert(NodeA);
554     DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
555     while (IDomA) {
556       NodeADoms.insert(IDomA);
557       IDomA = IDomA->getIDom();
558     }
559
560     // Walk NodeB immediate dominators chain and find common dominator node.
561     DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
562     while (IDomB) {
563       if (NodeADoms.count(IDomB) != 0)
564         return IDomB->getBlock();
565
566       IDomB = IDomB->getIDom();
567     }
568
569     return nullptr;
570   }
571
572   const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
573     // Cast away the const qualifiers here. This is ok since
574     // const is re-introduced on the return type.
575     return findNearestCommonDominator(const_cast<NodeT *>(A),
576                                       const_cast<NodeT *>(B));
577   }
578
579   //===--------------------------------------------------------------------===//
580   // API to update (Post)DominatorTree information based on modifications to
581   // the CFG...
582
583   /// Add a new node to the dominator tree information.
584   ///
585   /// This creates a new node as a child of DomBB dominator node, linking it
586   /// into the children list of the immediate dominator.
587   ///
588   /// \param BB New node in CFG.
589   /// \param DomBB CFG node that is dominator for BB.
590   /// \returns New dominator tree node that represents new CFG node.
591   ///
592   DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
593     assert(getNode(BB) == nullptr && "Block already in dominator tree!");
594     DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
595     assert(IDomNode && "Not immediate dominator specified for block!");
596     DFSInfoValid = false;
597     return (DomTreeNodes[BB] = IDomNode->addChild(
598                 llvm::make_unique<DomTreeNodeBase<NodeT>>(BB, IDomNode))).get();
599   }
600
601   /// Add a new node to the forward dominator tree and make it a new root.
602   ///
603   /// \param BB New node in CFG.
604   /// \returns New dominator tree node that represents new CFG node.
605   ///
606   DomTreeNodeBase<NodeT> *setNewRoot(NodeT *BB) {
607     assert(getNode(BB) == nullptr && "Block already in dominator tree!");
608     assert(!this->isPostDominator() &&
609            "Cannot change root of post-dominator tree");
610     DFSInfoValid = false;
611     auto &Roots = DominatorBase<NodeT>::Roots;
612     DomTreeNodeBase<NodeT> *NewNode = (DomTreeNodes[BB] =
613       llvm::make_unique<DomTreeNodeBase<NodeT>>(BB, nullptr)).get();
614     if (Roots.empty()) {
615       addRoot(BB);
616     } else {
617       assert(Roots.size() == 1);
618       NodeT *OldRoot = Roots.front();
619       DomTreeNodes[OldRoot] =
620         NewNode->addChild(std::move(DomTreeNodes[OldRoot]));
621       Roots[0] = BB;
622     }
623     return RootNode = NewNode;
624   }
625
626   /// changeImmediateDominator - This method is used to update the dominator
627   /// tree information when a node's immediate dominator changes.
628   ///
629   void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
630                                 DomTreeNodeBase<NodeT> *NewIDom) {
631     assert(N && NewIDom && "Cannot change null node pointers!");
632     DFSInfoValid = false;
633     N->setIDom(NewIDom);
634   }
635
636   void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
637     changeImmediateDominator(getNode(BB), getNode(NewBB));
638   }
639
640   /// eraseNode - Removes a node from the dominator tree. Block must not
641   /// dominate any other blocks. Removes node from its immediate dominator's
642   /// children list. Deletes dominator node associated with basic block BB.
643   void eraseNode(NodeT *BB) {
644     DomTreeNodeBase<NodeT> *Node = getNode(BB);
645     assert(Node && "Removing node that isn't in dominator tree.");
646     assert(Node->getChildren().empty() && "Node is not a leaf node.");
647
648     // Remove node from immediate dominator's children list.
649     DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
650     if (IDom) {
651       typename std::vector<DomTreeNodeBase<NodeT> *>::iterator I =
652           find(IDom->Children, Node);
653       assert(I != IDom->Children.end() &&
654              "Not in immediate dominator children set!");
655       // I am no longer your child...
656       IDom->Children.erase(I);
657     }
658
659     DomTreeNodes.erase(BB);
660   }
661
662   /// splitBlock - BB is split and now it has one successor. Update dominator
663   /// tree to reflect this change.
664   void splitBlock(NodeT *NewBB) {
665     if (this->IsPostDominators)
666       this->Split<Inverse<NodeT *>, GraphTraits<Inverse<NodeT *>>>(*this,
667                                                                    NewBB);
668     else
669       this->Split<NodeT *, GraphTraits<NodeT *>>(*this, NewBB);
670   }
671
672   /// print - Convert to human readable form
673   ///
674   void print(raw_ostream &o) const {
675     o << "=============================--------------------------------\n";
676     if (this->isPostDominator())
677       o << "Inorder PostDominator Tree: ";
678     else
679       o << "Inorder Dominator Tree: ";
680     if (!this->DFSInfoValid)
681       o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
682     o << "\n";
683
684     // The postdom tree can have a null root if there are no returns.
685     if (getRootNode())
686       PrintDomTree<NodeT>(getRootNode(), o, 1);
687   }
688
689 protected:
690   template <class GraphT>
691   friend typename GraphT::NodeRef
692   Eval(DominatorTreeBaseByGraphTraits<GraphT> &DT, typename GraphT::NodeRef V,
693        unsigned LastLinked);
694
695   template <class GraphT>
696   friend unsigned ReverseDFSPass(DominatorTreeBaseByGraphTraits<GraphT> &DT,
697                                  typename GraphT::NodeRef V, unsigned N);
698
699   template <class GraphT>
700   friend unsigned DFSPass(DominatorTreeBaseByGraphTraits<GraphT> &DT,
701                           typename GraphT::NodeRef V, unsigned N);
702
703   template <class FuncT, class N>
704   friend void Calculate(DominatorTreeBaseByGraphTraits<GraphTraits<N>> &DT,
705                         FuncT &F);
706
707   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
708     if (DomTreeNodeBase<NodeT> *Node = getNode(BB))
709       return Node;
710
711     // Haven't calculated this node yet?  Get or calculate the node for the
712     // immediate dominator.
713     NodeT *IDom = getIDom(BB);
714
715     assert(IDom || this->DomTreeNodes[nullptr]);
716     DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
717
718     // Add a new tree node for this NodeT, and link it as a child of
719     // IDomNode
720     return (this->DomTreeNodes[BB] = IDomNode->addChild(
721                 llvm::make_unique<DomTreeNodeBase<NodeT>>(BB, IDomNode))).get();
722   }
723
724   NodeT *getIDom(NodeT *BB) const { return IDoms.lookup(BB); }
725
726   void addRoot(NodeT *BB) { this->Roots.push_back(BB); }
727
728 public:
729   /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
730   /// dominator tree in dfs order.
731   void updateDFSNumbers() const {
732     if (DFSInfoValid) {
733       SlowQueries = 0;
734       return;
735     }
736
737     unsigned DFSNum = 0;
738
739     SmallVector<std::pair<const DomTreeNodeBase<NodeT> *,
740                           typename DomTreeNodeBase<NodeT>::const_iterator>,
741                 32> WorkStack;
742
743     const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
744
745     if (!ThisRoot)
746       return;
747
748     // Even in the case of multiple exits that form the post dominator root
749     // nodes, do not iterate over all exits, but start from the virtual root
750     // node. Otherwise bbs, that are not post dominated by any exit but by the
751     // virtual root node, will never be assigned a DFS number.
752     WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
753     ThisRoot->DFSNumIn = DFSNum++;
754
755     while (!WorkStack.empty()) {
756       const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
757       typename DomTreeNodeBase<NodeT>::const_iterator ChildIt =
758           WorkStack.back().second;
759
760       // If we visited all of the children of this node, "recurse" back up the
761       // stack setting the DFOutNum.
762       if (ChildIt == Node->end()) {
763         Node->DFSNumOut = DFSNum++;
764         WorkStack.pop_back();
765       } else {
766         // Otherwise, recursively visit this child.
767         const DomTreeNodeBase<NodeT> *Child = *ChildIt;
768         ++WorkStack.back().second;
769
770         WorkStack.push_back(std::make_pair(Child, Child->begin()));
771         Child->DFSNumIn = DFSNum++;
772       }
773     }
774
775     SlowQueries = 0;
776     DFSInfoValid = true;
777   }
778
779   /// recalculate - compute a dominator tree for the given function
780   template <class FT> void recalculate(FT &F) {
781     typedef GraphTraits<FT *> TraitsTy;
782     reset();
783     this->Vertex.push_back(nullptr);
784
785     if (!this->IsPostDominators) {
786       // Initialize root
787       NodeT *entry = TraitsTy::getEntryNode(&F);
788       addRoot(entry);
789
790       Calculate<FT, NodeT *>(*this, F);
791     } else {
792       // Initialize the roots list
793       for (auto *Node : nodes(&F))
794         if (TraitsTy::child_begin(Node) == TraitsTy::child_end(Node))
795           addRoot(Node);
796
797       Calculate<FT, Inverse<NodeT *>>(*this, F);
798     }
799   }
800 };
801
802 // These two functions are declared out of line as a workaround for building
803 // with old (< r147295) versions of clang because of pr11642.
804 template <class NodeT>
805 bool DominatorTreeBase<NodeT>::dominates(const NodeT *A, const NodeT *B) const {
806   if (A == B)
807     return true;
808
809   // Cast away the const qualifiers here. This is ok since
810   // this function doesn't actually return the values returned
811   // from getNode.
812   return dominates(getNode(const_cast<NodeT *>(A)),
813                    getNode(const_cast<NodeT *>(B)));
814 }
815 template <class NodeT>
816 bool DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A,
817                                                  const NodeT *B) const {
818   if (A == B)
819     return false;
820
821   // Cast away the const qualifiers here. This is ok since
822   // this function doesn't actually return the values returned
823   // from getNode.
824   return dominates(getNode(const_cast<NodeT *>(A)),
825                    getNode(const_cast<NodeT *>(B)));
826 }
827
828 } // end namespace llvm
829
830 #endif // LLVM_SUPPORT_GENERICDOMTREE_H