1 //===-- CFGMST.h - Minimum Spanning Tree for CFG -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Union-find algorithm to compute Minimum Spanning Tree
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include "llvm/Support/BranchProbability.h"
19 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
20 #include "llvm/Analysis/CFG.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/Analysis/BlockFrequencyInfo.h"
29 #define DEBUG_TYPE "cfgmst"
31 template <class Edge, class BBInfo> class CFGMST {
35 // Store all the edges in CFG. It may contain some stale edges
36 // when Removed is set.
37 std::vector<std::unique_ptr<Edge>> AllEdges;
39 // This map records the auxiliary information for each BB.
40 DenseMap<const BasicBlock *, std::unique_ptr<BBInfo>> BBInfos;
42 // Find the root group of the G and compress the path from G to the root.
43 BBInfo *findAndCompressGroup(BBInfo *G) {
45 G->Group = findAndCompressGroup(static_cast<BBInfo *>(G->Group));
46 return static_cast<BBInfo *>(G->Group);
49 // Union BB1 and BB2 into the same group and return true.
50 // Returns false if BB1 and BB2 are already in the same group.
51 bool unionGroups(const BasicBlock *BB1, const BasicBlock *BB2) {
52 BBInfo *BB1G = findAndCompressGroup(&getBBInfo(BB1));
53 BBInfo *BB2G = findAndCompressGroup(&getBBInfo(BB2));
58 // Make the smaller rank tree a direct child or the root of high rank tree.
59 if (BB1G->Rank < BB2G->Rank)
63 // If the ranks are the same, increment root of one tree by one.
64 if (BB1G->Rank == BB2G->Rank)
70 // Give BB, return the auxiliary information.
71 BBInfo &getBBInfo(const BasicBlock *BB) const {
72 auto It = BBInfos.find(BB);
73 assert(It->second.get() != nullptr);
74 return *It->second.get();
77 // Traverse the CFG using a stack. Find all the edges and assign the weight.
78 // Edges with large weight will be put into MST first so they are less likely
79 // to be instrumented.
81 DEBUG(dbgs() << "Build Edge on " << F.getName() << "\n");
83 const BasicBlock *BB = &(F.getEntryBlock());
84 // Add a fake edge to the entry.
85 addEdge(nullptr, BB, BFI->getEntryFreq());
87 // Special handling for single BB functions.
89 addEdge(BB, nullptr, BFI->getEntryFreq());
93 static const uint32_t CriticalEdgeMultiplier = 1000;
95 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
96 TerminatorInst *TI = BB->getTerminator();
97 uint64_t BBWeight = BFI->getBlockFreq(&*BB).getFrequency();
99 if (int successors = TI->getNumSuccessors()) {
100 for (uint32_t i = 0; i != successors; ++i) {
101 BasicBlock *TargetBB = TI->getSuccessor(i);
102 bool Critical = isCriticalEdge(TI, i);
103 uint64_t scaleFactor = BBWeight;
105 if (scaleFactor < UINT64_MAX / CriticalEdgeMultiplier)
106 scaleFactor *= CriticalEdgeMultiplier;
108 scaleFactor = UINT64_MAX;
110 Weight = BPI->getEdgeProbability(&*BB, TargetBB).scale(scaleFactor);
111 addEdge(&*BB, TargetBB, Weight).IsCritical = Critical;
112 DEBUG(dbgs() << " Edge: from " << BB->getName() << " to "
113 << TargetBB->getName() << " w=" << Weight << "\n");
116 addEdge(&*BB, nullptr, BBWeight);
117 DEBUG(dbgs() << " Edge: from " << BB->getName() << " to exit"
118 << " w = " << BBWeight << "\n");
123 // Sort CFG edges based on its weight.
124 void sortEdgesByWeight() {
126 AllEdges.begin(), AllEdges.end(),
127 [](const std::unique_ptr<Edge> &lhs, const std::unique_ptr<Edge> &rhs) {
128 return lhs->Weight > rhs->Weight;
132 // Traverse all the edges and compute the Minimum Weight Spanning Tree
133 // using union-find algorithm.
134 void computeMinimumSpanningTree() {
135 // First, put all the critical edge with landing-pad as the Dest to MST.
136 // This works around the insufficient support of critical edges split
137 // when destination BB is a landing pad.
138 for (auto &Ei : AllEdges) {
141 if (Ei->IsCritical) {
142 if (Ei->DestBB && Ei->DestBB->isLandingPad()) {
143 if (unionGroups(Ei->SrcBB, Ei->DestBB))
149 for (auto &Ei : AllEdges) {
152 if (unionGroups(Ei->SrcBB, Ei->DestBB))
157 // Dump the Debug information about the instrumentation.
158 void dumpEdges(raw_ostream &OS, const StringRef Message = StringRef()) const {
159 if (!Message.empty())
160 OS << Message << "\n";
161 OS << " Number of Basic Blocks: " << BBInfos.size() << "\n";
162 for (auto &BI : BBInfos) {
163 const BasicBlock *BB = BI.first;
164 OS << " BB: " << (BB == nullptr ? "FakeNode" : BB->getName()) << " "
165 << BI.second->infoString() << "\n";
168 OS << " Number of Edges: " << AllEdges.size()
169 << " (*: Instrument, C: CriticalEdge, -: Removed)\n";
171 for (auto &EI : AllEdges) {
172 OS << " Edge " << Count++ << ": " << getBBInfo(EI->SrcBB).Index << "-->"
173 << getBBInfo(EI->DestBB).Index << EI->infoString() << "\n";
177 // Add an edge to AllEdges with weight W.
178 Edge &addEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W) {
179 uint32_t Index = BBInfos.size();
180 auto Iter = BBInfos.end();
182 std::tie(Iter, Inserted) = BBInfos.insert(std::make_pair(Src, nullptr));
184 // Newly inserted, update the real info.
185 Iter->second = std::move(llvm::make_unique<BBInfo>(Index));
188 std::tie(Iter, Inserted) = BBInfos.insert(std::make_pair(Dest, nullptr));
190 // Newly inserted, update the real info.
191 Iter->second = std::move(llvm::make_unique<BBInfo>(Index));
192 AllEdges.emplace_back(new Edge(Src, Dest, W));
193 return *AllEdges.back();
196 BranchProbabilityInfo *BPI;
197 BlockFrequencyInfo *BFI;
200 CFGMST(Function &Func, BranchProbabilityInfo *BPI_ = nullptr,
201 BlockFrequencyInfo *BFI_ = nullptr)
202 : F(Func), BPI(BPI_), BFI(BFI_) {
205 computeMinimumSpanningTree();
209 #undef DEBUG_TYPE // "cfgmst"
210 } // end namespace llvm