LLVM 22.0.0git
CFGDiff.h
Go to the documentation of this file.
1//===- CFGDiff.h - Define a CFG snapshot. -----------------------*- C++ -*-===//
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// This file defines specializations of GraphTraits that allows generic
10// algorithms to see a different snapshot of a CFG.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_CFGDIFF_H
15#define LLVM_SUPPORT_CFGDIFF_H
16
18#include "llvm/ADT/iterator.h"
22#include <cassert>
23#include <cstddef>
24
25// Two booleans are used to define orders in graphs:
26// InverseGraph defines when we need to reverse the whole graph and is as such
27// also equivalent to applying updates in reverse.
28// InverseEdge defines whether we want to change the edges direction. E.g., for
29// a non-inversed graph, the children are naturally the successors when
30// InverseEdge is false and the predecessors when InverseEdge is true.
31
32namespace llvm {
33
34namespace detail {
35template <typename Range>
36auto reverse_if_helper(Range &&R, std::bool_constant<false>) {
37 return std::forward<Range>(R);
38}
39
40template <typename Range>
41auto reverse_if_helper(Range &&R, std::bool_constant<true>) {
42 return llvm::reverse(std::forward<Range>(R));
43}
44
45template <bool B, typename Range> auto reverse_if(Range &&R) {
46 return reverse_if_helper(std::forward<Range>(R), std::bool_constant<B>{});
47}
48} // namespace detail
49
50// GraphDiff defines a CFG snapshot: given a set of Update<NodePtr>, provides
51// a getChildren method to get a Node's children based on the additional updates
52// in the snapshot. The current diff treats the CFG as a graph rather than a
53// multigraph. Added edges are pruned to be unique, and deleted edges will
54// remove all existing edges between two blocks.
55template <typename NodePtr, bool InverseGraph = false> class GraphDiff {
56 struct DeletesInserts {
58 };
59 using UpdateMapType = SmallDenseMap<NodePtr, DeletesInserts>;
60 UpdateMapType Succ;
61 UpdateMapType Pred;
62
63 // By default, it is assumed that, given a CFG and a set of updates, we wish
64 // to apply these updates as given. If UpdatedAreReverseApplied is set, the
65 // updates will be applied in reverse: deleted edges are considered re-added
66 // and inserted edges are considered deleted when returning children.
67 bool UpdatedAreReverseApplied;
68
69 // Keep the list of legalized updates for a deterministic order of updates
70 // when using a GraphDiff for incremental updates in the DominatorTree.
71 // The list is kept in reverse to allow popping from end.
72 SmallVector<cfg::Update<NodePtr>, 4> LegalizedUpdates;
73
74 void printMap(raw_ostream &OS, const UpdateMapType &M) const {
75 StringRef DIText[2] = {"Delete", "Insert"};
76 for (auto Pair : M) {
77 for (unsigned IsInsert = 0; IsInsert <= 1; ++IsInsert) {
78 OS << DIText[IsInsert] << " edges: \n";
79 for (auto Child : Pair.second.DI[IsInsert]) {
80 OS << "(";
81 Pair.first->printAsOperand(OS, false);
82 OS << ", ";
83 Child->printAsOperand(OS, false);
84 OS << ") ";
85 }
86 }
87 }
88 OS << "\n";
89 }
90
91public:
92 GraphDiff() : UpdatedAreReverseApplied(false) {}
94 bool ReverseApplyUpdates = false) {
95 cfg::LegalizeUpdates<NodePtr>(Updates, LegalizedUpdates, InverseGraph);
96 for (auto U : LegalizedUpdates) {
97 unsigned IsInsert =
98 (U.getKind() == cfg::UpdateKind::Insert) == !ReverseApplyUpdates;
99 Succ[U.getFrom()].DI[IsInsert].push_back(U.getTo());
100 Pred[U.getTo()].DI[IsInsert].push_back(U.getFrom());
101 }
102 UpdatedAreReverseApplied = ReverseApplyUpdates;
103 }
104
105 auto getLegalizedUpdates() const {
106 return make_range(LegalizedUpdates.begin(), LegalizedUpdates.end());
107 }
108
109 unsigned getNumLegalizedUpdates() const { return LegalizedUpdates.size(); }
110
112 assert(!LegalizedUpdates.empty() && "No updates to apply!");
113 auto U = LegalizedUpdates.pop_back_val();
114 unsigned IsInsert =
115 (U.getKind() == cfg::UpdateKind::Insert) == !UpdatedAreReverseApplied;
116 auto &SuccDIList = Succ[U.getFrom()];
117 auto &SuccList = SuccDIList.DI[IsInsert];
118 assert(SuccList.back() == U.getTo());
119 SuccList.pop_back();
120 if (SuccList.empty() && SuccDIList.DI[!IsInsert].empty())
121 Succ.erase(U.getFrom());
122
123 auto &PredDIList = Pred[U.getTo()];
124 auto &PredList = PredDIList.DI[IsInsert];
125 assert(PredList.back() == U.getFrom());
126 PredList.pop_back();
127 if (PredList.empty() && PredDIList.DI[!IsInsert].empty())
128 Pred.erase(U.getTo());
129 return U;
130 }
131
133 template <bool InverseEdge> VectRet getChildren(NodePtr N) const {
134 using DirectedNodeT =
135 std::conditional_t<InverseEdge, Inverse<NodePtr>, NodePtr>;
136 auto R = children<DirectedNodeT>(N);
138
139 // Remove nullptr children for clang.
140 llvm::erase(Res, nullptr);
141
142 auto &Children = (InverseEdge != InverseGraph) ? Pred : Succ;
143 auto It = Children.find(N);
144 if (It == Children.end())
145 return Res;
146
147 // Remove children present in the CFG but not in the snapshot.
148 for (auto *Child : It->second.DI[0])
149 llvm::erase(Res, Child);
150
151 // Add children present in the snapshot for not in the real CFG.
152 auto &AddedChildren = It->second.DI[1];
153 llvm::append_range(Res, AddedChildren);
154
155 return Res;
156 }
157
158 void print(raw_ostream &OS) const {
159 OS << "===== GraphDiff: CFG edge changes to create a CFG snapshot. \n"
160 "===== (Note: notion of children/inverse_children depends on "
161 "the direction of edges and the graph.)\n";
162 OS << "Children to delete/insert:\n\t";
163 printMap(OS, Succ);
164 OS << "Inverse_children to delete/insert:\n\t";
165 printMap(OS, Pred);
166 OS << "\n";
167 }
168
169#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
170 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
171#endif
172};
173} // end namespace llvm
174
175#endif // LLVM_SUPPORT_CFGDIFF_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:638
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
auto getLegalizedUpdates() const
Definition CFGDiff.h:105
SmallVector< MachineBasicBlock *, 8 > VectRet
Definition CFGDiff.h:132
void print(raw_ostream &OS) const
Definition CFGDiff.h:158
LLVM_DUMP_METHOD void dump() const
Definition CFGDiff.h:170
VectRet getChildren(NodePtr N) const
Definition CFGDiff.h:133
GraphDiff(ArrayRef< cfg::Update< NodePtr > > Updates, bool ReverseApplyUpdates=false)
Definition CFGDiff.h:93
cfg::Update< NodePtr > popUpdateForIncrementalUpdates()
Definition CFGDiff.h:111
unsigned getNumLegalizedUpdates() const
Definition CFGDiff.h:109
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
void LegalizeUpdates(ArrayRef< Update< NodePtr > > AllUpdates, SmallVectorImpl< Update< NodePtr > > &Result, bool InverseGraph, bool ReverseResultOrder=false)
Definition CFGUpdate.h:63
A self-contained host- and target-independent arbitrary-precision floating-point software implementat...
Definition ADL.h:123
auto reverse_if(Range &&R)
Definition CFGDiff.h:45
auto reverse_if_helper(Range &&R, std::bool_constant< false >)
Definition CFGDiff.h:36
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2136
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2128
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
#define N