1 //===- bolt/Passes/ReorderAlgorithm.cpp - Basic block reordering ----------===//
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 classes used by several basic block reordering
10 // algorithms.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "bolt/Passes/ReorderAlgorithm.h"
15 #include "bolt/Core/BinaryBasicBlock.h"
16 #include "bolt/Core/BinaryFunction.h"
17 #include "llvm/Support/CommandLine.h"
18 #include <queue>
19 #include <random>
20 #include <stack>
21
22 #undef DEBUG_TYPE
23 #define DEBUG_TYPE "bolt"
24
25 using namespace llvm;
26 using namespace bolt;
27
28 namespace opts {
29
30 extern cl::OptionCategory BoltOptCategory;
31 extern cl::opt<bool> NoThreads;
32
33 static cl::opt<unsigned> ColdThreshold(
34 "cold-threshold",
35 cl::desc("tenths of percents of main entry frequency to use as a "
36 "threshold when evaluating whether a basic block is cold "
37 "(0 means it is only considered cold if the block has zero "
38 "samples). Default: 0 "),
39 cl::init(0), cl::ZeroOrMore, cl::Hidden, cl::cat(BoltOptCategory));
40
41 static cl::opt<bool> PrintClusters("print-clusters", cl::desc("print clusters"),
42 cl::Hidden, cl::cat(BoltOptCategory));
43
44 cl::opt<uint32_t> RandomSeed("bolt-seed", cl::desc("seed for randomization"),
45 cl::init(42), cl::Hidden,
46 cl::cat(BoltOptCategory));
47
48 } // namespace opts
49
50 namespace {
51
hashCombine(size_t & Seed,const T & Val)52 template <class T> inline void hashCombine(size_t &Seed, const T &Val) {
53 std::hash<T> Hasher;
54 Seed ^= Hasher(Val) + 0x9e3779b9 + (Seed << 6) + (Seed >> 2);
55 }
56
57 template <typename A, typename B> struct HashPair {
operator ()__anon4595c24e0111::HashPair58 size_t operator()(const std::pair<A, B> &Val) const {
59 std::hash<A> Hasher;
60 size_t Seed = Hasher(Val.first);
61 hashCombine(Seed, Val.second);
62 return Seed;
63 }
64 };
65
66 } // namespace
67
computeClusterAverageFrequency(const BinaryContext & BC)68 void ClusterAlgorithm::computeClusterAverageFrequency(const BinaryContext &BC) {
69 // Create a separate MCCodeEmitter to allow lock-free execution
70 BinaryContext::IndependentCodeEmitter Emitter;
71 if (!opts::NoThreads)
72 Emitter = BC.createIndependentMCCodeEmitter();
73
74 AvgFreq.resize(Clusters.size(), 0.0);
75 for (uint32_t I = 0, E = Clusters.size(); I < E; ++I) {
76 double Freq = 0.0;
77 uint64_t ClusterSize = 0;
78 for (BinaryBasicBlock *BB : Clusters[I]) {
79 if (BB->getNumNonPseudos() > 0) {
80 Freq += BB->getExecutionCount();
81 // Estimate the size of a block in bytes at run time
82 // NOTE: This might be inaccurate
83 ClusterSize += BB->estimateSize(Emitter.MCE.get());
84 }
85 }
86 AvgFreq[I] = ClusterSize == 0 ? 0 : Freq / ClusterSize;
87 }
88 }
89
printClusters() const90 void ClusterAlgorithm::printClusters() const {
91 for (uint32_t I = 0, E = Clusters.size(); I < E; ++I) {
92 errs() << "Cluster number " << I;
93 if (AvgFreq.size() == Clusters.size())
94 errs() << " (frequency: " << AvgFreq[I] << ")";
95 errs() << " : ";
96 const char *Sep = "";
97 for (BinaryBasicBlock *BB : Clusters[I]) {
98 errs() << Sep << BB->getName();
99 Sep = ", ";
100 }
101 errs() << "\n";
102 }
103 }
104
reset()105 void ClusterAlgorithm::reset() {
106 Clusters.clear();
107 ClusterEdges.clear();
108 AvgFreq.clear();
109 }
110
print(raw_ostream & OS) const111 void GreedyClusterAlgorithm::EdgeTy::print(raw_ostream &OS) const {
112 OS << Src->getName() << " -> " << Dst->getName() << ", count: " << Count;
113 }
114
operator ()(const EdgeTy & E) const115 size_t GreedyClusterAlgorithm::EdgeHash::operator()(const EdgeTy &E) const {
116 HashPair<const BinaryBasicBlock *, const BinaryBasicBlock *> Hasher;
117 return Hasher(std::make_pair(E.Src, E.Dst));
118 }
119
operator ()(const EdgeTy & A,const EdgeTy & B) const120 bool GreedyClusterAlgorithm::EdgeEqual::operator()(const EdgeTy &A,
121 const EdgeTy &B) const {
122 return A.Src == B.Src && A.Dst == B.Dst;
123 }
124
clusterBasicBlocks(const BinaryFunction & BF,bool ComputeEdges)125 void GreedyClusterAlgorithm::clusterBasicBlocks(const BinaryFunction &BF,
126 bool ComputeEdges) {
127 reset();
128
129 // Greedy heuristic implementation for the TSP, applied to BB layout. Try to
130 // maximize weight during a path traversing all BBs. In this way, we will
131 // convert the hottest branches into fall-throughs.
132
133 // This is the queue of edges from which we will pop edges and use them to
134 // cluster basic blocks in a greedy fashion.
135 std::vector<EdgeTy> Queue;
136
137 // Initialize inter-cluster weights.
138 if (ComputeEdges)
139 ClusterEdges.resize(BF.getLayout().block_size());
140
141 // Initialize clusters and edge queue.
142 for (BinaryBasicBlock *BB : BF.getLayout().blocks()) {
143 // Create a cluster for this BB.
144 uint32_t I = Clusters.size();
145 Clusters.emplace_back();
146 std::vector<BinaryBasicBlock *> &Cluster = Clusters.back();
147 Cluster.push_back(BB);
148 BBToClusterMap[BB] = I;
149 // Populate priority queue with edges.
150 auto BI = BB->branch_info_begin();
151 for (BinaryBasicBlock *&I : BB->successors()) {
152 assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
153 "attempted reordering blocks of function with no profile data");
154 Queue.emplace_back(EdgeTy(BB, I, BI->Count));
155 ++BI;
156 }
157 }
158 // Sort and adjust the edge queue.
159 initQueue(Queue, BF);
160
161 // Grow clusters in a greedy fashion.
162 while (!Queue.empty()) {
163 EdgeTy E = Queue.back();
164 Queue.pop_back();
165
166 const BinaryBasicBlock *SrcBB = E.Src;
167 const BinaryBasicBlock *DstBB = E.Dst;
168
169 LLVM_DEBUG(dbgs() << "Popped edge "; E.print(dbgs()); dbgs() << "\n");
170
171 // Case 1: BBSrc and BBDst are the same. Ignore this edge
172 if (SrcBB == DstBB || DstBB == *BF.getLayout().block_begin()) {
173 LLVM_DEBUG(dbgs() << "\tIgnored (same src, dst)\n");
174 continue;
175 }
176
177 int I = BBToClusterMap[SrcBB];
178 int J = BBToClusterMap[DstBB];
179
180 // Case 2: If they are already allocated at the same cluster, just increase
181 // the weight of this cluster
182 if (I == J) {
183 if (ComputeEdges)
184 ClusterEdges[I][I] += E.Count;
185 LLVM_DEBUG(dbgs() << "\tIgnored (src, dst belong to the same cluster)\n");
186 continue;
187 }
188
189 std::vector<BinaryBasicBlock *> &ClusterA = Clusters[I];
190 std::vector<BinaryBasicBlock *> &ClusterB = Clusters[J];
191 if (areClustersCompatible(ClusterA, ClusterB, E)) {
192 // Case 3: SrcBB is at the end of a cluster and DstBB is at the start,
193 // allowing us to merge two clusters.
194 for (BinaryBasicBlock *BB : ClusterB)
195 BBToClusterMap[BB] = I;
196 ClusterA.insert(ClusterA.end(), ClusterB.begin(), ClusterB.end());
197 ClusterB.clear();
198 if (ComputeEdges) {
199 // Increase the intra-cluster edge count of cluster A with the count of
200 // this edge as well as with the total count of previously visited edges
201 // from cluster B cluster A.
202 ClusterEdges[I][I] += E.Count;
203 ClusterEdges[I][I] += ClusterEdges[J][I];
204 // Iterate through all inter-cluster edges and transfer edges targeting
205 // cluster B to cluster A.
206 for (uint32_t K = 0, E = ClusterEdges.size(); K != E; ++K)
207 ClusterEdges[K][I] += ClusterEdges[K][J];
208 }
209 // Adjust the weights of the remaining edges and re-sort the queue.
210 adjustQueue(Queue, BF);
211 LLVM_DEBUG(dbgs() << "\tMerged clusters of src, dst\n");
212 } else {
213 // Case 4: Both SrcBB and DstBB are allocated in positions we cannot
214 // merge them. Add the count of this edge to the inter-cluster edge count
215 // between clusters A and B to help us decide ordering between these
216 // clusters.
217 if (ComputeEdges)
218 ClusterEdges[I][J] += E.Count;
219 LLVM_DEBUG(
220 dbgs() << "\tIgnored (src, dst belong to incompatible clusters)\n");
221 }
222 }
223 }
224
reset()225 void GreedyClusterAlgorithm::reset() {
226 ClusterAlgorithm::reset();
227 BBToClusterMap.clear();
228 }
229
initQueue(std::vector<EdgeTy> & Queue,const BinaryFunction & BF)230 void PHGreedyClusterAlgorithm::initQueue(std::vector<EdgeTy> &Queue,
231 const BinaryFunction &BF) {
232 // Define a comparison function to establish SWO between edges.
233 auto Comp = [&BF](const EdgeTy &A, const EdgeTy &B) {
234 // With equal weights, prioritize branches with lower index
235 // source/destination. This helps to keep original block order for blocks
236 // when optimal order cannot be deducted from a profile.
237 if (A.Count == B.Count) {
238 const signed SrcOrder = BF.getOriginalLayoutRelativeOrder(A.Src, B.Src);
239 return (SrcOrder != 0)
240 ? SrcOrder > 0
241 : BF.getOriginalLayoutRelativeOrder(A.Dst, B.Dst) > 0;
242 }
243 return A.Count < B.Count;
244 };
245
246 // Sort edges in increasing profile count order.
247 llvm::sort(Queue, Comp);
248 }
249
adjustQueue(std::vector<EdgeTy> & Queue,const BinaryFunction & BF)250 void PHGreedyClusterAlgorithm::adjustQueue(std::vector<EdgeTy> &Queue,
251 const BinaryFunction &BF) {
252 // Nothing to do.
253 return;
254 }
255
areClustersCompatible(const ClusterTy & Front,const ClusterTy & Back,const EdgeTy & E) const256 bool PHGreedyClusterAlgorithm::areClustersCompatible(const ClusterTy &Front,
257 const ClusterTy &Back,
258 const EdgeTy &E) const {
259 return Front.back() == E.Src && Back.front() == E.Dst;
260 }
261
calculateWeight(const EdgeTy & E,const BinaryFunction & BF) const262 int64_t MinBranchGreedyClusterAlgorithm::calculateWeight(
263 const EdgeTy &E, const BinaryFunction &BF) const {
264 const BinaryBasicBlock *SrcBB = E.Src;
265 const BinaryBasicBlock *DstBB = E.Dst;
266
267 // Initial weight value.
268 int64_t W = (int64_t)E.Count;
269
270 // Adjust the weight by taking into account other edges with the same source.
271 auto BI = SrcBB->branch_info_begin();
272 for (const BinaryBasicBlock *SuccBB : SrcBB->successors()) {
273 assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
274 "attempted reordering blocks of function with no profile data");
275 assert(BI->Count <= std::numeric_limits<int64_t>::max() &&
276 "overflow detected");
277 // Ignore edges with same source and destination, edges that target the
278 // entry block as well as the edge E itself.
279 if (SuccBB != SrcBB && SuccBB != *BF.getLayout().block_begin() &&
280 SuccBB != DstBB)
281 W -= (int64_t)BI->Count;
282 ++BI;
283 }
284
285 // Adjust the weight by taking into account other edges with the same
286 // destination.
287 for (const BinaryBasicBlock *PredBB : DstBB->predecessors()) {
288 // Ignore edges with same source and destination as well as the edge E
289 // itself.
290 if (PredBB == DstBB || PredBB == SrcBB)
291 continue;
292 auto BI = PredBB->branch_info_begin();
293 for (const BinaryBasicBlock *SuccBB : PredBB->successors()) {
294 if (SuccBB == DstBB)
295 break;
296 ++BI;
297 }
298 assert(BI != PredBB->branch_info_end() && "invalid control flow graph");
299 assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
300 "attempted reordering blocks of function with no profile data");
301 assert(BI->Count <= std::numeric_limits<int64_t>::max() &&
302 "overflow detected");
303 W -= (int64_t)BI->Count;
304 }
305
306 return W;
307 }
308
initQueue(std::vector<EdgeTy> & Queue,const BinaryFunction & BF)309 void MinBranchGreedyClusterAlgorithm::initQueue(std::vector<EdgeTy> &Queue,
310 const BinaryFunction &BF) {
311 // Initialize edge weights.
312 for (const EdgeTy &E : Queue)
313 Weight.emplace(std::make_pair(E, calculateWeight(E, BF)));
314
315 // Sort edges in increasing weight order.
316 adjustQueue(Queue, BF);
317 }
318
adjustQueue(std::vector<EdgeTy> & Queue,const BinaryFunction & BF)319 void MinBranchGreedyClusterAlgorithm::adjustQueue(std::vector<EdgeTy> &Queue,
320 const BinaryFunction &BF) {
321 // Define a comparison function to establish SWO between edges.
322 auto Comp = [&](const EdgeTy &A, const EdgeTy &B) {
323 // With equal weights, prioritize branches with lower index
324 // source/destination. This helps to keep original block order for blocks
325 // when optimal order cannot be deduced from a profile.
326 if (Weight[A] == Weight[B]) {
327 const signed SrcOrder = BF.getOriginalLayoutRelativeOrder(A.Src, B.Src);
328 return (SrcOrder != 0)
329 ? SrcOrder > 0
330 : BF.getOriginalLayoutRelativeOrder(A.Dst, B.Dst) > 0;
331 }
332 return Weight[A] < Weight[B];
333 };
334
335 // Iterate through all remaining edges to find edges that have their
336 // source and destination in the same cluster.
337 std::vector<EdgeTy> NewQueue;
338 for (const EdgeTy &E : Queue) {
339 const BinaryBasicBlock *SrcBB = E.Src;
340 const BinaryBasicBlock *DstBB = E.Dst;
341
342 // Case 1: SrcBB and DstBB are the same or DstBB is the entry block. Ignore
343 // this edge.
344 if (SrcBB == DstBB || DstBB == *BF.getLayout().block_begin()) {
345 LLVM_DEBUG(dbgs() << "\tAdjustment: Ignored edge "; E.print(dbgs());
346 dbgs() << " (same src, dst)\n");
347 continue;
348 }
349
350 int I = BBToClusterMap[SrcBB];
351 int J = BBToClusterMap[DstBB];
352 std::vector<BinaryBasicBlock *> &ClusterA = Clusters[I];
353 std::vector<BinaryBasicBlock *> &ClusterB = Clusters[J];
354
355 // Case 2: They are already allocated at the same cluster or incompatible
356 // clusters. Adjust the weights of edges with the same source or
357 // destination, so that this edge has no effect on them any more, and ignore
358 // this edge. Also increase the intra- (or inter-) cluster edge count.
359 if (I == J || !areClustersCompatible(ClusterA, ClusterB, E)) {
360 if (!ClusterEdges.empty())
361 ClusterEdges[I][J] += E.Count;
362 LLVM_DEBUG(dbgs() << "\tAdjustment: Ignored edge "; E.print(dbgs());
363 dbgs() << " (src, dst belong to same cluster or incompatible "
364 "clusters)\n");
365 for (const BinaryBasicBlock *SuccBB : SrcBB->successors()) {
366 if (SuccBB == DstBB)
367 continue;
368 auto WI = Weight.find(EdgeTy(SrcBB, SuccBB, 0));
369 assert(WI != Weight.end() && "CFG edge not found in Weight map");
370 WI->second += (int64_t)E.Count;
371 }
372 for (const BinaryBasicBlock *PredBB : DstBB->predecessors()) {
373 if (PredBB == SrcBB)
374 continue;
375 auto WI = Weight.find(EdgeTy(PredBB, DstBB, 0));
376 assert(WI != Weight.end() && "CFG edge not found in Weight map");
377 WI->second += (int64_t)E.Count;
378 }
379 continue;
380 }
381
382 // Case 3: None of the previous cases is true, so just keep this edge in
383 // the queue.
384 NewQueue.emplace_back(E);
385 }
386
387 // Sort remaining edges in increasing weight order.
388 Queue.swap(NewQueue);
389 llvm::sort(Queue, Comp);
390 }
391
areClustersCompatible(const ClusterTy & Front,const ClusterTy & Back,const EdgeTy & E) const392 bool MinBranchGreedyClusterAlgorithm::areClustersCompatible(
393 const ClusterTy &Front, const ClusterTy &Back, const EdgeTy &E) const {
394 return Front.back() == E.Src && Back.front() == E.Dst;
395 }
396
reset()397 void MinBranchGreedyClusterAlgorithm::reset() {
398 GreedyClusterAlgorithm::reset();
399 Weight.clear();
400 }
401
reorderBasicBlocks(const BinaryFunction & BF,BasicBlockOrder & Order) const402 void TSPReorderAlgorithm::reorderBasicBlocks(const BinaryFunction &BF,
403 BasicBlockOrder &Order) const {
404 std::vector<std::vector<uint64_t>> Weight;
405 std::vector<BinaryBasicBlock *> IndexToBB;
406
407 const size_t N = BF.getLayout().block_size();
408 assert(N <= std::numeric_limits<uint64_t>::digits &&
409 "cannot use TSP solution for sizes larger than bits in uint64_t");
410
411 // Populating weight map and index map
412 for (BinaryBasicBlock *BB : BF.getLayout().blocks()) {
413 BB->setLayoutIndex(IndexToBB.size());
414 IndexToBB.push_back(BB);
415 }
416 Weight.resize(N);
417 for (BinaryBasicBlock *BB : BF.getLayout().blocks()) {
418 auto BI = BB->branch_info_begin();
419 Weight[BB->getLayoutIndex()].resize(N);
420 for (BinaryBasicBlock *SuccBB : BB->successors()) {
421 if (BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE)
422 Weight[BB->getLayoutIndex()][SuccBB->getLayoutIndex()] = BI->Count;
423 ++BI;
424 }
425 }
426
427 std::vector<std::vector<int64_t>> DP;
428 DP.resize(1 << N);
429 for (std::vector<int64_t> &Elmt : DP)
430 Elmt.resize(N, -1);
431
432 // Start with the entry basic block being allocated with cost zero
433 DP[1][0] = 0;
434 // Walk through TSP solutions using a bitmask to represent state (current set
435 // of BBs in the layout)
436 uint64_t BestSet = 1;
437 uint64_t BestLast = 0;
438 int64_t BestWeight = 0;
439 for (uint64_t Set = 1; Set < (1ULL << N); ++Set) {
440 // Traverse each possibility of Last BB visited in this layout
441 for (uint64_t Last = 0; Last < N; ++Last) {
442 // Case 1: There is no possible layout with this BB as Last
443 if (DP[Set][Last] == -1)
444 continue;
445
446 // Case 2: There is a layout with this Set and this Last, and we try
447 // to expand this set with New
448 for (uint64_t New = 1; New < N; ++New) {
449 // Case 2a: BB "New" is already in this Set
450 if ((Set & (1ULL << New)) != 0)
451 continue;
452
453 // Case 2b: BB "New" is not in this set and we add it to this Set and
454 // record total weight of this layout with "New" as the last BB.
455 uint64_t NewSet = (Set | (1ULL << New));
456 if (DP[NewSet][New] == -1)
457 DP[NewSet][New] = DP[Set][Last] + (int64_t)Weight[Last][New];
458 DP[NewSet][New] = std::max(DP[NewSet][New],
459 DP[Set][Last] + (int64_t)Weight[Last][New]);
460
461 if (DP[NewSet][New] > BestWeight) {
462 BestWeight = DP[NewSet][New];
463 BestSet = NewSet;
464 BestLast = New;
465 }
466 }
467 }
468 }
469
470 // Define final function layout based on layout that maximizes weight
471 uint64_t Last = BestLast;
472 uint64_t Set = BestSet;
473 BitVector Visited;
474 Visited.resize(N);
475 Visited[Last] = true;
476 Order.push_back(IndexToBB[Last]);
477 Set = Set & ~(1ULL << Last);
478 while (Set != 0) {
479 int64_t Best = -1;
480 uint64_t NewLast;
481 for (uint64_t I = 0; I < N; ++I) {
482 if (DP[Set][I] == -1)
483 continue;
484 int64_t AdjWeight = Weight[I][Last] > 0 ? Weight[I][Last] : 0;
485 if (DP[Set][I] + AdjWeight > Best) {
486 NewLast = I;
487 Best = DP[Set][I] + AdjWeight;
488 }
489 }
490 Last = NewLast;
491 Visited[Last] = true;
492 Order.push_back(IndexToBB[Last]);
493 Set = Set & ~(1ULL << Last);
494 }
495 std::reverse(Order.begin(), Order.end());
496
497 // Finalize layout with BBs that weren't assigned to the layout using the
498 // input layout.
499 for (BinaryBasicBlock *BB : BF.getLayout().blocks())
500 if (Visited[BB->getLayoutIndex()] == false)
501 Order.push_back(BB);
502 }
503
reorderBasicBlocks(const BinaryFunction & BF,BasicBlockOrder & Order) const504 void OptimizeReorderAlgorithm::reorderBasicBlocks(
505 const BinaryFunction &BF, BasicBlockOrder &Order) const {
506 if (BF.getLayout().block_empty())
507 return;
508
509 // Cluster basic blocks.
510 CAlgo->clusterBasicBlocks(BF);
511
512 if (opts::PrintClusters)
513 CAlgo->printClusters();
514
515 // Arrange basic blocks according to clusters.
516 for (ClusterAlgorithm::ClusterTy &Cluster : CAlgo->Clusters)
517 Order.insert(Order.end(), Cluster.begin(), Cluster.end());
518 }
519
reorderBasicBlocks(const BinaryFunction & BF,BasicBlockOrder & Order) const520 void OptimizeBranchReorderAlgorithm::reorderBasicBlocks(
521 const BinaryFunction &BF, BasicBlockOrder &Order) const {
522 if (BF.getLayout().block_empty())
523 return;
524
525 // Cluster basic blocks.
526 CAlgo->clusterBasicBlocks(BF, /* ComputeEdges = */ true);
527 std::vector<ClusterAlgorithm::ClusterTy> &Clusters = CAlgo->Clusters;
528 std::vector<std::unordered_map<uint32_t, uint64_t>> &ClusterEdges =
529 CAlgo->ClusterEdges;
530
531 // Compute clusters' average frequencies.
532 CAlgo->computeClusterAverageFrequency(BF.getBinaryContext());
533 std::vector<double> &AvgFreq = CAlgo->AvgFreq;
534
535 if (opts::PrintClusters)
536 CAlgo->printClusters();
537
538 // Cluster layout order
539 std::vector<uint32_t> ClusterOrder;
540
541 // Do a topological sort for clusters, prioritizing frequently-executed BBs
542 // during the traversal.
543 std::stack<uint32_t> Stack;
544 std::vector<uint32_t> Status;
545 std::vector<uint32_t> Parent;
546 Status.resize(Clusters.size(), 0);
547 Parent.resize(Clusters.size(), 0);
548 constexpr uint32_t STACKED = 1;
549 constexpr uint32_t VISITED = 2;
550 Status[0] = STACKED;
551 Stack.push(0);
552 while (!Stack.empty()) {
553 uint32_t I = Stack.top();
554 if (!(Status[I] & VISITED)) {
555 Status[I] |= VISITED;
556 // Order successors by weight
557 auto ClusterComp = [&ClusterEdges, I](uint32_t A, uint32_t B) {
558 return ClusterEdges[I][A] > ClusterEdges[I][B];
559 };
560 std::priority_queue<uint32_t, std::vector<uint32_t>,
561 decltype(ClusterComp)>
562 SuccQueue(ClusterComp);
563 for (std::pair<const uint32_t, uint64_t> &Target : ClusterEdges[I]) {
564 if (Target.second > 0 && !(Status[Target.first] & STACKED) &&
565 !Clusters[Target.first].empty()) {
566 Parent[Target.first] = I;
567 Status[Target.first] = STACKED;
568 SuccQueue.push(Target.first);
569 }
570 }
571 while (!SuccQueue.empty()) {
572 Stack.push(SuccQueue.top());
573 SuccQueue.pop();
574 }
575 continue;
576 }
577 // Already visited this node
578 Stack.pop();
579 ClusterOrder.push_back(I);
580 }
581 std::reverse(ClusterOrder.begin(), ClusterOrder.end());
582 // Put unreachable clusters at the end
583 for (uint32_t I = 0, E = Clusters.size(); I < E; ++I)
584 if (!(Status[I] & VISITED) && !Clusters[I].empty())
585 ClusterOrder.push_back(I);
586
587 // Sort nodes with equal precedence
588 auto Beg = ClusterOrder.begin();
589 // Don't reorder the first cluster, which contains the function entry point
590 ++Beg;
591 std::stable_sort(Beg, ClusterOrder.end(),
592 [&AvgFreq, &Parent](uint32_t A, uint32_t B) {
593 uint32_t P = Parent[A];
594 while (Parent[P] != 0) {
595 if (Parent[P] == B)
596 return false;
597 P = Parent[P];
598 }
599 P = Parent[B];
600 while (Parent[P] != 0) {
601 if (Parent[P] == A)
602 return true;
603 P = Parent[P];
604 }
605 return AvgFreq[A] > AvgFreq[B];
606 });
607
608 if (opts::PrintClusters) {
609 errs() << "New cluster order: ";
610 const char *Sep = "";
611 for (uint32_t O : ClusterOrder) {
612 errs() << Sep << O;
613 Sep = ", ";
614 }
615 errs() << '\n';
616 }
617
618 // Arrange basic blocks according to cluster order.
619 for (uint32_t ClusterIndex : ClusterOrder) {
620 ClusterAlgorithm::ClusterTy &Cluster = Clusters[ClusterIndex];
621 Order.insert(Order.end(), Cluster.begin(), Cluster.end());
622 }
623 }
624
reorderBasicBlocks(const BinaryFunction & BF,BasicBlockOrder & Order) const625 void OptimizeCacheReorderAlgorithm::reorderBasicBlocks(
626 const BinaryFunction &BF, BasicBlockOrder &Order) const {
627 if (BF.getLayout().block_empty())
628 return;
629
630 const uint64_t ColdThreshold =
631 opts::ColdThreshold *
632 (*BF.getLayout().block_begin())->getExecutionCount() / 1000;
633
634 // Cluster basic blocks.
635 CAlgo->clusterBasicBlocks(BF);
636 std::vector<ClusterAlgorithm::ClusterTy> &Clusters = CAlgo->Clusters;
637
638 // Compute clusters' average frequencies.
639 CAlgo->computeClusterAverageFrequency(BF.getBinaryContext());
640 std::vector<double> &AvgFreq = CAlgo->AvgFreq;
641
642 if (opts::PrintClusters)
643 CAlgo->printClusters();
644
645 // Cluster layout order
646 std::vector<uint32_t> ClusterOrder;
647
648 // Order clusters based on average instruction execution frequency
649 for (uint32_t I = 0, E = Clusters.size(); I < E; ++I)
650 if (!Clusters[I].empty())
651 ClusterOrder.push_back(I);
652 // Don't reorder the first cluster, which contains the function entry point
653 std::stable_sort(
654 std::next(ClusterOrder.begin()), ClusterOrder.end(),
655 [&AvgFreq](uint32_t A, uint32_t B) { return AvgFreq[A] > AvgFreq[B]; });
656
657 if (opts::PrintClusters) {
658 errs() << "New cluster order: ";
659 const char *Sep = "";
660 for (uint32_t O : ClusterOrder) {
661 errs() << Sep << O;
662 Sep = ", ";
663 }
664 errs() << '\n';
665 }
666
667 // Arrange basic blocks according to cluster order.
668 for (uint32_t ClusterIndex : ClusterOrder) {
669 ClusterAlgorithm::ClusterTy &Cluster = Clusters[ClusterIndex];
670 Order.insert(Order.end(), Cluster.begin(), Cluster.end());
671 // Force zero execution count on clusters that do not meet the cut off
672 // specified by --cold-threshold.
673 if (AvgFreq[ClusterIndex] < static_cast<double>(ColdThreshold))
674 for (BinaryBasicBlock *BBPtr : Cluster)
675 BBPtr->setExecutionCount(0);
676 }
677 }
678
reorderBasicBlocks(const BinaryFunction & BF,BasicBlockOrder & Order) const679 void ReverseReorderAlgorithm::reorderBasicBlocks(const BinaryFunction &BF,
680 BasicBlockOrder &Order) const {
681 if (BF.getLayout().block_empty())
682 return;
683
684 BinaryBasicBlock *FirstBB = *BF.getLayout().block_begin();
685 Order.push_back(FirstBB);
686 for (auto RLI = BF.getLayout().block_rbegin(); *RLI != FirstBB; ++RLI)
687 Order.push_back(*RLI);
688 }
689
reorderBasicBlocks(const BinaryFunction & BF,BasicBlockOrder & Order) const690 void RandomClusterReorderAlgorithm::reorderBasicBlocks(
691 const BinaryFunction &BF, BasicBlockOrder &Order) const {
692 if (BF.getLayout().block_empty())
693 return;
694
695 // Cluster basic blocks.
696 CAlgo->clusterBasicBlocks(BF);
697 std::vector<ClusterAlgorithm::ClusterTy> &Clusters = CAlgo->Clusters;
698
699 if (opts::PrintClusters)
700 CAlgo->printClusters();
701
702 // Cluster layout order
703 std::vector<uint32_t> ClusterOrder;
704
705 // Order clusters based on average instruction execution frequency
706 for (uint32_t I = 0, E = Clusters.size(); I < E; ++I)
707 if (!Clusters[I].empty())
708 ClusterOrder.push_back(I);
709
710 std::shuffle(std::next(ClusterOrder.begin()), ClusterOrder.end(),
711 std::default_random_engine(opts::RandomSeed.getValue()));
712
713 if (opts::PrintClusters) {
714 errs() << "New cluster order: ";
715 const char *Sep = "";
716 for (uint32_t O : ClusterOrder) {
717 errs() << Sep << O;
718 Sep = ", ";
719 }
720 errs() << '\n';
721 }
722
723 // Arrange basic blocks according to cluster order.
724 for (uint32_t ClusterIndex : ClusterOrder) {
725 ClusterAlgorithm::ClusterTy &Cluster = Clusters[ClusterIndex];
726 Order.insert(Order.end(), Cluster.begin(), Cluster.end());
727 }
728 }
729