xref: /llvm-project/llvm/lib/Transforms/Utils/SampleProfileInference.cpp (revision 98dd2f9ed3ddb0a114582d48d48f781d9c80a2da)
1 //===- SampleProfileInference.cpp - Adjust sample profiles in the IR ------===//
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 implements a profile inference algorithm. Given an incomplete and
10 // possibly imprecise block counts, the algorithm reconstructs realistic block
11 // and edge counts that satisfy flow conservation rules, while minimally modify
12 // input block counts.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/Utils/SampleProfileInference.h"
17 #include "llvm/Support/Debug.h"
18 #include <queue>
19 #include <set>
20 
21 using namespace llvm;
22 #define DEBUG_TYPE "sample-profile-inference"
23 
24 namespace {
25 
26 /// A value indicating an infinite flow/capacity/weight of a block/edge.
27 /// Not using numeric_limits<int64_t>::max(), as the values can be summed up
28 /// during the execution.
29 static constexpr int64_t INF = ((int64_t)1) << 50;
30 
31 /// The minimum-cost maximum flow algorithm.
32 ///
33 /// The algorithm finds the maximum flow of minimum cost on a given (directed)
34 /// network using a modified version of the classical Moore-Bellman-Ford
35 /// approach. The algorithm applies a number of augmentation iterations in which
36 /// flow is sent along paths of positive capacity from the source to the sink.
37 /// The worst-case time complexity of the implementation is O(v(f)*m*n), where
38 /// where m is the number of edges, n is the number of vertices, and v(f) is the
39 /// value of the maximum flow. However, the observed running time on typical
40 /// instances is sub-quadratic, that is, o(n^2).
41 ///
42 /// The input is a set of edges with specified costs and capacities, and a pair
43 /// of nodes (source and sink). The output is the flow along each edge of the
44 /// minimum total cost respecting the given edge capacities.
45 class MinCostMaxFlow {
46 public:
47   // Initialize algorithm's data structures for a network of a given size.
48   void initialize(uint64_t NodeCount, uint64_t SourceNode, uint64_t SinkNode) {
49     Source = SourceNode;
50     Target = SinkNode;
51 
52     Nodes = std::vector<Node>(NodeCount);
53     Edges = std::vector<std::vector<Edge>>(NodeCount, std::vector<Edge>());
54   }
55 
56   // Run the algorithm.
57   int64_t run() {
58     // Find an augmenting path and update the flow along the path
59     size_t AugmentationIters = 0;
60     while (findAugmentingPath()) {
61       augmentFlowAlongPath();
62       AugmentationIters++;
63     }
64 
65     // Compute the total flow and its cost
66     int64_t TotalCost = 0;
67     int64_t TotalFlow = 0;
68     for (uint64_t Src = 0; Src < Nodes.size(); Src++) {
69       for (auto &Edge : Edges[Src]) {
70         if (Edge.Flow > 0) {
71           TotalCost += Edge.Cost * Edge.Flow;
72           if (Src == Source)
73             TotalFlow += Edge.Flow;
74         }
75       }
76     }
77     LLVM_DEBUG(dbgs() << "Completed profi after " << AugmentationIters
78                       << " iterations with " << TotalFlow << " total flow"
79                       << " of " << TotalCost << " cost\n");
80     (void)TotalFlow;
81     return TotalCost;
82   }
83 
84   /// Adding an edge to the network with a specified capacity and a cost.
85   /// Multiple edges between a pair of nodes are allowed but self-edges
86   /// are not supported.
87   void addEdge(uint64_t Src, uint64_t Dst, int64_t Capacity, int64_t Cost) {
88     assert(Capacity > 0 && "adding an edge of zero capacity");
89     assert(Src != Dst && "loop edge are not supported");
90 
91     Edge SrcEdge;
92     SrcEdge.Dst = Dst;
93     SrcEdge.Cost = Cost;
94     SrcEdge.Capacity = Capacity;
95     SrcEdge.Flow = 0;
96     SrcEdge.RevEdgeIndex = Edges[Dst].size();
97 
98     Edge DstEdge;
99     DstEdge.Dst = Src;
100     DstEdge.Cost = -Cost;
101     DstEdge.Capacity = 0;
102     DstEdge.Flow = 0;
103     DstEdge.RevEdgeIndex = Edges[Src].size();
104 
105     Edges[Src].push_back(SrcEdge);
106     Edges[Dst].push_back(DstEdge);
107   }
108 
109   /// Adding an edge to the network of infinite capacity and a given cost.
110   void addEdge(uint64_t Src, uint64_t Dst, int64_t Cost) {
111     addEdge(Src, Dst, INF, Cost);
112   }
113 
114   /// Get the total flow from a given source node.
115   /// Returns a list of pairs (target node, amount of flow to the target).
116   const std::vector<std::pair<uint64_t, int64_t>> getFlow(uint64_t Src) const {
117     std::vector<std::pair<uint64_t, int64_t>> Flow;
118     for (auto &Edge : Edges[Src]) {
119       if (Edge.Flow > 0)
120         Flow.push_back(std::make_pair(Edge.Dst, Edge.Flow));
121     }
122     return Flow;
123   }
124 
125   /// Get the total flow between a pair of nodes.
126   int64_t getFlow(uint64_t Src, uint64_t Dst) const {
127     int64_t Flow = 0;
128     for (auto &Edge : Edges[Src]) {
129       if (Edge.Dst == Dst) {
130         Flow += Edge.Flow;
131       }
132     }
133     return Flow;
134   }
135 
136   /// A cost of increasing a block's count by one.
137   static constexpr int64_t AuxCostInc = 10;
138   /// A cost of decreasing a block's count by one.
139   static constexpr int64_t AuxCostDec = 20;
140   /// A cost of increasing a count of zero-weight block by one.
141   static constexpr int64_t AuxCostIncZero = 11;
142   /// A cost of increasing the entry block's count by one.
143   static constexpr int64_t AuxCostIncEntry = 40;
144   /// A cost of decreasing the entry block's count by one.
145   static constexpr int64_t AuxCostDecEntry = 10;
146   /// A cost of taking an unlikely jump.
147   static constexpr int64_t AuxCostUnlikely = ((int64_t)1) << 20;
148 
149 private:
150   /// Check for existence of an augmenting path with a positive capacity.
151   bool findAugmentingPath() {
152     // Initialize data structures
153     for (auto &Node : Nodes) {
154       Node.Distance = INF;
155       Node.ParentNode = uint64_t(-1);
156       Node.ParentEdgeIndex = uint64_t(-1);
157       Node.Taken = false;
158     }
159 
160     std::queue<uint64_t> Queue;
161     Queue.push(Source);
162     Nodes[Source].Distance = 0;
163     Nodes[Source].Taken = true;
164     while (!Queue.empty()) {
165       uint64_t Src = Queue.front();
166       Queue.pop();
167       Nodes[Src].Taken = false;
168       // Although the residual network contains edges with negative costs
169       // (in particular, backward edges), it can be shown that there are no
170       // negative-weight cycles and the following two invariants are maintained:
171       // (i) Dist[Source, V] >= 0 and (ii) Dist[V, Target] >= 0 for all nodes V,
172       // where Dist is the length of the shortest path between two nodes. This
173       // allows to prune the search-space of the path-finding algorithm using
174       // the following early-stop criteria:
175       // -- If we find a path with zero-distance from Source to Target, stop the
176       //    search, as the path is the shortest since Dist[Source, Target] >= 0;
177       // -- If we have Dist[Source, V] > Dist[Source, Target], then do not
178       //    process node V, as it is guaranteed _not_ to be on a shortest path
179       //    from Source to Target; it follows from inequalities
180       //    Dist[Source, Target] >= Dist[Source, V] + Dist[V, Target]
181       //                         >= Dist[Source, V]
182       if (Nodes[Target].Distance == 0)
183         break;
184       if (Nodes[Src].Distance > Nodes[Target].Distance)
185         continue;
186 
187       // Process adjacent edges
188       for (uint64_t EdgeIdx = 0; EdgeIdx < Edges[Src].size(); EdgeIdx++) {
189         auto &Edge = Edges[Src][EdgeIdx];
190         if (Edge.Flow < Edge.Capacity) {
191           uint64_t Dst = Edge.Dst;
192           int64_t NewDistance = Nodes[Src].Distance + Edge.Cost;
193           if (Nodes[Dst].Distance > NewDistance) {
194             // Update the distance and the parent node/edge
195             Nodes[Dst].Distance = NewDistance;
196             Nodes[Dst].ParentNode = Src;
197             Nodes[Dst].ParentEdgeIndex = EdgeIdx;
198             // Add the node to the queue, if it is not there yet
199             if (!Nodes[Dst].Taken) {
200               Queue.push(Dst);
201               Nodes[Dst].Taken = true;
202             }
203           }
204         }
205       }
206     }
207 
208     return Nodes[Target].Distance != INF;
209   }
210 
211   /// Update the current flow along the augmenting path.
212   void augmentFlowAlongPath() {
213     // Find path capacity
214     int64_t PathCapacity = INF;
215     uint64_t Now = Target;
216     while (Now != Source) {
217       uint64_t Pred = Nodes[Now].ParentNode;
218       auto &Edge = Edges[Pred][Nodes[Now].ParentEdgeIndex];
219       PathCapacity = std::min(PathCapacity, Edge.Capacity - Edge.Flow);
220       Now = Pred;
221     }
222 
223     assert(PathCapacity > 0 && "found incorrect augmenting path");
224 
225     // Update the flow along the path
226     Now = Target;
227     while (Now != Source) {
228       uint64_t Pred = Nodes[Now].ParentNode;
229       auto &Edge = Edges[Pred][Nodes[Now].ParentEdgeIndex];
230       auto &RevEdge = Edges[Now][Edge.RevEdgeIndex];
231 
232       Edge.Flow += PathCapacity;
233       RevEdge.Flow -= PathCapacity;
234 
235       Now = Pred;
236     }
237   }
238 
239   /// An node in a flow network.
240   struct Node {
241     /// The cost of the cheapest path from the source to the current node.
242     int64_t Distance;
243     /// The node preceding the current one in the path.
244     uint64_t ParentNode;
245     /// The index of the edge between ParentNode and the current node.
246     uint64_t ParentEdgeIndex;
247     /// An indicator of whether the current node is in a queue.
248     bool Taken;
249   };
250   /// An edge in a flow network.
251   struct Edge {
252     /// The cost of the edge.
253     int64_t Cost;
254     /// The capacity of the edge.
255     int64_t Capacity;
256     /// The current flow on the edge.
257     int64_t Flow;
258     /// The destination node of the edge.
259     uint64_t Dst;
260     /// The index of the reverse edge between Dst and the current node.
261     uint64_t RevEdgeIndex;
262   };
263 
264   /// The set of network nodes.
265   std::vector<Node> Nodes;
266   /// The set of network edges.
267   std::vector<std::vector<Edge>> Edges;
268   /// Source node of the flow.
269   uint64_t Source;
270   /// Target (sink) node of the flow.
271   uint64_t Target;
272 };
273 
274 /// Post-processing adjustment of the control flow.
275 class FlowAdjuster {
276 public:
277   FlowAdjuster(FlowFunction &Func) : Func(Func) {
278     assert(Func.Blocks[Func.Entry].isEntry() &&
279            "incorrect index of the entry block");
280   }
281 
282   // Run the post-processing
283   void run() {
284     /// We adjust the control flow in a function so as to remove all
285     /// "isolated" components with positive flow that are unreachable
286     /// from the entry block. For every such component, we find the shortest
287     /// path from the entry to an exit passing through the component, and
288     /// increase the flow by one unit along the path.
289     joinIsolatedComponents();
290   }
291 
292 private:
293   void joinIsolatedComponents() {
294     // Find blocks that are reachable from the source
295     auto Visited = std::vector<bool>(NumBlocks(), false);
296     findReachable(Func.Entry, Visited);
297 
298     // Iterate over all non-reachable blocks and adjust their weights
299     for (uint64_t I = 0; I < NumBlocks(); I++) {
300       auto &Block = Func.Blocks[I];
301       if (Block.Flow > 0 && !Visited[I]) {
302         // Find a path from the entry to an exit passing through the block I
303         auto Path = findShortestPath(I);
304         // Increase the flow along the path
305         assert(Path.size() > 0 && Path[0]->Source == Func.Entry &&
306                "incorrectly computed path adjusting control flow");
307         Func.Blocks[Func.Entry].Flow += 1;
308         for (auto &Jump : Path) {
309           Jump->Flow += 1;
310           Func.Blocks[Jump->Target].Flow += 1;
311           // Update reachability
312           findReachable(Jump->Target, Visited);
313         }
314       }
315     }
316   }
317 
318   /// Run bfs from a given block along the jumps with a positive flow and mark
319   /// all reachable blocks.
320   void findReachable(uint64_t Src, std::vector<bool> &Visited) {
321     if (Visited[Src])
322       return;
323     std::queue<uint64_t> Queue;
324     Queue.push(Src);
325     Visited[Src] = true;
326     while (!Queue.empty()) {
327       Src = Queue.front();
328       Queue.pop();
329       for (auto Jump : Func.Blocks[Src].SuccJumps) {
330         uint64_t Dst = Jump->Target;
331         if (Jump->Flow > 0 && !Visited[Dst]) {
332           Queue.push(Dst);
333           Visited[Dst] = true;
334         }
335       }
336     }
337   }
338 
339   /// Find the shortest path from the entry block to an exit block passing
340   /// through a given block.
341   std::vector<FlowJump *> findShortestPath(uint64_t BlockIdx) {
342     // A path from the entry block to BlockIdx
343     auto ForwardPath = findShortestPath(Func.Entry, BlockIdx);
344     // A path from BlockIdx to an exit block
345     auto BackwardPath = findShortestPath(BlockIdx, AnyExitBlock);
346 
347     // Concatenate the two paths
348     std::vector<FlowJump *> Result;
349     Result.insert(Result.end(), ForwardPath.begin(), ForwardPath.end());
350     Result.insert(Result.end(), BackwardPath.begin(), BackwardPath.end());
351     return Result;
352   }
353 
354   /// Apply the Dijkstra algorithm to find the shortest path from a given
355   /// Source to a given Target block.
356   /// If Target == -1, then the path ends at an exit block.
357   std::vector<FlowJump *> findShortestPath(uint64_t Source, uint64_t Target) {
358     // Quit early, if possible
359     if (Source == Target)
360       return std::vector<FlowJump *>();
361     if (Func.Blocks[Source].isExit() && Target == AnyExitBlock)
362       return std::vector<FlowJump *>();
363 
364     // Initialize data structures
365     auto Distance = std::vector<int64_t>(NumBlocks(), INF);
366     auto Parent = std::vector<FlowJump *>(NumBlocks(), nullptr);
367     Distance[Source] = 0;
368     std::set<std::pair<uint64_t, uint64_t>> Queue;
369     Queue.insert(std::make_pair(Distance[Source], Source));
370 
371     // Run the Dijkstra algorithm
372     while (!Queue.empty()) {
373       uint64_t Src = Queue.begin()->second;
374       Queue.erase(Queue.begin());
375       // If we found a solution, quit early
376       if (Src == Target ||
377           (Func.Blocks[Src].isExit() && Target == AnyExitBlock))
378         break;
379 
380       for (auto Jump : Func.Blocks[Src].SuccJumps) {
381         uint64_t Dst = Jump->Target;
382         int64_t JumpDist = jumpDistance(Jump);
383         if (Distance[Dst] > Distance[Src] + JumpDist) {
384           Queue.erase(std::make_pair(Distance[Dst], Dst));
385 
386           Distance[Dst] = Distance[Src] + JumpDist;
387           Parent[Dst] = Jump;
388 
389           Queue.insert(std::make_pair(Distance[Dst], Dst));
390         }
391       }
392     }
393     // If Target is not provided, find the closest exit block
394     if (Target == AnyExitBlock) {
395       for (uint64_t I = 0; I < NumBlocks(); I++) {
396         if (Func.Blocks[I].isExit() && Parent[I] != nullptr) {
397           if (Target == AnyExitBlock || Distance[Target] > Distance[I]) {
398             Target = I;
399           }
400         }
401       }
402     }
403     assert(Parent[Target] != nullptr && "a path does not exist");
404 
405     // Extract the constructed path
406     std::vector<FlowJump *> Result;
407     uint64_t Now = Target;
408     while (Now != Source) {
409       assert(Now == Parent[Now]->Target && "incorrect parent jump");
410       Result.push_back(Parent[Now]);
411       Now = Parent[Now]->Source;
412     }
413     // Reverse the path, since it is extracted from Target to Source
414     std::reverse(Result.begin(), Result.end());
415     return Result;
416   }
417 
418   /// A distance of a path for a given jump.
419   /// In order to incite the path to use blocks/jumps with large positive flow,
420   /// and avoid changing branch probability of outgoing edges drastically,
421   /// set the distance as follows:
422   ///   if Jump.Flow > 0, then distance = max(100 - Jump->Flow, 0)
423   ///   if Block.Weight > 0, then distance = 1
424   ///   otherwise distance >> 1
425   int64_t jumpDistance(FlowJump *Jump) const {
426     int64_t BaseDistance = 100;
427     if (Jump->IsUnlikely)
428       return MinCostMaxFlow::AuxCostUnlikely;
429     if (Jump->Flow > 0)
430       return std::max(BaseDistance - (int64_t)Jump->Flow, (int64_t)0);
431     if (Func.Blocks[Jump->Target].Weight > 0)
432       return BaseDistance;
433     return BaseDistance * (NumBlocks() + 1);
434   };
435 
436   uint64_t NumBlocks() const { return Func.Blocks.size(); }
437 
438   /// A constant indicating an arbitrary exit block of a function.
439   static constexpr uint64_t AnyExitBlock = uint64_t(-1);
440 
441   /// The function.
442   FlowFunction &Func;
443 };
444 
445 /// Initializing flow network for a given function.
446 ///
447 /// Every block is split into three nodes that are responsible for (i) an
448 /// incoming flow, (ii) an outgoing flow, and (iii) penalizing an increase or
449 /// reduction of the block weight.
450 void initializeNetwork(MinCostMaxFlow &Network, FlowFunction &Func) {
451   uint64_t NumBlocks = Func.Blocks.size();
452   assert(NumBlocks > 1 && "Too few blocks in a function");
453   LLVM_DEBUG(dbgs() << "Initializing profi for " << NumBlocks << " blocks\n");
454 
455   // Pre-process data: make sure the entry weight is at least 1
456   if (Func.Blocks[Func.Entry].Weight == 0) {
457     Func.Blocks[Func.Entry].Weight = 1;
458   }
459   // Introducing dummy source/sink pairs to allow flow circulation.
460   // The nodes corresponding to blocks of Func have indicies in the range
461   // [0..3 * NumBlocks); the dummy nodes are indexed by the next four values.
462   uint64_t S = 3 * NumBlocks;
463   uint64_t T = S + 1;
464   uint64_t S1 = S + 2;
465   uint64_t T1 = S + 3;
466 
467   Network.initialize(3 * NumBlocks + 4, S1, T1);
468 
469   // Create three nodes for every block of the function
470   for (uint64_t B = 0; B < NumBlocks; B++) {
471     auto &Block = Func.Blocks[B];
472     assert((!Block.UnknownWeight || Block.Weight == 0 || Block.isEntry()) &&
473            "non-zero weight of a block w/o weight except for an entry");
474 
475     // Split every block into two nodes
476     uint64_t Bin = 3 * B;
477     uint64_t Bout = 3 * B + 1;
478     uint64_t Baux = 3 * B + 2;
479     if (Block.Weight > 0) {
480       Network.addEdge(S1, Bout, Block.Weight, 0);
481       Network.addEdge(Bin, T1, Block.Weight, 0);
482     }
483 
484     // Edges from S and to T
485     assert((!Block.isEntry() || !Block.isExit()) &&
486            "a block cannot be an entry and an exit");
487     if (Block.isEntry()) {
488       Network.addEdge(S, Bin, 0);
489     } else if (Block.isExit()) {
490       Network.addEdge(Bout, T, 0);
491     }
492 
493     // An auxiliary node to allow increase/reduction of block counts:
494     // We assume that decreasing block counts is more expensive than increasing,
495     // and thus, setting separate costs here. In the future we may want to tune
496     // the relative costs so as to maximize the quality of generated profiles.
497     int64_t AuxCostInc = MinCostMaxFlow::AuxCostInc;
498     int64_t AuxCostDec = MinCostMaxFlow::AuxCostDec;
499     if (Block.UnknownWeight) {
500       // Do not penalize changing weights of blocks w/o known profile count
501       AuxCostInc = 0;
502       AuxCostDec = 0;
503     } else {
504       // Increasing the count for "cold" blocks with zero initial count is more
505       // expensive than for "hot" ones
506       if (Block.Weight == 0) {
507         AuxCostInc = MinCostMaxFlow::AuxCostIncZero;
508       }
509       // Modifying the count of the entry block is expensive
510       if (Block.isEntry()) {
511         AuxCostInc = MinCostMaxFlow::AuxCostIncEntry;
512         AuxCostDec = MinCostMaxFlow::AuxCostDecEntry;
513       }
514     }
515     // For blocks with self-edges, do not penalize a reduction of the count,
516     // as all of the increase can be attributed to the self-edge
517     if (Block.HasSelfEdge) {
518       AuxCostDec = 0;
519     }
520 
521     Network.addEdge(Bin, Baux, AuxCostInc);
522     Network.addEdge(Baux, Bout, AuxCostInc);
523     if (Block.Weight > 0) {
524       Network.addEdge(Bout, Baux, AuxCostDec);
525       Network.addEdge(Baux, Bin, AuxCostDec);
526     }
527   }
528 
529   // Creating edges for every jump
530   for (auto &Jump : Func.Jumps) {
531     uint64_t Src = Jump.Source;
532     uint64_t Dst = Jump.Target;
533     if (Src != Dst) {
534       uint64_t SrcOut = 3 * Src + 1;
535       uint64_t DstIn = 3 * Dst;
536       uint64_t Cost = Jump.IsUnlikely ? MinCostMaxFlow::AuxCostUnlikely : 0;
537       Network.addEdge(SrcOut, DstIn, Cost);
538     }
539   }
540 
541   // Make sure we have a valid flow circulation
542   Network.addEdge(T, S, 0);
543 }
544 
545 /// Extract resulting block and edge counts from the flow network.
546 void extractWeights(MinCostMaxFlow &Network, FlowFunction &Func) {
547   uint64_t NumBlocks = Func.Blocks.size();
548 
549   // Extract resulting block counts
550   for (uint64_t Src = 0; Src < NumBlocks; Src++) {
551     auto &Block = Func.Blocks[Src];
552     uint64_t SrcOut = 3 * Src + 1;
553     int64_t Flow = 0;
554     for (auto &Adj : Network.getFlow(SrcOut)) {
555       uint64_t DstIn = Adj.first;
556       int64_t DstFlow = Adj.second;
557       bool IsAuxNode = (DstIn < 3 * NumBlocks && DstIn % 3 == 2);
558       if (!IsAuxNode || Block.HasSelfEdge) {
559         Flow += DstFlow;
560       }
561     }
562     Block.Flow = Flow;
563     assert(Flow >= 0 && "negative block flow");
564   }
565 
566   // Extract resulting jump counts
567   for (auto &Jump : Func.Jumps) {
568     uint64_t Src = Jump.Source;
569     uint64_t Dst = Jump.Target;
570     int64_t Flow = 0;
571     if (Src != Dst) {
572       uint64_t SrcOut = 3 * Src + 1;
573       uint64_t DstIn = 3 * Dst;
574       Flow = Network.getFlow(SrcOut, DstIn);
575     } else {
576       uint64_t SrcOut = 3 * Src + 1;
577       uint64_t SrcAux = 3 * Src + 2;
578       int64_t AuxFlow = Network.getFlow(SrcOut, SrcAux);
579       if (AuxFlow > 0)
580         Flow = AuxFlow;
581     }
582     Jump.Flow = Flow;
583     assert(Flow >= 0 && "negative jump flow");
584   }
585 }
586 
587 #ifndef NDEBUG
588 /// Verify that the computed flow values satisfy flow conservation rules
589 void verifyWeights(const FlowFunction &Func) {
590   const uint64_t NumBlocks = Func.Blocks.size();
591   auto InFlow = std::vector<uint64_t>(NumBlocks, 0);
592   auto OutFlow = std::vector<uint64_t>(NumBlocks, 0);
593   for (auto &Jump : Func.Jumps) {
594     InFlow[Jump.Target] += Jump.Flow;
595     OutFlow[Jump.Source] += Jump.Flow;
596   }
597 
598   uint64_t TotalInFlow = 0;
599   uint64_t TotalOutFlow = 0;
600   for (uint64_t I = 0; I < NumBlocks; I++) {
601     auto &Block = Func.Blocks[I];
602     if (Block.isEntry()) {
603       TotalInFlow += Block.Flow;
604       assert(Block.Flow == OutFlow[I] && "incorrectly computed control flow");
605     } else if (Block.isExit()) {
606       TotalOutFlow += Block.Flow;
607       assert(Block.Flow == InFlow[I] && "incorrectly computed control flow");
608     } else {
609       assert(Block.Flow == OutFlow[I] && "incorrectly computed control flow");
610       assert(Block.Flow == InFlow[I] && "incorrectly computed control flow");
611     }
612   }
613   assert(TotalInFlow == TotalOutFlow && "incorrectly computed control flow");
614 
615   // Verify that there are no isolated flow components
616   // One could modify FlowFunction to hold edges indexed by the sources, which
617   // will avoid a creation of the object
618   auto PositiveFlowEdges = std::vector<std::vector<uint64_t>>(NumBlocks);
619   for (auto &Jump : Func.Jumps) {
620     if (Jump.Flow > 0) {
621       PositiveFlowEdges[Jump.Source].push_back(Jump.Target);
622     }
623   }
624 
625   // Run bfs from the source along edges with positive flow
626   std::queue<uint64_t> Queue;
627   auto Visited = std::vector<bool>(NumBlocks, false);
628   Queue.push(Func.Entry);
629   Visited[Func.Entry] = true;
630   while (!Queue.empty()) {
631     uint64_t Src = Queue.front();
632     Queue.pop();
633     for (uint64_t Dst : PositiveFlowEdges[Src]) {
634       if (!Visited[Dst]) {
635         Queue.push(Dst);
636         Visited[Dst] = true;
637       }
638     }
639   }
640 
641   // Verify that every block that has a positive flow is reached from the source
642   // along edges with a positive flow
643   for (uint64_t I = 0; I < NumBlocks; I++) {
644     auto &Block = Func.Blocks[I];
645     assert((Visited[I] || Block.Flow == 0) && "an isolated flow component");
646   }
647 }
648 #endif
649 
650 } // end of anonymous namespace
651 
652 /// Apply the profile inference algorithm for a given flow function
653 void llvm::applyFlowInference(FlowFunction &Func) {
654   // Create and apply an inference network model
655   auto InferenceNetwork = MinCostMaxFlow();
656   initializeNetwork(InferenceNetwork, Func);
657   InferenceNetwork.run();
658 
659   // Extract flow values for every block and every edge
660   extractWeights(InferenceNetwork, Func);
661 
662   // Post-processing adjustments to the flow
663   auto Adjuster = FlowAdjuster(Func);
664   Adjuster.run();
665 
666 #ifndef NDEBUG
667   // Verify the result
668   verifyWeights(Func);
669 #endif
670 }
671