17cc2493dSspupyrev //===- SampleProfileInference.cpp - Adjust sample profiles in the IR ------===// 27cc2493dSspupyrev // 37cc2493dSspupyrev // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 47cc2493dSspupyrev // See https://llvm.org/LICENSE.txt for license information. 57cc2493dSspupyrev // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 67cc2493dSspupyrev // 77cc2493dSspupyrev //===----------------------------------------------------------------------===// 87cc2493dSspupyrev // 97cc2493dSspupyrev // This file implements a profile inference algorithm. Given an incomplete and 107cc2493dSspupyrev // possibly imprecise block counts, the algorithm reconstructs realistic block 117cc2493dSspupyrev // and edge counts that satisfy flow conservation rules, while minimally modify 127cc2493dSspupyrev // input block counts. 137cc2493dSspupyrev // 147cc2493dSspupyrev //===----------------------------------------------------------------------===// 157cc2493dSspupyrev 167cc2493dSspupyrev #include "llvm/Transforms/Utils/SampleProfileInference.h" 17*5f4ae564SJan Svoboda #include "llvm/ADT/BitVector.h" 187cc2493dSspupyrev #include "llvm/Support/Debug.h" 197cc2493dSspupyrev #include <queue> 207cc2493dSspupyrev #include <set> 217cc2493dSspupyrev 227cc2493dSspupyrev using namespace llvm; 237cc2493dSspupyrev #define DEBUG_TYPE "sample-profile-inference" 247cc2493dSspupyrev 257cc2493dSspupyrev namespace { 267cc2493dSspupyrev 277cc2493dSspupyrev /// A value indicating an infinite flow/capacity/weight of a block/edge. 287cc2493dSspupyrev /// Not using numeric_limits<int64_t>::max(), as the values can be summed up 297cc2493dSspupyrev /// during the execution. 307cc2493dSspupyrev static constexpr int64_t INF = ((int64_t)1) << 50; 317cc2493dSspupyrev 327cc2493dSspupyrev /// The minimum-cost maximum flow algorithm. 337cc2493dSspupyrev /// 347cc2493dSspupyrev /// The algorithm finds the maximum flow of minimum cost on a given (directed) 357cc2493dSspupyrev /// network using a modified version of the classical Moore-Bellman-Ford 367cc2493dSspupyrev /// approach. The algorithm applies a number of augmentation iterations in which 377cc2493dSspupyrev /// flow is sent along paths of positive capacity from the source to the sink. 387cc2493dSspupyrev /// The worst-case time complexity of the implementation is O(v(f)*m*n), where 397cc2493dSspupyrev /// where m is the number of edges, n is the number of vertices, and v(f) is the 407cc2493dSspupyrev /// value of the maximum flow. However, the observed running time on typical 417cc2493dSspupyrev /// instances is sub-quadratic, that is, o(n^2). 427cc2493dSspupyrev /// 437cc2493dSspupyrev /// The input is a set of edges with specified costs and capacities, and a pair 447cc2493dSspupyrev /// of nodes (source and sink). The output is the flow along each edge of the 457cc2493dSspupyrev /// minimum total cost respecting the given edge capacities. 467cc2493dSspupyrev class MinCostMaxFlow { 477cc2493dSspupyrev public: 487cc2493dSspupyrev // Initialize algorithm's data structures for a network of a given size. 497cc2493dSspupyrev void initialize(uint64_t NodeCount, uint64_t SourceNode, uint64_t SinkNode) { 507cc2493dSspupyrev Source = SourceNode; 517cc2493dSspupyrev Target = SinkNode; 527cc2493dSspupyrev 537cc2493dSspupyrev Nodes = std::vector<Node>(NodeCount); 547cc2493dSspupyrev Edges = std::vector<std::vector<Edge>>(NodeCount, std::vector<Edge>()); 557cc2493dSspupyrev } 567cc2493dSspupyrev 577cc2493dSspupyrev // Run the algorithm. 587cc2493dSspupyrev int64_t run() { 597cc2493dSspupyrev // Find an augmenting path and update the flow along the path 607cc2493dSspupyrev size_t AugmentationIters = 0; 617cc2493dSspupyrev while (findAugmentingPath()) { 627cc2493dSspupyrev augmentFlowAlongPath(); 637cc2493dSspupyrev AugmentationIters++; 647cc2493dSspupyrev } 657cc2493dSspupyrev 667cc2493dSspupyrev // Compute the total flow and its cost 677cc2493dSspupyrev int64_t TotalCost = 0; 687cc2493dSspupyrev int64_t TotalFlow = 0; 697cc2493dSspupyrev for (uint64_t Src = 0; Src < Nodes.size(); Src++) { 707cc2493dSspupyrev for (auto &Edge : Edges[Src]) { 717cc2493dSspupyrev if (Edge.Flow > 0) { 727cc2493dSspupyrev TotalCost += Edge.Cost * Edge.Flow; 737cc2493dSspupyrev if (Src == Source) 747cc2493dSspupyrev TotalFlow += Edge.Flow; 757cc2493dSspupyrev } 767cc2493dSspupyrev } 777cc2493dSspupyrev } 787cc2493dSspupyrev LLVM_DEBUG(dbgs() << "Completed profi after " << AugmentationIters 797cc2493dSspupyrev << " iterations with " << TotalFlow << " total flow" 807cc2493dSspupyrev << " of " << TotalCost << " cost\n"); 8122d82949SKazu Hirata (void)TotalFlow; 827cc2493dSspupyrev return TotalCost; 837cc2493dSspupyrev } 847cc2493dSspupyrev 857cc2493dSspupyrev /// Adding an edge to the network with a specified capacity and a cost. 867cc2493dSspupyrev /// Multiple edges between a pair of nodes are allowed but self-edges 877cc2493dSspupyrev /// are not supported. 887cc2493dSspupyrev void addEdge(uint64_t Src, uint64_t Dst, int64_t Capacity, int64_t Cost) { 897cc2493dSspupyrev assert(Capacity > 0 && "adding an edge of zero capacity"); 907cc2493dSspupyrev assert(Src != Dst && "loop edge are not supported"); 917cc2493dSspupyrev 927cc2493dSspupyrev Edge SrcEdge; 937cc2493dSspupyrev SrcEdge.Dst = Dst; 947cc2493dSspupyrev SrcEdge.Cost = Cost; 957cc2493dSspupyrev SrcEdge.Capacity = Capacity; 967cc2493dSspupyrev SrcEdge.Flow = 0; 977cc2493dSspupyrev SrcEdge.RevEdgeIndex = Edges[Dst].size(); 987cc2493dSspupyrev 997cc2493dSspupyrev Edge DstEdge; 1007cc2493dSspupyrev DstEdge.Dst = Src; 1017cc2493dSspupyrev DstEdge.Cost = -Cost; 1027cc2493dSspupyrev DstEdge.Capacity = 0; 1037cc2493dSspupyrev DstEdge.Flow = 0; 1047cc2493dSspupyrev DstEdge.RevEdgeIndex = Edges[Src].size(); 1057cc2493dSspupyrev 1067cc2493dSspupyrev Edges[Src].push_back(SrcEdge); 1077cc2493dSspupyrev Edges[Dst].push_back(DstEdge); 1087cc2493dSspupyrev } 1097cc2493dSspupyrev 1107cc2493dSspupyrev /// Adding an edge to the network of infinite capacity and a given cost. 1117cc2493dSspupyrev void addEdge(uint64_t Src, uint64_t Dst, int64_t Cost) { 1127cc2493dSspupyrev addEdge(Src, Dst, INF, Cost); 1137cc2493dSspupyrev } 1147cc2493dSspupyrev 1157cc2493dSspupyrev /// Get the total flow from a given source node. 1167cc2493dSspupyrev /// Returns a list of pairs (target node, amount of flow to the target). 1177cc2493dSspupyrev const std::vector<std::pair<uint64_t, int64_t>> getFlow(uint64_t Src) const { 1187cc2493dSspupyrev std::vector<std::pair<uint64_t, int64_t>> Flow; 1197cc2493dSspupyrev for (auto &Edge : Edges[Src]) { 1207cc2493dSspupyrev if (Edge.Flow > 0) 1217cc2493dSspupyrev Flow.push_back(std::make_pair(Edge.Dst, Edge.Flow)); 1227cc2493dSspupyrev } 1237cc2493dSspupyrev return Flow; 1247cc2493dSspupyrev } 1257cc2493dSspupyrev 1267cc2493dSspupyrev /// Get the total flow between a pair of nodes. 1277cc2493dSspupyrev int64_t getFlow(uint64_t Src, uint64_t Dst) const { 1287cc2493dSspupyrev int64_t Flow = 0; 1297cc2493dSspupyrev for (auto &Edge : Edges[Src]) { 1307cc2493dSspupyrev if (Edge.Dst == Dst) { 1317cc2493dSspupyrev Flow += Edge.Flow; 1327cc2493dSspupyrev } 1337cc2493dSspupyrev } 1347cc2493dSspupyrev return Flow; 1357cc2493dSspupyrev } 1367cc2493dSspupyrev 1377cc2493dSspupyrev /// A cost of increasing a block's count by one. 1387cc2493dSspupyrev static constexpr int64_t AuxCostInc = 10; 1397cc2493dSspupyrev /// A cost of decreasing a block's count by one. 1407cc2493dSspupyrev static constexpr int64_t AuxCostDec = 20; 1417cc2493dSspupyrev /// A cost of increasing a count of zero-weight block by one. 1427cc2493dSspupyrev static constexpr int64_t AuxCostIncZero = 11; 1437cc2493dSspupyrev /// A cost of increasing the entry block's count by one. 1447cc2493dSspupyrev static constexpr int64_t AuxCostIncEntry = 40; 1457cc2493dSspupyrev /// A cost of decreasing the entry block's count by one. 1467cc2493dSspupyrev static constexpr int64_t AuxCostDecEntry = 10; 1477cc2493dSspupyrev /// A cost of taking an unlikely jump. 1487cc2493dSspupyrev static constexpr int64_t AuxCostUnlikely = ((int64_t)1) << 20; 1497cc2493dSspupyrev 1507cc2493dSspupyrev private: 1517cc2493dSspupyrev /// Check for existence of an augmenting path with a positive capacity. 1527cc2493dSspupyrev bool findAugmentingPath() { 1537cc2493dSspupyrev // Initialize data structures 1547cc2493dSspupyrev for (auto &Node : Nodes) { 1557cc2493dSspupyrev Node.Distance = INF; 1567cc2493dSspupyrev Node.ParentNode = uint64_t(-1); 1577cc2493dSspupyrev Node.ParentEdgeIndex = uint64_t(-1); 1587cc2493dSspupyrev Node.Taken = false; 1597cc2493dSspupyrev } 1607cc2493dSspupyrev 1617cc2493dSspupyrev std::queue<uint64_t> Queue; 1627cc2493dSspupyrev Queue.push(Source); 1637cc2493dSspupyrev Nodes[Source].Distance = 0; 1647cc2493dSspupyrev Nodes[Source].Taken = true; 1657cc2493dSspupyrev while (!Queue.empty()) { 1667cc2493dSspupyrev uint64_t Src = Queue.front(); 1677cc2493dSspupyrev Queue.pop(); 1687cc2493dSspupyrev Nodes[Src].Taken = false; 1697cc2493dSspupyrev // Although the residual network contains edges with negative costs 1707cc2493dSspupyrev // (in particular, backward edges), it can be shown that there are no 1717cc2493dSspupyrev // negative-weight cycles and the following two invariants are maintained: 1727cc2493dSspupyrev // (i) Dist[Source, V] >= 0 and (ii) Dist[V, Target] >= 0 for all nodes V, 1737cc2493dSspupyrev // where Dist is the length of the shortest path between two nodes. This 1747cc2493dSspupyrev // allows to prune the search-space of the path-finding algorithm using 1757cc2493dSspupyrev // the following early-stop criteria: 1767cc2493dSspupyrev // -- If we find a path with zero-distance from Source to Target, stop the 1777cc2493dSspupyrev // search, as the path is the shortest since Dist[Source, Target] >= 0; 1787cc2493dSspupyrev // -- If we have Dist[Source, V] > Dist[Source, Target], then do not 1797cc2493dSspupyrev // process node V, as it is guaranteed _not_ to be on a shortest path 1807cc2493dSspupyrev // from Source to Target; it follows from inequalities 1817cc2493dSspupyrev // Dist[Source, Target] >= Dist[Source, V] + Dist[V, Target] 1827cc2493dSspupyrev // >= Dist[Source, V] 1837cc2493dSspupyrev if (Nodes[Target].Distance == 0) 1847cc2493dSspupyrev break; 1857cc2493dSspupyrev if (Nodes[Src].Distance > Nodes[Target].Distance) 1867cc2493dSspupyrev continue; 1877cc2493dSspupyrev 1887cc2493dSspupyrev // Process adjacent edges 1897cc2493dSspupyrev for (uint64_t EdgeIdx = 0; EdgeIdx < Edges[Src].size(); EdgeIdx++) { 1907cc2493dSspupyrev auto &Edge = Edges[Src][EdgeIdx]; 1917cc2493dSspupyrev if (Edge.Flow < Edge.Capacity) { 1927cc2493dSspupyrev uint64_t Dst = Edge.Dst; 1937cc2493dSspupyrev int64_t NewDistance = Nodes[Src].Distance + Edge.Cost; 1947cc2493dSspupyrev if (Nodes[Dst].Distance > NewDistance) { 1957cc2493dSspupyrev // Update the distance and the parent node/edge 1967cc2493dSspupyrev Nodes[Dst].Distance = NewDistance; 1977cc2493dSspupyrev Nodes[Dst].ParentNode = Src; 1987cc2493dSspupyrev Nodes[Dst].ParentEdgeIndex = EdgeIdx; 1997cc2493dSspupyrev // Add the node to the queue, if it is not there yet 2007cc2493dSspupyrev if (!Nodes[Dst].Taken) { 2017cc2493dSspupyrev Queue.push(Dst); 2027cc2493dSspupyrev Nodes[Dst].Taken = true; 2037cc2493dSspupyrev } 2047cc2493dSspupyrev } 2057cc2493dSspupyrev } 2067cc2493dSspupyrev } 2077cc2493dSspupyrev } 2087cc2493dSspupyrev 2097cc2493dSspupyrev return Nodes[Target].Distance != INF; 2107cc2493dSspupyrev } 2117cc2493dSspupyrev 2127cc2493dSspupyrev /// Update the current flow along the augmenting path. 2137cc2493dSspupyrev void augmentFlowAlongPath() { 2147cc2493dSspupyrev // Find path capacity 2157cc2493dSspupyrev int64_t PathCapacity = INF; 2167cc2493dSspupyrev uint64_t Now = Target; 2177cc2493dSspupyrev while (Now != Source) { 2187cc2493dSspupyrev uint64_t Pred = Nodes[Now].ParentNode; 2197cc2493dSspupyrev auto &Edge = Edges[Pred][Nodes[Now].ParentEdgeIndex]; 2207cc2493dSspupyrev PathCapacity = std::min(PathCapacity, Edge.Capacity - Edge.Flow); 2217cc2493dSspupyrev Now = Pred; 2227cc2493dSspupyrev } 2237cc2493dSspupyrev 22493a2c291Sspupyrev assert(PathCapacity > 0 && "found an incorrect augmenting path"); 2257cc2493dSspupyrev 2267cc2493dSspupyrev // Update the flow along the path 2277cc2493dSspupyrev Now = Target; 2287cc2493dSspupyrev while (Now != Source) { 2297cc2493dSspupyrev uint64_t Pred = Nodes[Now].ParentNode; 2307cc2493dSspupyrev auto &Edge = Edges[Pred][Nodes[Now].ParentEdgeIndex]; 2317cc2493dSspupyrev auto &RevEdge = Edges[Now][Edge.RevEdgeIndex]; 2327cc2493dSspupyrev 2337cc2493dSspupyrev Edge.Flow += PathCapacity; 2347cc2493dSspupyrev RevEdge.Flow -= PathCapacity; 2357cc2493dSspupyrev 2367cc2493dSspupyrev Now = Pred; 2377cc2493dSspupyrev } 2387cc2493dSspupyrev } 2397cc2493dSspupyrev 2407cc2493dSspupyrev /// An node in a flow network. 2417cc2493dSspupyrev struct Node { 2427cc2493dSspupyrev /// The cost of the cheapest path from the source to the current node. 2437cc2493dSspupyrev int64_t Distance; 2447cc2493dSspupyrev /// The node preceding the current one in the path. 2457cc2493dSspupyrev uint64_t ParentNode; 2467cc2493dSspupyrev /// The index of the edge between ParentNode and the current node. 2477cc2493dSspupyrev uint64_t ParentEdgeIndex; 2487cc2493dSspupyrev /// An indicator of whether the current node is in a queue. 2497cc2493dSspupyrev bool Taken; 2507cc2493dSspupyrev }; 2517cc2493dSspupyrev /// An edge in a flow network. 2527cc2493dSspupyrev struct Edge { 2537cc2493dSspupyrev /// The cost of the edge. 2547cc2493dSspupyrev int64_t Cost; 2557cc2493dSspupyrev /// The capacity of the edge. 2567cc2493dSspupyrev int64_t Capacity; 2577cc2493dSspupyrev /// The current flow on the edge. 2587cc2493dSspupyrev int64_t Flow; 2597cc2493dSspupyrev /// The destination node of the edge. 2607cc2493dSspupyrev uint64_t Dst; 2617cc2493dSspupyrev /// The index of the reverse edge between Dst and the current node. 2627cc2493dSspupyrev uint64_t RevEdgeIndex; 2637cc2493dSspupyrev }; 2647cc2493dSspupyrev 2657cc2493dSspupyrev /// The set of network nodes. 2667cc2493dSspupyrev std::vector<Node> Nodes; 2677cc2493dSspupyrev /// The set of network edges. 2687cc2493dSspupyrev std::vector<std::vector<Edge>> Edges; 2697cc2493dSspupyrev /// Source node of the flow. 2707cc2493dSspupyrev uint64_t Source; 2717cc2493dSspupyrev /// Target (sink) node of the flow. 2727cc2493dSspupyrev uint64_t Target; 2737cc2493dSspupyrev }; 2747cc2493dSspupyrev 27593a2c291Sspupyrev /// A post-processing adjustment of control flow. It applies two steps by 27693a2c291Sspupyrev /// rerouting some flow and making it more realistic: 27793a2c291Sspupyrev /// 27893a2c291Sspupyrev /// - First, it removes all isolated components ("islands") with a positive flow 27993a2c291Sspupyrev /// that are unreachable from the entry block. For every such component, we 28093a2c291Sspupyrev /// find the shortest from the entry to an exit passing through the component, 28193a2c291Sspupyrev /// and increase the flow by one unit along the path. 28293a2c291Sspupyrev /// 28393a2c291Sspupyrev /// - Second, it identifies all "unknown subgraphs" consisting of basic blocks 28493a2c291Sspupyrev /// with no sampled counts. Then it rebalnces the flow that goes through such 28593a2c291Sspupyrev /// a subgraph so that each branch is taken with probability 50%. 28693a2c291Sspupyrev /// An unknown subgraph is such that for every two nodes u and v: 28793a2c291Sspupyrev /// - u dominates v and u is not unknown; 28893a2c291Sspupyrev /// - v post-dominates u; and 28993a2c291Sspupyrev /// - all inner-nodes of all (u,v)-paths are unknown. 29093a2c291Sspupyrev /// 29198dd2f9eSspupyrev class FlowAdjuster { 29298dd2f9eSspupyrev public: 29398dd2f9eSspupyrev FlowAdjuster(FlowFunction &Func) : Func(Func) { 29498dd2f9eSspupyrev assert(Func.Blocks[Func.Entry].isEntry() && 29598dd2f9eSspupyrev "incorrect index of the entry block"); 29698dd2f9eSspupyrev } 29798dd2f9eSspupyrev 29898dd2f9eSspupyrev // Run the post-processing 29998dd2f9eSspupyrev void run() { 30093a2c291Sspupyrev /// Adjust the flow to get rid of isolated components. 30198dd2f9eSspupyrev joinIsolatedComponents(); 30293a2c291Sspupyrev 30393a2c291Sspupyrev /// Rebalance the flow inside unknown subgraphs. 30493a2c291Sspupyrev rebalanceUnknownSubgraphs(); 30598dd2f9eSspupyrev } 30698dd2f9eSspupyrev 30793a2c291Sspupyrev /// The probability for the first successor of a unknown subgraph 30893a2c291Sspupyrev static constexpr double UnknownFirstSuccProbability = 0.5; 30993a2c291Sspupyrev 31098dd2f9eSspupyrev private: 31198dd2f9eSspupyrev void joinIsolatedComponents() { 31298dd2f9eSspupyrev // Find blocks that are reachable from the source 313*5f4ae564SJan Svoboda auto Visited = BitVector(NumBlocks(), false); 31498dd2f9eSspupyrev findReachable(Func.Entry, Visited); 31598dd2f9eSspupyrev 31698dd2f9eSspupyrev // Iterate over all non-reachable blocks and adjust their weights 31798dd2f9eSspupyrev for (uint64_t I = 0; I < NumBlocks(); I++) { 31898dd2f9eSspupyrev auto &Block = Func.Blocks[I]; 31998dd2f9eSspupyrev if (Block.Flow > 0 && !Visited[I]) { 32098dd2f9eSspupyrev // Find a path from the entry to an exit passing through the block I 32198dd2f9eSspupyrev auto Path = findShortestPath(I); 32298dd2f9eSspupyrev // Increase the flow along the path 32398dd2f9eSspupyrev assert(Path.size() > 0 && Path[0]->Source == Func.Entry && 32498dd2f9eSspupyrev "incorrectly computed path adjusting control flow"); 32598dd2f9eSspupyrev Func.Blocks[Func.Entry].Flow += 1; 32698dd2f9eSspupyrev for (auto &Jump : Path) { 32798dd2f9eSspupyrev Jump->Flow += 1; 32898dd2f9eSspupyrev Func.Blocks[Jump->Target].Flow += 1; 32998dd2f9eSspupyrev // Update reachability 33098dd2f9eSspupyrev findReachable(Jump->Target, Visited); 33198dd2f9eSspupyrev } 33298dd2f9eSspupyrev } 33398dd2f9eSspupyrev } 33498dd2f9eSspupyrev } 33598dd2f9eSspupyrev 33693a2c291Sspupyrev /// Run BFS from a given block along the jumps with a positive flow and mark 33798dd2f9eSspupyrev /// all reachable blocks. 338*5f4ae564SJan Svoboda void findReachable(uint64_t Src, BitVector &Visited) { 33998dd2f9eSspupyrev if (Visited[Src]) 34098dd2f9eSspupyrev return; 34198dd2f9eSspupyrev std::queue<uint64_t> Queue; 34298dd2f9eSspupyrev Queue.push(Src); 34398dd2f9eSspupyrev Visited[Src] = true; 34498dd2f9eSspupyrev while (!Queue.empty()) { 34598dd2f9eSspupyrev Src = Queue.front(); 34698dd2f9eSspupyrev Queue.pop(); 34798dd2f9eSspupyrev for (auto Jump : Func.Blocks[Src].SuccJumps) { 34898dd2f9eSspupyrev uint64_t Dst = Jump->Target; 34998dd2f9eSspupyrev if (Jump->Flow > 0 && !Visited[Dst]) { 35098dd2f9eSspupyrev Queue.push(Dst); 35198dd2f9eSspupyrev Visited[Dst] = true; 35298dd2f9eSspupyrev } 35398dd2f9eSspupyrev } 35498dd2f9eSspupyrev } 35598dd2f9eSspupyrev } 35698dd2f9eSspupyrev 35798dd2f9eSspupyrev /// Find the shortest path from the entry block to an exit block passing 35898dd2f9eSspupyrev /// through a given block. 35998dd2f9eSspupyrev std::vector<FlowJump *> findShortestPath(uint64_t BlockIdx) { 36098dd2f9eSspupyrev // A path from the entry block to BlockIdx 36198dd2f9eSspupyrev auto ForwardPath = findShortestPath(Func.Entry, BlockIdx); 36298dd2f9eSspupyrev // A path from BlockIdx to an exit block 36398dd2f9eSspupyrev auto BackwardPath = findShortestPath(BlockIdx, AnyExitBlock); 36498dd2f9eSspupyrev 36598dd2f9eSspupyrev // Concatenate the two paths 36698dd2f9eSspupyrev std::vector<FlowJump *> Result; 36798dd2f9eSspupyrev Result.insert(Result.end(), ForwardPath.begin(), ForwardPath.end()); 36898dd2f9eSspupyrev Result.insert(Result.end(), BackwardPath.begin(), BackwardPath.end()); 36998dd2f9eSspupyrev return Result; 37098dd2f9eSspupyrev } 37198dd2f9eSspupyrev 37298dd2f9eSspupyrev /// Apply the Dijkstra algorithm to find the shortest path from a given 37398dd2f9eSspupyrev /// Source to a given Target block. 37498dd2f9eSspupyrev /// If Target == -1, then the path ends at an exit block. 37598dd2f9eSspupyrev std::vector<FlowJump *> findShortestPath(uint64_t Source, uint64_t Target) { 37698dd2f9eSspupyrev // Quit early, if possible 37798dd2f9eSspupyrev if (Source == Target) 37898dd2f9eSspupyrev return std::vector<FlowJump *>(); 37998dd2f9eSspupyrev if (Func.Blocks[Source].isExit() && Target == AnyExitBlock) 38098dd2f9eSspupyrev return std::vector<FlowJump *>(); 38198dd2f9eSspupyrev 38298dd2f9eSspupyrev // Initialize data structures 38398dd2f9eSspupyrev auto Distance = std::vector<int64_t>(NumBlocks(), INF); 38498dd2f9eSspupyrev auto Parent = std::vector<FlowJump *>(NumBlocks(), nullptr); 38598dd2f9eSspupyrev Distance[Source] = 0; 38698dd2f9eSspupyrev std::set<std::pair<uint64_t, uint64_t>> Queue; 38798dd2f9eSspupyrev Queue.insert(std::make_pair(Distance[Source], Source)); 38898dd2f9eSspupyrev 38998dd2f9eSspupyrev // Run the Dijkstra algorithm 39098dd2f9eSspupyrev while (!Queue.empty()) { 39198dd2f9eSspupyrev uint64_t Src = Queue.begin()->second; 39298dd2f9eSspupyrev Queue.erase(Queue.begin()); 39398dd2f9eSspupyrev // If we found a solution, quit early 39498dd2f9eSspupyrev if (Src == Target || 39598dd2f9eSspupyrev (Func.Blocks[Src].isExit() && Target == AnyExitBlock)) 39698dd2f9eSspupyrev break; 39798dd2f9eSspupyrev 39898dd2f9eSspupyrev for (auto Jump : Func.Blocks[Src].SuccJumps) { 39998dd2f9eSspupyrev uint64_t Dst = Jump->Target; 40098dd2f9eSspupyrev int64_t JumpDist = jumpDistance(Jump); 40198dd2f9eSspupyrev if (Distance[Dst] > Distance[Src] + JumpDist) { 40298dd2f9eSspupyrev Queue.erase(std::make_pair(Distance[Dst], Dst)); 40398dd2f9eSspupyrev 40498dd2f9eSspupyrev Distance[Dst] = Distance[Src] + JumpDist; 40598dd2f9eSspupyrev Parent[Dst] = Jump; 40698dd2f9eSspupyrev 40798dd2f9eSspupyrev Queue.insert(std::make_pair(Distance[Dst], Dst)); 40898dd2f9eSspupyrev } 40998dd2f9eSspupyrev } 41098dd2f9eSspupyrev } 41198dd2f9eSspupyrev // If Target is not provided, find the closest exit block 41298dd2f9eSspupyrev if (Target == AnyExitBlock) { 41398dd2f9eSspupyrev for (uint64_t I = 0; I < NumBlocks(); I++) { 41498dd2f9eSspupyrev if (Func.Blocks[I].isExit() && Parent[I] != nullptr) { 41598dd2f9eSspupyrev if (Target == AnyExitBlock || Distance[Target] > Distance[I]) { 41698dd2f9eSspupyrev Target = I; 41798dd2f9eSspupyrev } 41898dd2f9eSspupyrev } 41998dd2f9eSspupyrev } 42098dd2f9eSspupyrev } 42198dd2f9eSspupyrev assert(Parent[Target] != nullptr && "a path does not exist"); 42298dd2f9eSspupyrev 42398dd2f9eSspupyrev // Extract the constructed path 42498dd2f9eSspupyrev std::vector<FlowJump *> Result; 42598dd2f9eSspupyrev uint64_t Now = Target; 42698dd2f9eSspupyrev while (Now != Source) { 42798dd2f9eSspupyrev assert(Now == Parent[Now]->Target && "incorrect parent jump"); 42898dd2f9eSspupyrev Result.push_back(Parent[Now]); 42998dd2f9eSspupyrev Now = Parent[Now]->Source; 43098dd2f9eSspupyrev } 43198dd2f9eSspupyrev // Reverse the path, since it is extracted from Target to Source 43298dd2f9eSspupyrev std::reverse(Result.begin(), Result.end()); 43398dd2f9eSspupyrev return Result; 43498dd2f9eSspupyrev } 43598dd2f9eSspupyrev 43698dd2f9eSspupyrev /// A distance of a path for a given jump. 43798dd2f9eSspupyrev /// In order to incite the path to use blocks/jumps with large positive flow, 43898dd2f9eSspupyrev /// and avoid changing branch probability of outgoing edges drastically, 43998dd2f9eSspupyrev /// set the distance as follows: 44098dd2f9eSspupyrev /// if Jump.Flow > 0, then distance = max(100 - Jump->Flow, 0) 44198dd2f9eSspupyrev /// if Block.Weight > 0, then distance = 1 44298dd2f9eSspupyrev /// otherwise distance >> 1 44398dd2f9eSspupyrev int64_t jumpDistance(FlowJump *Jump) const { 44498dd2f9eSspupyrev int64_t BaseDistance = 100; 44598dd2f9eSspupyrev if (Jump->IsUnlikely) 44698dd2f9eSspupyrev return MinCostMaxFlow::AuxCostUnlikely; 44798dd2f9eSspupyrev if (Jump->Flow > 0) 44898dd2f9eSspupyrev return std::max(BaseDistance - (int64_t)Jump->Flow, (int64_t)0); 44998dd2f9eSspupyrev if (Func.Blocks[Jump->Target].Weight > 0) 45098dd2f9eSspupyrev return BaseDistance; 45198dd2f9eSspupyrev return BaseDistance * (NumBlocks() + 1); 45298dd2f9eSspupyrev }; 45398dd2f9eSspupyrev 45498dd2f9eSspupyrev uint64_t NumBlocks() const { return Func.Blocks.size(); } 45598dd2f9eSspupyrev 45693a2c291Sspupyrev /// Rebalance unknown subgraphs so as each branch splits with probabilities 45793a2c291Sspupyrev /// UnknownFirstSuccProbability and 1 - UnknownFirstSuccProbability 45893a2c291Sspupyrev void rebalanceUnknownSubgraphs() { 459e7774f49SKazu Hirata static_assert( 460e7774f49SKazu Hirata UnknownFirstSuccProbability >= 0.0 && 461e7774f49SKazu Hirata UnknownFirstSuccProbability <= 1.0, 46293a2c291Sspupyrev "the share of the unknown successor should be between 0 and 1"); 46393a2c291Sspupyrev // Try to find unknown subgraphs from each non-unknown block 46493a2c291Sspupyrev for (uint64_t I = 0; I < Func.Blocks.size(); I++) { 46593a2c291Sspupyrev auto SrcBlock = &Func.Blocks[I]; 46693a2c291Sspupyrev // Do not attempt to find unknown successors from a unknown or a 46793a2c291Sspupyrev // zero-flow block 46893a2c291Sspupyrev if (SrcBlock->UnknownWeight || SrcBlock->Flow == 0) 46993a2c291Sspupyrev continue; 47093a2c291Sspupyrev 47193a2c291Sspupyrev std::vector<FlowBlock *> UnknownSuccs; 47293a2c291Sspupyrev FlowBlock *DstBlock = nullptr; 47393a2c291Sspupyrev // Find a unknown subgraphs starting at block SrcBlock 47493a2c291Sspupyrev if (!findUnknownSubgraph(SrcBlock, DstBlock, UnknownSuccs)) 47593a2c291Sspupyrev continue; 47693a2c291Sspupyrev // At the moment, we do not rebalance subgraphs containing cycles among 47793a2c291Sspupyrev // unknown blocks 47893a2c291Sspupyrev if (!isAcyclicSubgraph(SrcBlock, DstBlock, UnknownSuccs)) 47993a2c291Sspupyrev continue; 48093a2c291Sspupyrev 48193a2c291Sspupyrev // Rebalance the flow 48293a2c291Sspupyrev rebalanceUnknownSubgraph(SrcBlock, DstBlock, UnknownSuccs); 48393a2c291Sspupyrev } 48493a2c291Sspupyrev } 48593a2c291Sspupyrev 48693a2c291Sspupyrev /// Find a unknown subgraph starting at block SrcBlock. 48793a2c291Sspupyrev /// If the search is successful, the method sets DstBlock and UnknownSuccs. 48893a2c291Sspupyrev bool findUnknownSubgraph(FlowBlock *SrcBlock, FlowBlock *&DstBlock, 48993a2c291Sspupyrev std::vector<FlowBlock *> &UnknownSuccs) { 49093a2c291Sspupyrev // Run BFS from SrcBlock and make sure all paths are going through unknown 49193a2c291Sspupyrev // blocks and end at a non-unknown DstBlock 492*5f4ae564SJan Svoboda auto Visited = BitVector(NumBlocks(), false); 49393a2c291Sspupyrev std::queue<uint64_t> Queue; 49493a2c291Sspupyrev DstBlock = nullptr; 49593a2c291Sspupyrev 49693a2c291Sspupyrev Queue.push(SrcBlock->Index); 49793a2c291Sspupyrev Visited[SrcBlock->Index] = true; 49893a2c291Sspupyrev while (!Queue.empty()) { 49993a2c291Sspupyrev auto &Block = Func.Blocks[Queue.front()]; 50093a2c291Sspupyrev Queue.pop(); 50193a2c291Sspupyrev // Process blocks reachable from Block 50293a2c291Sspupyrev for (auto Jump : Block.SuccJumps) { 50393a2c291Sspupyrev uint64_t Dst = Jump->Target; 50493a2c291Sspupyrev if (Visited[Dst]) 50593a2c291Sspupyrev continue; 50693a2c291Sspupyrev Visited[Dst] = true; 50793a2c291Sspupyrev if (!Func.Blocks[Dst].UnknownWeight) { 50893a2c291Sspupyrev // If we see non-unique non-unknown block reachable from SrcBlock, 50993a2c291Sspupyrev // stop processing and skip rebalancing 51093a2c291Sspupyrev FlowBlock *CandidateDstBlock = &Func.Blocks[Dst]; 51193a2c291Sspupyrev if (DstBlock != nullptr && DstBlock != CandidateDstBlock) 51293a2c291Sspupyrev return false; 51393a2c291Sspupyrev DstBlock = CandidateDstBlock; 51493a2c291Sspupyrev } else { 51593a2c291Sspupyrev Queue.push(Dst); 51693a2c291Sspupyrev UnknownSuccs.push_back(&Func.Blocks[Dst]); 51793a2c291Sspupyrev } 51893a2c291Sspupyrev } 51993a2c291Sspupyrev } 52093a2c291Sspupyrev 52193a2c291Sspupyrev // If the list of unknown blocks is empty, we don't need rebalancing 52293a2c291Sspupyrev if (UnknownSuccs.empty()) 52393a2c291Sspupyrev return false; 52493a2c291Sspupyrev // If all reachable nodes from SrcBlock are unknown, skip rebalancing 52593a2c291Sspupyrev if (DstBlock == nullptr) 52693a2c291Sspupyrev return false; 52793a2c291Sspupyrev // If any of the unknown blocks is an exit block, skip rebalancing 52893a2c291Sspupyrev for (auto Block : UnknownSuccs) { 52993a2c291Sspupyrev if (Block->isExit()) 53093a2c291Sspupyrev return false; 53193a2c291Sspupyrev } 53293a2c291Sspupyrev 53393a2c291Sspupyrev return true; 53493a2c291Sspupyrev } 53593a2c291Sspupyrev 53693a2c291Sspupyrev /// Verify if the given unknown subgraph is acyclic, and if yes, reorder 53793a2c291Sspupyrev /// UnknownSuccs in the topological order (so that all jumps are "forward"). 53893a2c291Sspupyrev bool isAcyclicSubgraph(FlowBlock *SrcBlock, FlowBlock *DstBlock, 53993a2c291Sspupyrev std::vector<FlowBlock *> &UnknownSuccs) { 54093a2c291Sspupyrev // Extract local in-degrees in the considered subgraph 54193a2c291Sspupyrev auto LocalInDegree = std::vector<uint64_t>(NumBlocks(), 0); 54293a2c291Sspupyrev for (auto Jump : SrcBlock->SuccJumps) { 54393a2c291Sspupyrev LocalInDegree[Jump->Target]++; 54493a2c291Sspupyrev } 54593a2c291Sspupyrev for (uint64_t I = 0; I < UnknownSuccs.size(); I++) { 54693a2c291Sspupyrev for (auto Jump : UnknownSuccs[I]->SuccJumps) { 54793a2c291Sspupyrev LocalInDegree[Jump->Target]++; 54893a2c291Sspupyrev } 54993a2c291Sspupyrev } 55093a2c291Sspupyrev // A loop containing SrcBlock 55193a2c291Sspupyrev if (LocalInDegree[SrcBlock->Index] > 0) 55293a2c291Sspupyrev return false; 55393a2c291Sspupyrev 55493a2c291Sspupyrev std::vector<FlowBlock *> AcyclicOrder; 55593a2c291Sspupyrev std::queue<uint64_t> Queue; 55693a2c291Sspupyrev Queue.push(SrcBlock->Index); 55793a2c291Sspupyrev while (!Queue.empty()) { 55893a2c291Sspupyrev auto &Block = Func.Blocks[Queue.front()]; 55993a2c291Sspupyrev Queue.pop(); 56093a2c291Sspupyrev // Stop propagation once we reach DstBlock 56193a2c291Sspupyrev if (Block.Index == DstBlock->Index) 56293a2c291Sspupyrev break; 56393a2c291Sspupyrev 56493a2c291Sspupyrev AcyclicOrder.push_back(&Block); 56593a2c291Sspupyrev // Add to the queue all successors with zero local in-degree 56693a2c291Sspupyrev for (auto Jump : Block.SuccJumps) { 56793a2c291Sspupyrev uint64_t Dst = Jump->Target; 56893a2c291Sspupyrev LocalInDegree[Dst]--; 56993a2c291Sspupyrev if (LocalInDegree[Dst] == 0) { 57093a2c291Sspupyrev Queue.push(Dst); 57193a2c291Sspupyrev } 57293a2c291Sspupyrev } 57393a2c291Sspupyrev } 57493a2c291Sspupyrev 57593a2c291Sspupyrev // If there is a cycle in the subgraph, AcyclicOrder contains only a subset 57693a2c291Sspupyrev // of all blocks 57793a2c291Sspupyrev if (UnknownSuccs.size() + 1 != AcyclicOrder.size()) 57893a2c291Sspupyrev return false; 57993a2c291Sspupyrev UnknownSuccs = AcyclicOrder; 58093a2c291Sspupyrev return true; 58193a2c291Sspupyrev } 58293a2c291Sspupyrev 58393a2c291Sspupyrev /// Rebalance a given subgraph. 58493a2c291Sspupyrev void rebalanceUnknownSubgraph(FlowBlock *SrcBlock, FlowBlock *DstBlock, 58593a2c291Sspupyrev std::vector<FlowBlock *> &UnknownSuccs) { 58693a2c291Sspupyrev assert(SrcBlock->Flow > 0 && "zero-flow block in unknown subgraph"); 58793a2c291Sspupyrev assert(UnknownSuccs.front() == SrcBlock && "incorrect order of unknowns"); 58893a2c291Sspupyrev 58993a2c291Sspupyrev for (auto Block : UnknownSuccs) { 59093a2c291Sspupyrev // Block's flow is the sum of incoming flows 59193a2c291Sspupyrev uint64_t TotalFlow = 0; 59293a2c291Sspupyrev if (Block == SrcBlock) { 59393a2c291Sspupyrev TotalFlow = Block->Flow; 59493a2c291Sspupyrev } else { 59593a2c291Sspupyrev for (auto Jump : Block->PredJumps) { 59693a2c291Sspupyrev TotalFlow += Jump->Flow; 59793a2c291Sspupyrev } 59893a2c291Sspupyrev Block->Flow = TotalFlow; 59993a2c291Sspupyrev } 60093a2c291Sspupyrev 60193a2c291Sspupyrev // Process all successor jumps and update corresponding flow values 60293a2c291Sspupyrev for (uint64_t I = 0; I < Block->SuccJumps.size(); I++) { 60393a2c291Sspupyrev auto Jump = Block->SuccJumps[I]; 60493a2c291Sspupyrev if (I + 1 == Block->SuccJumps.size()) { 60593a2c291Sspupyrev Jump->Flow = TotalFlow; 60693a2c291Sspupyrev continue; 60793a2c291Sspupyrev } 60893a2c291Sspupyrev uint64_t Flow = uint64_t(TotalFlow * UnknownFirstSuccProbability); 60993a2c291Sspupyrev Jump->Flow = Flow; 61093a2c291Sspupyrev TotalFlow -= Flow; 61193a2c291Sspupyrev } 61293a2c291Sspupyrev } 61393a2c291Sspupyrev } 61493a2c291Sspupyrev 61598dd2f9eSspupyrev /// A constant indicating an arbitrary exit block of a function. 61698dd2f9eSspupyrev static constexpr uint64_t AnyExitBlock = uint64_t(-1); 61798dd2f9eSspupyrev 61898dd2f9eSspupyrev /// The function. 61998dd2f9eSspupyrev FlowFunction &Func; 62098dd2f9eSspupyrev }; 62198dd2f9eSspupyrev 6227cc2493dSspupyrev /// Initializing flow network for a given function. 6237cc2493dSspupyrev /// 6247cc2493dSspupyrev /// Every block is split into three nodes that are responsible for (i) an 6257cc2493dSspupyrev /// incoming flow, (ii) an outgoing flow, and (iii) penalizing an increase or 6267cc2493dSspupyrev /// reduction of the block weight. 6277cc2493dSspupyrev void initializeNetwork(MinCostMaxFlow &Network, FlowFunction &Func) { 6287cc2493dSspupyrev uint64_t NumBlocks = Func.Blocks.size(); 6297cc2493dSspupyrev assert(NumBlocks > 1 && "Too few blocks in a function"); 6307cc2493dSspupyrev LLVM_DEBUG(dbgs() << "Initializing profi for " << NumBlocks << " blocks\n"); 6317cc2493dSspupyrev 6327cc2493dSspupyrev // Pre-process data: make sure the entry weight is at least 1 6337cc2493dSspupyrev if (Func.Blocks[Func.Entry].Weight == 0) { 6347cc2493dSspupyrev Func.Blocks[Func.Entry].Weight = 1; 6357cc2493dSspupyrev } 6367cc2493dSspupyrev // Introducing dummy source/sink pairs to allow flow circulation. 6377cc2493dSspupyrev // The nodes corresponding to blocks of Func have indicies in the range 6387cc2493dSspupyrev // [0..3 * NumBlocks); the dummy nodes are indexed by the next four values. 6397cc2493dSspupyrev uint64_t S = 3 * NumBlocks; 6407cc2493dSspupyrev uint64_t T = S + 1; 6417cc2493dSspupyrev uint64_t S1 = S + 2; 6427cc2493dSspupyrev uint64_t T1 = S + 3; 6437cc2493dSspupyrev 6447cc2493dSspupyrev Network.initialize(3 * NumBlocks + 4, S1, T1); 6457cc2493dSspupyrev 6467cc2493dSspupyrev // Create three nodes for every block of the function 6477cc2493dSspupyrev for (uint64_t B = 0; B < NumBlocks; B++) { 6487cc2493dSspupyrev auto &Block = Func.Blocks[B]; 6497cc2493dSspupyrev assert((!Block.UnknownWeight || Block.Weight == 0 || Block.isEntry()) && 6507cc2493dSspupyrev "non-zero weight of a block w/o weight except for an entry"); 6517cc2493dSspupyrev 6527cc2493dSspupyrev // Split every block into two nodes 6537cc2493dSspupyrev uint64_t Bin = 3 * B; 6547cc2493dSspupyrev uint64_t Bout = 3 * B + 1; 6557cc2493dSspupyrev uint64_t Baux = 3 * B + 2; 6567cc2493dSspupyrev if (Block.Weight > 0) { 6577cc2493dSspupyrev Network.addEdge(S1, Bout, Block.Weight, 0); 6587cc2493dSspupyrev Network.addEdge(Bin, T1, Block.Weight, 0); 6597cc2493dSspupyrev } 6607cc2493dSspupyrev 6617cc2493dSspupyrev // Edges from S and to T 6627cc2493dSspupyrev assert((!Block.isEntry() || !Block.isExit()) && 6637cc2493dSspupyrev "a block cannot be an entry and an exit"); 6647cc2493dSspupyrev if (Block.isEntry()) { 6657cc2493dSspupyrev Network.addEdge(S, Bin, 0); 6667cc2493dSspupyrev } else if (Block.isExit()) { 6677cc2493dSspupyrev Network.addEdge(Bout, T, 0); 6687cc2493dSspupyrev } 6697cc2493dSspupyrev 6707cc2493dSspupyrev // An auxiliary node to allow increase/reduction of block counts: 6717cc2493dSspupyrev // We assume that decreasing block counts is more expensive than increasing, 6727cc2493dSspupyrev // and thus, setting separate costs here. In the future we may want to tune 6737cc2493dSspupyrev // the relative costs so as to maximize the quality of generated profiles. 6747cc2493dSspupyrev int64_t AuxCostInc = MinCostMaxFlow::AuxCostInc; 6757cc2493dSspupyrev int64_t AuxCostDec = MinCostMaxFlow::AuxCostDec; 6767cc2493dSspupyrev if (Block.UnknownWeight) { 6777cc2493dSspupyrev // Do not penalize changing weights of blocks w/o known profile count 6787cc2493dSspupyrev AuxCostInc = 0; 6797cc2493dSspupyrev AuxCostDec = 0; 6807cc2493dSspupyrev } else { 6817cc2493dSspupyrev // Increasing the count for "cold" blocks with zero initial count is more 6827cc2493dSspupyrev // expensive than for "hot" ones 6837cc2493dSspupyrev if (Block.Weight == 0) { 6847cc2493dSspupyrev AuxCostInc = MinCostMaxFlow::AuxCostIncZero; 6857cc2493dSspupyrev } 6867cc2493dSspupyrev // Modifying the count of the entry block is expensive 6877cc2493dSspupyrev if (Block.isEntry()) { 6887cc2493dSspupyrev AuxCostInc = MinCostMaxFlow::AuxCostIncEntry; 6897cc2493dSspupyrev AuxCostDec = MinCostMaxFlow::AuxCostDecEntry; 6907cc2493dSspupyrev } 6917cc2493dSspupyrev } 6927cc2493dSspupyrev // For blocks with self-edges, do not penalize a reduction of the count, 6937cc2493dSspupyrev // as all of the increase can be attributed to the self-edge 6947cc2493dSspupyrev if (Block.HasSelfEdge) { 6957cc2493dSspupyrev AuxCostDec = 0; 6967cc2493dSspupyrev } 6977cc2493dSspupyrev 6987cc2493dSspupyrev Network.addEdge(Bin, Baux, AuxCostInc); 6997cc2493dSspupyrev Network.addEdge(Baux, Bout, AuxCostInc); 7007cc2493dSspupyrev if (Block.Weight > 0) { 7017cc2493dSspupyrev Network.addEdge(Bout, Baux, AuxCostDec); 7027cc2493dSspupyrev Network.addEdge(Baux, Bin, AuxCostDec); 7037cc2493dSspupyrev } 7047cc2493dSspupyrev } 7057cc2493dSspupyrev 7067cc2493dSspupyrev // Creating edges for every jump 7077cc2493dSspupyrev for (auto &Jump : Func.Jumps) { 7087cc2493dSspupyrev uint64_t Src = Jump.Source; 7097cc2493dSspupyrev uint64_t Dst = Jump.Target; 7107cc2493dSspupyrev if (Src != Dst) { 7117cc2493dSspupyrev uint64_t SrcOut = 3 * Src + 1; 7127cc2493dSspupyrev uint64_t DstIn = 3 * Dst; 7137cc2493dSspupyrev uint64_t Cost = Jump.IsUnlikely ? MinCostMaxFlow::AuxCostUnlikely : 0; 7147cc2493dSspupyrev Network.addEdge(SrcOut, DstIn, Cost); 7157cc2493dSspupyrev } 7167cc2493dSspupyrev } 7177cc2493dSspupyrev 7187cc2493dSspupyrev // Make sure we have a valid flow circulation 7197cc2493dSspupyrev Network.addEdge(T, S, 0); 7207cc2493dSspupyrev } 7217cc2493dSspupyrev 7227cc2493dSspupyrev /// Extract resulting block and edge counts from the flow network. 7237cc2493dSspupyrev void extractWeights(MinCostMaxFlow &Network, FlowFunction &Func) { 7247cc2493dSspupyrev uint64_t NumBlocks = Func.Blocks.size(); 7257cc2493dSspupyrev 7267cc2493dSspupyrev // Extract resulting block counts 7277cc2493dSspupyrev for (uint64_t Src = 0; Src < NumBlocks; Src++) { 7287cc2493dSspupyrev auto &Block = Func.Blocks[Src]; 7297cc2493dSspupyrev uint64_t SrcOut = 3 * Src + 1; 7307cc2493dSspupyrev int64_t Flow = 0; 7317cc2493dSspupyrev for (auto &Adj : Network.getFlow(SrcOut)) { 7327cc2493dSspupyrev uint64_t DstIn = Adj.first; 7337cc2493dSspupyrev int64_t DstFlow = Adj.second; 7347cc2493dSspupyrev bool IsAuxNode = (DstIn < 3 * NumBlocks && DstIn % 3 == 2); 7357cc2493dSspupyrev if (!IsAuxNode || Block.HasSelfEdge) { 7367cc2493dSspupyrev Flow += DstFlow; 7377cc2493dSspupyrev } 7387cc2493dSspupyrev } 7397cc2493dSspupyrev Block.Flow = Flow; 7407cc2493dSspupyrev assert(Flow >= 0 && "negative block flow"); 7417cc2493dSspupyrev } 7427cc2493dSspupyrev 7437cc2493dSspupyrev // Extract resulting jump counts 7447cc2493dSspupyrev for (auto &Jump : Func.Jumps) { 7457cc2493dSspupyrev uint64_t Src = Jump.Source; 7467cc2493dSspupyrev uint64_t Dst = Jump.Target; 7477cc2493dSspupyrev int64_t Flow = 0; 7487cc2493dSspupyrev if (Src != Dst) { 7497cc2493dSspupyrev uint64_t SrcOut = 3 * Src + 1; 7507cc2493dSspupyrev uint64_t DstIn = 3 * Dst; 7517cc2493dSspupyrev Flow = Network.getFlow(SrcOut, DstIn); 7527cc2493dSspupyrev } else { 7537cc2493dSspupyrev uint64_t SrcOut = 3 * Src + 1; 7547cc2493dSspupyrev uint64_t SrcAux = 3 * Src + 2; 7557cc2493dSspupyrev int64_t AuxFlow = Network.getFlow(SrcOut, SrcAux); 7567cc2493dSspupyrev if (AuxFlow > 0) 7577cc2493dSspupyrev Flow = AuxFlow; 7587cc2493dSspupyrev } 7597cc2493dSspupyrev Jump.Flow = Flow; 7607cc2493dSspupyrev assert(Flow >= 0 && "negative jump flow"); 7617cc2493dSspupyrev } 7627cc2493dSspupyrev } 7637cc2493dSspupyrev 7647cc2493dSspupyrev #ifndef NDEBUG 7657cc2493dSspupyrev /// Verify that the computed flow values satisfy flow conservation rules 7667cc2493dSspupyrev void verifyWeights(const FlowFunction &Func) { 7677cc2493dSspupyrev const uint64_t NumBlocks = Func.Blocks.size(); 7687cc2493dSspupyrev auto InFlow = std::vector<uint64_t>(NumBlocks, 0); 7697cc2493dSspupyrev auto OutFlow = std::vector<uint64_t>(NumBlocks, 0); 7707cc2493dSspupyrev for (auto &Jump : Func.Jumps) { 7717cc2493dSspupyrev InFlow[Jump.Target] += Jump.Flow; 7727cc2493dSspupyrev OutFlow[Jump.Source] += Jump.Flow; 7737cc2493dSspupyrev } 7747cc2493dSspupyrev 7757cc2493dSspupyrev uint64_t TotalInFlow = 0; 7767cc2493dSspupyrev uint64_t TotalOutFlow = 0; 7777cc2493dSspupyrev for (uint64_t I = 0; I < NumBlocks; I++) { 7787cc2493dSspupyrev auto &Block = Func.Blocks[I]; 7797cc2493dSspupyrev if (Block.isEntry()) { 7807cc2493dSspupyrev TotalInFlow += Block.Flow; 7817cc2493dSspupyrev assert(Block.Flow == OutFlow[I] && "incorrectly computed control flow"); 7827cc2493dSspupyrev } else if (Block.isExit()) { 7837cc2493dSspupyrev TotalOutFlow += Block.Flow; 7847cc2493dSspupyrev assert(Block.Flow == InFlow[I] && "incorrectly computed control flow"); 7857cc2493dSspupyrev } else { 7867cc2493dSspupyrev assert(Block.Flow == OutFlow[I] && "incorrectly computed control flow"); 7877cc2493dSspupyrev assert(Block.Flow == InFlow[I] && "incorrectly computed control flow"); 7887cc2493dSspupyrev } 7897cc2493dSspupyrev } 7907cc2493dSspupyrev assert(TotalInFlow == TotalOutFlow && "incorrectly computed control flow"); 79198dd2f9eSspupyrev 79298dd2f9eSspupyrev // Verify that there are no isolated flow components 79398dd2f9eSspupyrev // One could modify FlowFunction to hold edges indexed by the sources, which 79498dd2f9eSspupyrev // will avoid a creation of the object 79598dd2f9eSspupyrev auto PositiveFlowEdges = std::vector<std::vector<uint64_t>>(NumBlocks); 79698dd2f9eSspupyrev for (auto &Jump : Func.Jumps) { 79798dd2f9eSspupyrev if (Jump.Flow > 0) { 79898dd2f9eSspupyrev PositiveFlowEdges[Jump.Source].push_back(Jump.Target); 79998dd2f9eSspupyrev } 80098dd2f9eSspupyrev } 80198dd2f9eSspupyrev 80293a2c291Sspupyrev // Run BFS from the source along edges with positive flow 80398dd2f9eSspupyrev std::queue<uint64_t> Queue; 804*5f4ae564SJan Svoboda auto Visited = BitVector(NumBlocks, false); 80598dd2f9eSspupyrev Queue.push(Func.Entry); 80698dd2f9eSspupyrev Visited[Func.Entry] = true; 80798dd2f9eSspupyrev while (!Queue.empty()) { 80898dd2f9eSspupyrev uint64_t Src = Queue.front(); 80998dd2f9eSspupyrev Queue.pop(); 81098dd2f9eSspupyrev for (uint64_t Dst : PositiveFlowEdges[Src]) { 81198dd2f9eSspupyrev if (!Visited[Dst]) { 81298dd2f9eSspupyrev Queue.push(Dst); 81398dd2f9eSspupyrev Visited[Dst] = true; 81498dd2f9eSspupyrev } 81598dd2f9eSspupyrev } 81698dd2f9eSspupyrev } 81798dd2f9eSspupyrev 81898dd2f9eSspupyrev // Verify that every block that has a positive flow is reached from the source 81998dd2f9eSspupyrev // along edges with a positive flow 82098dd2f9eSspupyrev for (uint64_t I = 0; I < NumBlocks; I++) { 82198dd2f9eSspupyrev auto &Block = Func.Blocks[I]; 82298dd2f9eSspupyrev assert((Visited[I] || Block.Flow == 0) && "an isolated flow component"); 82398dd2f9eSspupyrev } 8247cc2493dSspupyrev } 8257cc2493dSspupyrev #endif 8267cc2493dSspupyrev 8277cc2493dSspupyrev } // end of anonymous namespace 8287cc2493dSspupyrev 8297cc2493dSspupyrev /// Apply the profile inference algorithm for a given flow function 8307cc2493dSspupyrev void llvm::applyFlowInference(FlowFunction &Func) { 8317cc2493dSspupyrev // Create and apply an inference network model 8327cc2493dSspupyrev auto InferenceNetwork = MinCostMaxFlow(); 8337cc2493dSspupyrev initializeNetwork(InferenceNetwork, Func); 8347cc2493dSspupyrev InferenceNetwork.run(); 8357cc2493dSspupyrev 8367cc2493dSspupyrev // Extract flow values for every block and every edge 8377cc2493dSspupyrev extractWeights(InferenceNetwork, Func); 8387cc2493dSspupyrev 83998dd2f9eSspupyrev // Post-processing adjustments to the flow 84098dd2f9eSspupyrev auto Adjuster = FlowAdjuster(Func); 84198dd2f9eSspupyrev Adjuster.run(); 84298dd2f9eSspupyrev 8437cc2493dSspupyrev #ifndef NDEBUG 8447cc2493dSspupyrev // Verify the result 8457cc2493dSspupyrev verifyWeights(Func); 8467cc2493dSspupyrev #endif 8477cc2493dSspupyrev } 848