1 //==- BlockFrequencyInfoImpl.h - Block Frequency Implementation --*- C++ -*-==// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Shared implementation of BlockFrequency for IR and Machine Instructions. 10 // See the documentation below for BlockFrequencyInfoImpl for details. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H 15 #define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H 16 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/DenseSet.h" 20 #include "llvm/ADT/GraphTraits.h" 21 #include "llvm/ADT/PostOrderIterator.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/SparseBitVector.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/ADT/iterator_range.h" 27 #include "llvm/IR/BasicBlock.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/ValueHandle.h" 30 #include "llvm/Support/BlockFrequency.h" 31 #include "llvm/Support/BranchProbability.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/DOTGraphTraits.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/Format.h" 36 #include "llvm/Support/ScaledNumber.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include <algorithm> 39 #include <cassert> 40 #include <cstddef> 41 #include <cstdint> 42 #include <deque> 43 #include <iterator> 44 #include <limits> 45 #include <list> 46 #include <optional> 47 #include <queue> 48 #include <string> 49 #include <utility> 50 #include <vector> 51 52 #define DEBUG_TYPE "block-freq" 53 54 namespace llvm { 55 extern llvm::cl::opt<bool> CheckBFIUnknownBlockQueries; 56 57 extern llvm::cl::opt<bool> UseIterativeBFIInference; 58 extern llvm::cl::opt<unsigned> IterativeBFIMaxIterationsPerBlock; 59 extern llvm::cl::opt<double> IterativeBFIPrecision; 60 61 class BranchProbabilityInfo; 62 class Function; 63 class Loop; 64 class LoopInfo; 65 class MachineBasicBlock; 66 class MachineBranchProbabilityInfo; 67 class MachineFunction; 68 class MachineLoop; 69 class MachineLoopInfo; 70 71 namespace bfi_detail { 72 73 struct IrreducibleGraph; 74 75 /// Mass of a block. 76 /// 77 /// This class implements a sort of fixed-point fraction always between 0.0 and 78 /// 1.0. getMass() == std::numeric_limits<uint64_t>::max() indicates a value of 79 /// 1.0. 80 /// 81 /// Masses can be added and subtracted. Simple saturation arithmetic is used, 82 /// so arithmetic operations never overflow or underflow. 83 /// 84 /// Masses can be multiplied. Multiplication treats full mass as 1.0 and uses 85 /// an inexpensive floating-point algorithm that's off-by-one (almost, but not 86 /// quite, maximum precision). 87 /// 88 /// Masses can be scaled by \a BranchProbability at maximum precision. 89 class BlockMass { 90 uint64_t Mass = 0; 91 92 public: 93 BlockMass() = default; BlockMass(uint64_t Mass)94 explicit BlockMass(uint64_t Mass) : Mass(Mass) {} 95 getEmpty()96 static BlockMass getEmpty() { return BlockMass(); } 97 getFull()98 static BlockMass getFull() { 99 return BlockMass(std::numeric_limits<uint64_t>::max()); 100 } 101 getMass()102 uint64_t getMass() const { return Mass; } 103 isFull()104 bool isFull() const { return Mass == std::numeric_limits<uint64_t>::max(); } isEmpty()105 bool isEmpty() const { return !Mass; } 106 107 bool operator!() const { return isEmpty(); } 108 109 /// Add another mass. 110 /// 111 /// Adds another mass, saturating at \a isFull() rather than overflowing. 112 BlockMass &operator+=(BlockMass X) { 113 uint64_t Sum = Mass + X.Mass; 114 Mass = Sum < Mass ? std::numeric_limits<uint64_t>::max() : Sum; 115 return *this; 116 } 117 118 /// Subtract another mass. 119 /// 120 /// Subtracts another mass, saturating at \a isEmpty() rather than 121 /// undeflowing. 122 BlockMass &operator-=(BlockMass X) { 123 uint64_t Diff = Mass - X.Mass; 124 Mass = Diff > Mass ? 0 : Diff; 125 return *this; 126 } 127 128 BlockMass &operator*=(BranchProbability P) { 129 Mass = P.scale(Mass); 130 return *this; 131 } 132 133 bool operator==(BlockMass X) const { return Mass == X.Mass; } 134 bool operator!=(BlockMass X) const { return Mass != X.Mass; } 135 bool operator<=(BlockMass X) const { return Mass <= X.Mass; } 136 bool operator>=(BlockMass X) const { return Mass >= X.Mass; } 137 bool operator<(BlockMass X) const { return Mass < X.Mass; } 138 bool operator>(BlockMass X) const { return Mass > X.Mass; } 139 140 /// Convert to scaled number. 141 /// 142 /// Convert to \a ScaledNumber. \a isFull() gives 1.0, while \a isEmpty() 143 /// gives slightly above 0.0. 144 ScaledNumber<uint64_t> toScaled() const; 145 146 void dump() const; 147 raw_ostream &print(raw_ostream &OS) const; 148 }; 149 150 inline BlockMass operator+(BlockMass L, BlockMass R) { 151 return BlockMass(L) += R; 152 } 153 inline BlockMass operator-(BlockMass L, BlockMass R) { 154 return BlockMass(L) -= R; 155 } 156 inline BlockMass operator*(BlockMass L, BranchProbability R) { 157 return BlockMass(L) *= R; 158 } 159 inline BlockMass operator*(BranchProbability L, BlockMass R) { 160 return BlockMass(R) *= L; 161 } 162 163 inline raw_ostream &operator<<(raw_ostream &OS, BlockMass X) { 164 return X.print(OS); 165 } 166 167 } // end namespace bfi_detail 168 169 /// Base class for BlockFrequencyInfoImpl 170 /// 171 /// BlockFrequencyInfoImplBase has supporting data structures and some 172 /// algorithms for BlockFrequencyInfoImplBase. Only algorithms that depend on 173 /// the block type (or that call such algorithms) are skipped here. 174 /// 175 /// Nevertheless, the majority of the overall algorithm documentation lives with 176 /// BlockFrequencyInfoImpl. See there for details. 177 class BlockFrequencyInfoImplBase { 178 public: 179 using Scaled64 = ScaledNumber<uint64_t>; 180 using BlockMass = bfi_detail::BlockMass; 181 182 /// Representative of a block. 183 /// 184 /// This is a simple wrapper around an index into the reverse-post-order 185 /// traversal of the blocks. 186 /// 187 /// Unlike a block pointer, its order has meaning (location in the 188 /// topological sort) and it's class is the same regardless of block type. 189 struct BlockNode { 190 using IndexType = uint32_t; 191 192 IndexType Index; 193 BlockNodeBlockNode194 BlockNode() : Index(std::numeric_limits<uint32_t>::max()) {} BlockNodeBlockNode195 BlockNode(IndexType Index) : Index(Index) {} 196 197 bool operator==(const BlockNode &X) const { return Index == X.Index; } 198 bool operator!=(const BlockNode &X) const { return Index != X.Index; } 199 bool operator<=(const BlockNode &X) const { return Index <= X.Index; } 200 bool operator>=(const BlockNode &X) const { return Index >= X.Index; } 201 bool operator<(const BlockNode &X) const { return Index < X.Index; } 202 bool operator>(const BlockNode &X) const { return Index > X.Index; } 203 isValidBlockNode204 bool isValid() const { return Index <= getMaxIndex(); } 205 getMaxIndexBlockNode206 static size_t getMaxIndex() { 207 return std::numeric_limits<uint32_t>::max() - 1; 208 } 209 }; 210 211 /// Stats about a block itself. 212 struct FrequencyData { 213 Scaled64 Scaled; 214 uint64_t Integer; 215 }; 216 217 /// Data about a loop. 218 /// 219 /// Contains the data necessary to represent a loop as a pseudo-node once it's 220 /// packaged. 221 struct LoopData { 222 using ExitMap = SmallVector<std::pair<BlockNode, BlockMass>, 4>; 223 using NodeList = SmallVector<BlockNode, 4>; 224 using HeaderMassList = SmallVector<BlockMass, 1>; 225 226 LoopData *Parent; ///< The parent loop. 227 bool IsPackaged = false; ///< Whether this has been packaged. 228 uint32_t NumHeaders = 1; ///< Number of headers. 229 ExitMap Exits; ///< Successor edges (and weights). 230 NodeList Nodes; ///< Header and the members of the loop. 231 HeaderMassList BackedgeMass; ///< Mass returned to each loop header. 232 BlockMass Mass; 233 Scaled64 Scale; 234 LoopDataLoopData235 LoopData(LoopData *Parent, const BlockNode &Header) 236 : Parent(Parent), Nodes(1, Header), BackedgeMass(1) {} 237 238 template <class It1, class It2> LoopDataLoopData239 LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther, 240 It2 LastOther) 241 : Parent(Parent), Nodes(FirstHeader, LastHeader) { 242 NumHeaders = Nodes.size(); 243 Nodes.insert(Nodes.end(), FirstOther, LastOther); 244 BackedgeMass.resize(NumHeaders); 245 } 246 isHeaderLoopData247 bool isHeader(const BlockNode &Node) const { 248 if (isIrreducible()) 249 return std::binary_search(Nodes.begin(), Nodes.begin() + NumHeaders, 250 Node); 251 return Node == Nodes[0]; 252 } 253 getHeaderLoopData254 BlockNode getHeader() const { return Nodes[0]; } isIrreducibleLoopData255 bool isIrreducible() const { return NumHeaders > 1; } 256 getHeaderIndexLoopData257 HeaderMassList::difference_type getHeaderIndex(const BlockNode &B) { 258 assert(isHeader(B) && "this is only valid on loop header blocks"); 259 if (isIrreducible()) 260 return std::lower_bound(Nodes.begin(), Nodes.begin() + NumHeaders, B) - 261 Nodes.begin(); 262 return 0; 263 } 264 members_beginLoopData265 NodeList::const_iterator members_begin() const { 266 return Nodes.begin() + NumHeaders; 267 } 268 members_endLoopData269 NodeList::const_iterator members_end() const { return Nodes.end(); } membersLoopData270 iterator_range<NodeList::const_iterator> members() const { 271 return make_range(members_begin(), members_end()); 272 } 273 }; 274 275 /// Index of loop information. 276 struct WorkingData { 277 BlockNode Node; ///< This node. 278 LoopData *Loop = nullptr; ///< The loop this block is inside. 279 BlockMass Mass; ///< Mass distribution from the entry block. 280 WorkingDataWorkingData281 WorkingData(const BlockNode &Node) : Node(Node) {} 282 isLoopHeaderWorkingData283 bool isLoopHeader() const { return Loop && Loop->isHeader(Node); } 284 isDoubleLoopHeaderWorkingData285 bool isDoubleLoopHeader() const { 286 return isLoopHeader() && Loop->Parent && Loop->Parent->isIrreducible() && 287 Loop->Parent->isHeader(Node); 288 } 289 getContainingLoopWorkingData290 LoopData *getContainingLoop() const { 291 if (!isLoopHeader()) 292 return Loop; 293 if (!isDoubleLoopHeader()) 294 return Loop->Parent; 295 return Loop->Parent->Parent; 296 } 297 298 /// Resolve a node to its representative. 299 /// 300 /// Get the node currently representing Node, which could be a containing 301 /// loop. 302 /// 303 /// This function should only be called when distributing mass. As long as 304 /// there are no irreducible edges to Node, then it will have complexity 305 /// O(1) in this context. 306 /// 307 /// In general, the complexity is O(L), where L is the number of loop 308 /// headers Node has been packaged into. Since this method is called in 309 /// the context of distributing mass, L will be the number of loop headers 310 /// an early exit edge jumps out of. getResolvedNodeWorkingData311 BlockNode getResolvedNode() const { 312 auto *L = getPackagedLoop(); 313 return L ? L->getHeader() : Node; 314 } 315 getPackagedLoopWorkingData316 LoopData *getPackagedLoop() const { 317 if (!Loop || !Loop->IsPackaged) 318 return nullptr; 319 auto *L = Loop; 320 while (L->Parent && L->Parent->IsPackaged) 321 L = L->Parent; 322 return L; 323 } 324 325 /// Get the appropriate mass for a node. 326 /// 327 /// Get appropriate mass for Node. If Node is a loop-header (whose loop 328 /// has been packaged), returns the mass of its pseudo-node. If it's a 329 /// node inside a packaged loop, it returns the loop's mass. getMassWorkingData330 BlockMass &getMass() { 331 if (!isAPackage()) 332 return Mass; 333 if (!isADoublePackage()) 334 return Loop->Mass; 335 return Loop->Parent->Mass; 336 } 337 338 /// Has ContainingLoop been packaged up? isPackagedWorkingData339 bool isPackaged() const { return getResolvedNode() != Node; } 340 341 /// Has Loop been packaged up? isAPackageWorkingData342 bool isAPackage() const { return isLoopHeader() && Loop->IsPackaged; } 343 344 /// Has Loop been packaged up twice? isADoublePackageWorkingData345 bool isADoublePackage() const { 346 return isDoubleLoopHeader() && Loop->Parent->IsPackaged; 347 } 348 }; 349 350 /// Unscaled probability weight. 351 /// 352 /// Probability weight for an edge in the graph (including the 353 /// successor/target node). 354 /// 355 /// All edges in the original function are 32-bit. However, exit edges from 356 /// loop packages are taken from 64-bit exit masses, so we need 64-bits of 357 /// space in general. 358 /// 359 /// In addition to the raw weight amount, Weight stores the type of the edge 360 /// in the current context (i.e., the context of the loop being processed). 361 /// Is this a local edge within the loop, an exit from the loop, or a 362 /// backedge to the loop header? 363 struct Weight { 364 enum DistType { Local, Exit, Backedge }; 365 DistType Type = Local; 366 BlockNode TargetNode; 367 uint64_t Amount = 0; 368 369 Weight() = default; WeightWeight370 Weight(DistType Type, BlockNode TargetNode, uint64_t Amount) 371 : Type(Type), TargetNode(TargetNode), Amount(Amount) {} 372 }; 373 374 /// Distribution of unscaled probability weight. 375 /// 376 /// Distribution of unscaled probability weight to a set of successors. 377 /// 378 /// This class collates the successor edge weights for later processing. 379 /// 380 /// \a DidOverflow indicates whether \a Total did overflow while adding to 381 /// the distribution. It should never overflow twice. 382 struct Distribution { 383 using WeightList = SmallVector<Weight, 4>; 384 385 WeightList Weights; ///< Individual successor weights. 386 uint64_t Total = 0; ///< Sum of all weights. 387 bool DidOverflow = false; ///< Whether \a Total did overflow. 388 389 Distribution() = default; 390 addLocalDistribution391 void addLocal(const BlockNode &Node, uint64_t Amount) { 392 add(Node, Amount, Weight::Local); 393 } 394 addExitDistribution395 void addExit(const BlockNode &Node, uint64_t Amount) { 396 add(Node, Amount, Weight::Exit); 397 } 398 addBackedgeDistribution399 void addBackedge(const BlockNode &Node, uint64_t Amount) { 400 add(Node, Amount, Weight::Backedge); 401 } 402 403 /// Normalize the distribution. 404 /// 405 /// Combines multiple edges to the same \a Weight::TargetNode and scales 406 /// down so that \a Total fits into 32-bits. 407 /// 408 /// This is linear in the size of \a Weights. For the vast majority of 409 /// cases, adjacent edge weights are combined by sorting WeightList and 410 /// combining adjacent weights. However, for very large edge lists an 411 /// auxiliary hash table is used. 412 void normalize(); 413 414 private: 415 void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type); 416 }; 417 418 /// Data about each block. This is used downstream. 419 std::vector<FrequencyData> Freqs; 420 421 /// Whether each block is an irreducible loop header. 422 /// This is used downstream. 423 SparseBitVector<> IsIrrLoopHeader; 424 425 /// Loop data: see initializeLoops(). 426 std::vector<WorkingData> Working; 427 428 /// Indexed information about loops. 429 std::list<LoopData> Loops; 430 431 /// Virtual destructor. 432 /// 433 /// Need a virtual destructor to mask the compiler warning about 434 /// getBlockName(). 435 virtual ~BlockFrequencyInfoImplBase() = default; 436 437 /// Add all edges out of a packaged loop to the distribution. 438 /// 439 /// Adds all edges from LocalLoopHead to Dist. Calls addToDist() to add each 440 /// successor edge. 441 /// 442 /// \return \c true unless there's an irreducible backedge. 443 bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop, 444 Distribution &Dist); 445 446 /// Add an edge to the distribution. 447 /// 448 /// Adds an edge to Succ to Dist. If \c LoopHead.isValid(), then whether the 449 /// edge is local/exit/backedge is in the context of LoopHead. Otherwise, 450 /// every edge should be a local edge (since all the loops are packaged up). 451 /// 452 /// \return \c true unless aborted due to an irreducible backedge. 453 bool addToDist(Distribution &Dist, const LoopData *OuterLoop, 454 const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight); 455 456 /// Analyze irreducible SCCs. 457 /// 458 /// Separate irreducible SCCs from \c G, which is an explicit graph of \c 459 /// OuterLoop (or the top-level function, if \c OuterLoop is \c nullptr). 460 /// Insert them into \a Loops before \c Insert. 461 /// 462 /// \return the \c LoopData nodes representing the irreducible SCCs. 463 iterator_range<std::list<LoopData>::iterator> 464 analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop, 465 std::list<LoopData>::iterator Insert); 466 467 /// Update a loop after packaging irreducible SCCs inside of it. 468 /// 469 /// Update \c OuterLoop. Before finding irreducible control flow, it was 470 /// partway through \a computeMassInLoop(), so \a LoopData::Exits and \a 471 /// LoopData::BackedgeMass need to be reset. Also, nodes that were packaged 472 /// up need to be removed from \a OuterLoop::Nodes. 473 void updateLoopWithIrreducible(LoopData &OuterLoop); 474 475 /// Distribute mass according to a distribution. 476 /// 477 /// Distributes the mass in Source according to Dist. If LoopHead.isValid(), 478 /// backedges and exits are stored in its entry in Loops. 479 /// 480 /// Mass is distributed in parallel from two copies of the source mass. 481 void distributeMass(const BlockNode &Source, LoopData *OuterLoop, 482 Distribution &Dist); 483 484 /// Compute the loop scale for a loop. 485 void computeLoopScale(LoopData &Loop); 486 487 /// Adjust the mass of all headers in an irreducible loop. 488 /// 489 /// Initially, irreducible loops are assumed to distribute their mass 490 /// equally among its headers. This can lead to wrong frequency estimates 491 /// since some headers may be executed more frequently than others. 492 /// 493 /// This adjusts header mass distribution so it matches the weights of 494 /// the backedges going into each of the loop headers. 495 void adjustLoopHeaderMass(LoopData &Loop); 496 497 void distributeIrrLoopHeaderMass(Distribution &Dist); 498 499 /// Package up a loop. 500 void packageLoop(LoopData &Loop); 501 502 /// Unwrap loops. 503 void unwrapLoops(); 504 505 /// Finalize frequency metrics. 506 /// 507 /// Calculates final frequencies and cleans up no-longer-needed data 508 /// structures. 509 void finalizeMetrics(); 510 511 /// Clear all memory. 512 void clear(); 513 514 virtual std::string getBlockName(const BlockNode &Node) const; 515 std::string getLoopName(const LoopData &Loop) const; 516 print(raw_ostream & OS)517 virtual raw_ostream &print(raw_ostream &OS) const { return OS; } dump()518 void dump() const { print(dbgs()); } 519 520 Scaled64 getFloatingBlockFreq(const BlockNode &Node) const; 521 522 BlockFrequency getBlockFreq(const BlockNode &Node) const; 523 std::optional<uint64_t> 524 getBlockProfileCount(const Function &F, const BlockNode &Node, 525 bool AllowSynthetic = false) const; 526 std::optional<uint64_t> 527 getProfileCountFromFreq(const Function &F, BlockFrequency Freq, 528 bool AllowSynthetic = false) const; 529 bool isIrrLoopHeader(const BlockNode &Node); 530 531 void setBlockFreq(const BlockNode &Node, BlockFrequency Freq); 532 getEntryFreq()533 BlockFrequency getEntryFreq() const { 534 assert(!Freqs.empty()); 535 return BlockFrequency(Freqs[0].Integer); 536 } 537 }; 538 539 namespace bfi_detail { 540 541 template <class BlockT> struct TypeMap {}; 542 template <> struct TypeMap<BasicBlock> { 543 using BlockT = BasicBlock; 544 using BlockKeyT = AssertingVH<const BasicBlock>; 545 using FunctionT = Function; 546 using BranchProbabilityInfoT = BranchProbabilityInfo; 547 using LoopT = Loop; 548 using LoopInfoT = LoopInfo; 549 }; 550 template <> struct TypeMap<MachineBasicBlock> { 551 using BlockT = MachineBasicBlock; 552 using BlockKeyT = const MachineBasicBlock *; 553 using FunctionT = MachineFunction; 554 using BranchProbabilityInfoT = MachineBranchProbabilityInfo; 555 using LoopT = MachineLoop; 556 using LoopInfoT = MachineLoopInfo; 557 }; 558 559 template <class BlockT, class BFIImplT> 560 class BFICallbackVH; 561 562 /// Get the name of a MachineBasicBlock. 563 /// 564 /// Get the name of a MachineBasicBlock. It's templated so that including from 565 /// CodeGen is unnecessary (that would be a layering issue). 566 /// 567 /// This is used mainly for debug output. The name is similar to 568 /// MachineBasicBlock::getFullName(), but skips the name of the function. 569 template <class BlockT> std::string getBlockName(const BlockT *BB) { 570 assert(BB && "Unexpected nullptr"); 571 auto MachineName = "BB" + Twine(BB->getNumber()); 572 if (BB->getBasicBlock()) 573 return (MachineName + "[" + BB->getName() + "]").str(); 574 return MachineName.str(); 575 } 576 /// Get the name of a BasicBlock. 577 template <> inline std::string getBlockName(const BasicBlock *BB) { 578 assert(BB && "Unexpected nullptr"); 579 return BB->getName().str(); 580 } 581 582 /// Graph of irreducible control flow. 583 /// 584 /// This graph is used for determining the SCCs in a loop (or top-level 585 /// function) that has irreducible control flow. 586 /// 587 /// During the block frequency algorithm, the local graphs are defined in a 588 /// light-weight way, deferring to the \a BasicBlock or \a MachineBasicBlock 589 /// graphs for most edges, but getting others from \a LoopData::ExitMap. The 590 /// latter only has successor information. 591 /// 592 /// \a IrreducibleGraph makes this graph explicit. It's in a form that can use 593 /// \a GraphTraits (so that \a analyzeIrreducible() can use \a scc_iterator), 594 /// and it explicitly lists predecessors and successors. The initialization 595 /// that relies on \c MachineBasicBlock is defined in the header. 596 struct IrreducibleGraph { 597 using BFIBase = BlockFrequencyInfoImplBase; 598 599 BFIBase &BFI; 600 601 using BlockNode = BFIBase::BlockNode; 602 struct IrrNode { 603 BlockNode Node; 604 unsigned NumIn = 0; 605 std::deque<const IrrNode *> Edges; 606 607 IrrNode(const BlockNode &Node) : Node(Node) {} 608 609 using iterator = std::deque<const IrrNode *>::const_iterator; 610 611 iterator pred_begin() const { return Edges.begin(); } 612 iterator succ_begin() const { return Edges.begin() + NumIn; } 613 iterator pred_end() const { return succ_begin(); } 614 iterator succ_end() const { return Edges.end(); } 615 }; 616 BlockNode Start; 617 const IrrNode *StartIrr = nullptr; 618 std::vector<IrrNode> Nodes; 619 SmallDenseMap<uint32_t, IrrNode *, 4> Lookup; 620 621 /// Construct an explicit graph containing irreducible control flow. 622 /// 623 /// Construct an explicit graph of the control flow in \c OuterLoop (or the 624 /// top-level function, if \c OuterLoop is \c nullptr). Uses \c 625 /// addBlockEdges to add block successors that have not been packaged into 626 /// loops. 627 /// 628 /// \a BlockFrequencyInfoImpl::computeIrreducibleMass() is the only expected 629 /// user of this. 630 template <class BlockEdgesAdder> 631 IrreducibleGraph(BFIBase &BFI, const BFIBase::LoopData *OuterLoop, 632 BlockEdgesAdder addBlockEdges) : BFI(BFI) { 633 initialize(OuterLoop, addBlockEdges); 634 } 635 636 template <class BlockEdgesAdder> 637 void initialize(const BFIBase::LoopData *OuterLoop, 638 BlockEdgesAdder addBlockEdges); 639 void addNodesInLoop(const BFIBase::LoopData &OuterLoop); 640 void addNodesInFunction(); 641 642 void addNode(const BlockNode &Node) { 643 Nodes.emplace_back(Node); 644 BFI.Working[Node.Index].getMass() = BlockMass::getEmpty(); 645 } 646 647 void indexNodes(); 648 template <class BlockEdgesAdder> 649 void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop, 650 BlockEdgesAdder addBlockEdges); 651 void addEdge(IrrNode &Irr, const BlockNode &Succ, 652 const BFIBase::LoopData *OuterLoop); 653 }; 654 655 template <class BlockEdgesAdder> 656 void IrreducibleGraph::initialize(const BFIBase::LoopData *OuterLoop, 657 BlockEdgesAdder addBlockEdges) { 658 if (OuterLoop) { 659 addNodesInLoop(*OuterLoop); 660 for (auto N : OuterLoop->Nodes) 661 addEdges(N, OuterLoop, addBlockEdges); 662 } else { 663 addNodesInFunction(); 664 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index) 665 addEdges(Index, OuterLoop, addBlockEdges); 666 } 667 StartIrr = Lookup[Start.Index]; 668 } 669 670 template <class BlockEdgesAdder> 671 void IrreducibleGraph::addEdges(const BlockNode &Node, 672 const BFIBase::LoopData *OuterLoop, 673 BlockEdgesAdder addBlockEdges) { 674 auto L = Lookup.find(Node.Index); 675 if (L == Lookup.end()) 676 return; 677 IrrNode &Irr = *L->second; 678 const auto &Working = BFI.Working[Node.Index]; 679 680 if (Working.isAPackage()) 681 for (const auto &I : Working.Loop->Exits) 682 addEdge(Irr, I.first, OuterLoop); 683 else 684 addBlockEdges(*this, Irr, OuterLoop); 685 } 686 687 } // end namespace bfi_detail 688 689 /// Shared implementation for block frequency analysis. 690 /// 691 /// This is a shared implementation of BlockFrequencyInfo and 692 /// MachineBlockFrequencyInfo, and calculates the relative frequencies of 693 /// blocks. 694 /// 695 /// LoopInfo defines a loop as a "non-trivial" SCC dominated by a single block, 696 /// which is called the header. A given loop, L, can have sub-loops, which are 697 /// loops within the subgraph of L that exclude its header. (A "trivial" SCC 698 /// consists of a single block that does not have a self-edge.) 699 /// 700 /// In addition to loops, this algorithm has limited support for irreducible 701 /// SCCs, which are SCCs with multiple entry blocks. Irreducible SCCs are 702 /// discovered on the fly, and modelled as loops with multiple headers. 703 /// 704 /// The headers of irreducible sub-SCCs consist of its entry blocks and all 705 /// nodes that are targets of a backedge within it (excluding backedges within 706 /// true sub-loops). Block frequency calculations act as if a block is 707 /// inserted that intercepts all the edges to the headers. All backedges and 708 /// entries point to this block. Its successors are the headers, which split 709 /// the frequency evenly. 710 /// 711 /// This algorithm leverages BlockMass and ScaledNumber to maintain precision, 712 /// separates mass distribution from loop scaling, and dithers to eliminate 713 /// probability mass loss. 714 /// 715 /// The implementation is split between BlockFrequencyInfoImpl, which knows the 716 /// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and 717 /// BlockFrequencyInfoImplBase, which doesn't. The base class uses \a 718 /// BlockNode, a wrapper around a uint32_t. BlockNode is numbered from 0 in 719 /// reverse-post order. This gives two advantages: it's easy to compare the 720 /// relative ordering of two nodes, and maps keyed on BlockT can be represented 721 /// by vectors. 722 /// 723 /// This algorithm is O(V+E), unless there is irreducible control flow, in 724 /// which case it's O(V*E) in the worst case. 725 /// 726 /// These are the main stages: 727 /// 728 /// 0. Reverse post-order traversal (\a initializeRPOT()). 729 /// 730 /// Run a single post-order traversal and save it (in reverse) in RPOT. 731 /// All other stages make use of this ordering. Save a lookup from BlockT 732 /// to BlockNode (the index into RPOT) in Nodes. 733 /// 734 /// 1. Loop initialization (\a initializeLoops()). 735 /// 736 /// Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of 737 /// the algorithm. In particular, store the immediate members of each loop 738 /// in reverse post-order. 739 /// 740 /// 2. Calculate mass and scale in loops (\a computeMassInLoops()). 741 /// 742 /// For each loop (bottom-up), distribute mass through the DAG resulting 743 /// from ignoring backedges and treating sub-loops as a single pseudo-node. 744 /// Track the backedge mass distributed to the loop header, and use it to 745 /// calculate the loop scale (number of loop iterations). Immediate 746 /// members that represent sub-loops will already have been visited and 747 /// packaged into a pseudo-node. 748 /// 749 /// Distributing mass in a loop is a reverse-post-order traversal through 750 /// the loop. Start by assigning full mass to the Loop header. For each 751 /// node in the loop: 752 /// 753 /// - Fetch and categorize the weight distribution for its successors. 754 /// If this is a packaged-subloop, the weight distribution is stored 755 /// in \a LoopData::Exits. Otherwise, fetch it from 756 /// BranchProbabilityInfo. 757 /// 758 /// - Each successor is categorized as \a Weight::Local, a local edge 759 /// within the current loop, \a Weight::Backedge, a backedge to the 760 /// loop header, or \a Weight::Exit, any successor outside the loop. 761 /// The weight, the successor, and its category are stored in \a 762 /// Distribution. There can be multiple edges to each successor. 763 /// 764 /// - If there's a backedge to a non-header, there's an irreducible SCC. 765 /// The usual flow is temporarily aborted. \a 766 /// computeIrreducibleMass() finds the irreducible SCCs within the 767 /// loop, packages them up, and restarts the flow. 768 /// 769 /// - Normalize the distribution: scale weights down so that their sum 770 /// is 32-bits, and coalesce multiple edges to the same node. 771 /// 772 /// - Distribute the mass accordingly, dithering to minimize mass loss, 773 /// as described in \a distributeMass(). 774 /// 775 /// In the case of irreducible loops, instead of a single loop header, 776 /// there will be several. The computation of backedge masses is similar 777 /// but instead of having a single backedge mass, there will be one 778 /// backedge per loop header. In these cases, each backedge will carry 779 /// a mass proportional to the edge weights along the corresponding 780 /// path. 781 /// 782 /// At the end of propagation, the full mass assigned to the loop will be 783 /// distributed among the loop headers proportionally according to the 784 /// mass flowing through their backedges. 785 /// 786 /// Finally, calculate the loop scale from the accumulated backedge mass. 787 /// 788 /// 3. Distribute mass in the function (\a computeMassInFunction()). 789 /// 790 /// Finally, distribute mass through the DAG resulting from packaging all 791 /// loops in the function. This uses the same algorithm as distributing 792 /// mass in a loop, except that there are no exit or backedge edges. 793 /// 794 /// 4. Unpackage loops (\a unwrapLoops()). 795 /// 796 /// Initialize each block's frequency to a floating point representation of 797 /// its mass. 798 /// 799 /// Visit loops top-down, scaling the frequencies of its immediate members 800 /// by the loop's pseudo-node's frequency. 801 /// 802 /// 5. Convert frequencies to a 64-bit range (\a finalizeMetrics()). 803 /// 804 /// Using the min and max frequencies as a guide, translate floating point 805 /// frequencies to an appropriate range in uint64_t. 806 /// 807 /// It has some known flaws. 808 /// 809 /// - The model of irreducible control flow is a rough approximation. 810 /// 811 /// Modelling irreducible control flow exactly involves setting up and 812 /// solving a group of infinite geometric series. Such precision is 813 /// unlikely to be worthwhile, since most of our algorithms give up on 814 /// irreducible control flow anyway. 815 /// 816 /// Nevertheless, we might find that we need to get closer. Here's a sort 817 /// of TODO list for the model with diminishing returns, to be completed as 818 /// necessary. 819 /// 820 /// - The headers for the \a LoopData representing an irreducible SCC 821 /// include non-entry blocks. When these extra blocks exist, they 822 /// indicate a self-contained irreducible sub-SCC. We could treat them 823 /// as sub-loops, rather than arbitrarily shoving the problematic 824 /// blocks into the headers of the main irreducible SCC. 825 /// 826 /// - Entry frequencies are assumed to be evenly split between the 827 /// headers of a given irreducible SCC, which is the only option if we 828 /// need to compute mass in the SCC before its parent loop. Instead, 829 /// we could partially compute mass in the parent loop, and stop when 830 /// we get to the SCC. Here, we have the correct ratio of entry 831 /// masses, which we can use to adjust their relative frequencies. 832 /// Compute mass in the SCC, and then continue propagation in the 833 /// parent. 834 /// 835 /// - We can propagate mass iteratively through the SCC, for some fixed 836 /// number of iterations. Each iteration starts by assigning the entry 837 /// blocks their backedge mass from the prior iteration. The final 838 /// mass for each block (and each exit, and the total backedge mass 839 /// used for computing loop scale) is the sum of all iterations. 840 /// (Running this until fixed point would "solve" the geometric 841 /// series by simulation.) 842 template <class BT> class BlockFrequencyInfoImpl : BlockFrequencyInfoImplBase { 843 using BlockT = typename bfi_detail::TypeMap<BT>::BlockT; 844 using BlockKeyT = typename bfi_detail::TypeMap<BT>::BlockKeyT; 845 using FunctionT = typename bfi_detail::TypeMap<BT>::FunctionT; 846 using BranchProbabilityInfoT = 847 typename bfi_detail::TypeMap<BT>::BranchProbabilityInfoT; 848 using LoopT = typename bfi_detail::TypeMap<BT>::LoopT; 849 using LoopInfoT = typename bfi_detail::TypeMap<BT>::LoopInfoT; 850 using Successor = GraphTraits<const BlockT *>; 851 using Predecessor = GraphTraits<Inverse<const BlockT *>>; 852 using BFICallbackVH = 853 bfi_detail::BFICallbackVH<BlockT, BlockFrequencyInfoImpl>; 854 855 const BranchProbabilityInfoT *BPI = nullptr; 856 const LoopInfoT *LI = nullptr; 857 const FunctionT *F = nullptr; 858 859 // All blocks in reverse postorder. 860 std::vector<const BlockT *> RPOT; 861 DenseMap<BlockKeyT, std::pair<BlockNode, BFICallbackVH>> Nodes; 862 863 using rpot_iterator = typename std::vector<const BlockT *>::const_iterator; 864 865 rpot_iterator rpot_begin() const { return RPOT.begin(); } 866 rpot_iterator rpot_end() const { return RPOT.end(); } 867 868 size_t getIndex(const rpot_iterator &I) const { return I - rpot_begin(); } 869 870 BlockNode getNode(const rpot_iterator &I) const { 871 return BlockNode(getIndex(I)); 872 } 873 874 BlockNode getNode(const BlockT *BB) const { return Nodes.lookup(BB).first; } 875 876 const BlockT *getBlock(const BlockNode &Node) const { 877 assert(Node.Index < RPOT.size()); 878 return RPOT[Node.Index]; 879 } 880 881 /// Run (and save) a post-order traversal. 882 /// 883 /// Saves a reverse post-order traversal of all the nodes in \a F. 884 void initializeRPOT(); 885 886 /// Initialize loop data. 887 /// 888 /// Build up \a Loops using \a LoopInfo. \a LoopInfo gives us a mapping from 889 /// each block to the deepest loop it's in, but we need the inverse. For each 890 /// loop, we store in reverse post-order its "immediate" members, defined as 891 /// the header, the headers of immediate sub-loops, and all other blocks in 892 /// the loop that are not in sub-loops. 893 void initializeLoops(); 894 895 /// Propagate to a block's successors. 896 /// 897 /// In the context of distributing mass through \c OuterLoop, divide the mass 898 /// currently assigned to \c Node between its successors. 899 /// 900 /// \return \c true unless there's an irreducible backedge. 901 bool propagateMassToSuccessors(LoopData *OuterLoop, const BlockNode &Node); 902 903 /// Compute mass in a particular loop. 904 /// 905 /// Assign mass to \c Loop's header, and then for each block in \c Loop in 906 /// reverse post-order, distribute mass to its successors. Only visits nodes 907 /// that have not been packaged into sub-loops. 908 /// 909 /// \pre \a computeMassInLoop() has been called for each subloop of \c Loop. 910 /// \return \c true unless there's an irreducible backedge. 911 bool computeMassInLoop(LoopData &Loop); 912 913 /// Try to compute mass in the top-level function. 914 /// 915 /// Assign mass to the entry block, and then for each block in reverse 916 /// post-order, distribute mass to its successors. Skips nodes that have 917 /// been packaged into loops. 918 /// 919 /// \pre \a computeMassInLoops() has been called. 920 /// \return \c true unless there's an irreducible backedge. 921 bool tryToComputeMassInFunction(); 922 923 /// Compute mass in (and package up) irreducible SCCs. 924 /// 925 /// Find the irreducible SCCs in \c OuterLoop, add them to \a Loops (in front 926 /// of \c Insert), and call \a computeMassInLoop() on each of them. 927 /// 928 /// If \c OuterLoop is \c nullptr, it refers to the top-level function. 929 /// 930 /// \pre \a computeMassInLoop() has been called for each subloop of \c 931 /// OuterLoop. 932 /// \pre \c Insert points at the last loop successfully processed by \a 933 /// computeMassInLoop(). 934 /// \pre \c OuterLoop has irreducible SCCs. 935 void computeIrreducibleMass(LoopData *OuterLoop, 936 std::list<LoopData>::iterator Insert); 937 938 /// Compute mass in all loops. 939 /// 940 /// For each loop bottom-up, call \a computeMassInLoop(). 941 /// 942 /// \a computeMassInLoop() aborts (and returns \c false) on loops that 943 /// contain a irreducible sub-SCCs. Use \a computeIrreducibleMass() and then 944 /// re-enter \a computeMassInLoop(). 945 /// 946 /// \post \a computeMassInLoop() has returned \c true for every loop. 947 void computeMassInLoops(); 948 949 /// Compute mass in the top-level function. 950 /// 951 /// Uses \a tryToComputeMassInFunction() and \a computeIrreducibleMass() to 952 /// compute mass in the top-level function. 953 /// 954 /// \post \a tryToComputeMassInFunction() has returned \c true. 955 void computeMassInFunction(); 956 957 std::string getBlockName(const BlockNode &Node) const override { 958 return bfi_detail::getBlockName(getBlock(Node)); 959 } 960 961 /// The current implementation for computing relative block frequencies does 962 /// not handle correctly control-flow graphs containing irreducible loops. To 963 /// resolve the problem, we apply a post-processing step, which iteratively 964 /// updates block frequencies based on the frequencies of their predesessors. 965 /// This corresponds to finding the stationary point of the Markov chain by 966 /// an iterative method aka "PageRank computation". 967 /// The algorithm takes at most O(|E| * IterativeBFIMaxIterations) steps but 968 /// typically converges faster. 969 /// 970 /// Decide whether we want to apply iterative inference for a given function. 971 bool needIterativeInference() const; 972 973 /// Apply an iterative post-processing to infer correct counts for irr loops. 974 void applyIterativeInference(); 975 976 using ProbMatrixType = std::vector<std::vector<std::pair<size_t, Scaled64>>>; 977 978 /// Run iterative inference for a probability matrix and initial frequencies. 979 void iterativeInference(const ProbMatrixType &ProbMatrix, 980 std::vector<Scaled64> &Freq) const; 981 982 /// Find all blocks to apply inference on, that is, reachable from the entry 983 /// and backward reachable from exists along edges with positive probability. 984 void findReachableBlocks(std::vector<const BlockT *> &Blocks) const; 985 986 /// Build a matrix of probabilities with transitions (edges) between the 987 /// blocks: ProbMatrix[I] holds pairs (J, P), where Pr[J -> I | J] = P 988 void initTransitionProbabilities( 989 const std::vector<const BlockT *> &Blocks, 990 const DenseMap<const BlockT *, size_t> &BlockIndex, 991 ProbMatrixType &ProbMatrix) const; 992 993 #ifndef NDEBUG 994 /// Compute the discrepancy between current block frequencies and the 995 /// probability matrix. 996 Scaled64 discrepancy(const ProbMatrixType &ProbMatrix, 997 const std::vector<Scaled64> &Freq) const; 998 #endif 999 1000 public: 1001 BlockFrequencyInfoImpl() = default; 1002 1003 const FunctionT *getFunction() const { return F; } 1004 1005 void calculate(const FunctionT &F, const BranchProbabilityInfoT &BPI, 1006 const LoopInfoT &LI); 1007 1008 using BlockFrequencyInfoImplBase::getEntryFreq; 1009 1010 BlockFrequency getBlockFreq(const BlockT *BB) const { 1011 return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB)); 1012 } 1013 1014 std::optional<uint64_t> 1015 getBlockProfileCount(const Function &F, const BlockT *BB, 1016 bool AllowSynthetic = false) const { 1017 return BlockFrequencyInfoImplBase::getBlockProfileCount(F, getNode(BB), 1018 AllowSynthetic); 1019 } 1020 1021 std::optional<uint64_t> 1022 getProfileCountFromFreq(const Function &F, BlockFrequency Freq, 1023 bool AllowSynthetic = false) const { 1024 return BlockFrequencyInfoImplBase::getProfileCountFromFreq(F, Freq, 1025 AllowSynthetic); 1026 } 1027 1028 bool isIrrLoopHeader(const BlockT *BB) { 1029 return BlockFrequencyInfoImplBase::isIrrLoopHeader(getNode(BB)); 1030 } 1031 1032 void setBlockFreq(const BlockT *BB, BlockFrequency Freq); 1033 1034 void forgetBlock(const BlockT *BB) { 1035 // We don't erase corresponding items from `Freqs`, `RPOT` and other to 1036 // avoid invalidating indices. Doing so would have saved some memory, but 1037 // it's not worth it. 1038 Nodes.erase(BB); 1039 } 1040 1041 Scaled64 getFloatingBlockFreq(const BlockT *BB) const { 1042 return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB)); 1043 } 1044 1045 const BranchProbabilityInfoT &getBPI() const { return *BPI; } 1046 1047 /// Print the frequencies for the current function. 1048 /// 1049 /// Prints the frequencies for the blocks in the current function. 1050 /// 1051 /// Blocks are printed in the natural iteration order of the function, rather 1052 /// than reverse post-order. This provides two advantages: writing -analyze 1053 /// tests is easier (since blocks come out in source order), and even 1054 /// unreachable blocks are printed. 1055 /// 1056 /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so 1057 /// we need to override it here. 1058 raw_ostream &print(raw_ostream &OS) const override; 1059 1060 using BlockFrequencyInfoImplBase::dump; 1061 1062 void verifyMatch(BlockFrequencyInfoImpl<BT> &Other) const; 1063 }; 1064 1065 namespace bfi_detail { 1066 1067 template <class BFIImplT> 1068 class BFICallbackVH<BasicBlock, BFIImplT> : public CallbackVH { 1069 BFIImplT *BFIImpl; 1070 1071 public: 1072 BFICallbackVH() = default; 1073 1074 BFICallbackVH(const BasicBlock *BB, BFIImplT *BFIImpl) 1075 : CallbackVH(BB), BFIImpl(BFIImpl) {} 1076 1077 virtual ~BFICallbackVH() = default; 1078 1079 void deleted() override { 1080 BFIImpl->forgetBlock(cast<BasicBlock>(getValPtr())); 1081 } 1082 }; 1083 1084 /// Dummy implementation since MachineBasicBlocks aren't Values, so ValueHandles 1085 /// don't apply to them. 1086 template <class BFIImplT> 1087 class BFICallbackVH<MachineBasicBlock, BFIImplT> { 1088 public: 1089 BFICallbackVH() = default; 1090 BFICallbackVH(const MachineBasicBlock *, BFIImplT *) {} 1091 }; 1092 1093 } // end namespace bfi_detail 1094 1095 template <class BT> 1096 void BlockFrequencyInfoImpl<BT>::calculate(const FunctionT &F, 1097 const BranchProbabilityInfoT &BPI, 1098 const LoopInfoT &LI) { 1099 // Save the parameters. 1100 this->BPI = &BPI; 1101 this->LI = &LI; 1102 this->F = &F; 1103 1104 // Clean up left-over data structures. 1105 BlockFrequencyInfoImplBase::clear(); 1106 RPOT.clear(); 1107 Nodes.clear(); 1108 1109 // Initialize. 1110 LLVM_DEBUG(dbgs() << "\nblock-frequency: " << F.getName() 1111 << "\n=================" 1112 << std::string(F.getName().size(), '=') << "\n"); 1113 initializeRPOT(); 1114 initializeLoops(); 1115 1116 // Visit loops in post-order to find the local mass distribution, and then do 1117 // the full function. 1118 computeMassInLoops(); 1119 computeMassInFunction(); 1120 unwrapLoops(); 1121 // Apply a post-processing step improving computed frequencies for functions 1122 // with irreducible loops. 1123 if (needIterativeInference()) 1124 applyIterativeInference(); 1125 finalizeMetrics(); 1126 1127 if (CheckBFIUnknownBlockQueries) { 1128 // To detect BFI queries for unknown blocks, add entries for unreachable 1129 // blocks, if any. This is to distinguish between known/existing unreachable 1130 // blocks and unknown blocks. 1131 for (const BlockT &BB : F) 1132 if (!Nodes.count(&BB)) 1133 setBlockFreq(&BB, BlockFrequency()); 1134 } 1135 } 1136 1137 template <class BT> 1138 void BlockFrequencyInfoImpl<BT>::setBlockFreq(const BlockT *BB, 1139 BlockFrequency Freq) { 1140 auto [It, Inserted] = Nodes.try_emplace(BB); 1141 if (!Inserted) 1142 BlockFrequencyInfoImplBase::setBlockFreq(It->second.first, Freq); 1143 else { 1144 // If BB is a newly added block after BFI is done, we need to create a new 1145 // BlockNode for it assigned with a new index. The index can be determined 1146 // by the size of Freqs. 1147 BlockNode NewNode(Freqs.size()); 1148 It->second = {NewNode, BFICallbackVH(BB, this)}; 1149 Freqs.emplace_back(); 1150 BlockFrequencyInfoImplBase::setBlockFreq(NewNode, Freq); 1151 } 1152 } 1153 1154 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() { 1155 const BlockT *Entry = &F->front(); 1156 RPOT.reserve(F->size()); 1157 std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT)); 1158 std::reverse(RPOT.begin(), RPOT.end()); 1159 1160 assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() && 1161 "More nodes in function than Block Frequency Info supports"); 1162 1163 LLVM_DEBUG(dbgs() << "reverse-post-order-traversal\n"); 1164 for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) { 1165 BlockNode Node = getNode(I); 1166 LLVM_DEBUG(dbgs() << " - " << getIndex(I) << ": " << getBlockName(Node) 1167 << "\n"); 1168 Nodes[*I] = {Node, BFICallbackVH(*I, this)}; 1169 } 1170 1171 Working.reserve(RPOT.size()); 1172 for (size_t Index = 0; Index < RPOT.size(); ++Index) 1173 Working.emplace_back(Index); 1174 Freqs.resize(RPOT.size()); 1175 } 1176 1177 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() { 1178 LLVM_DEBUG(dbgs() << "loop-detection\n"); 1179 if (LI->empty()) 1180 return; 1181 1182 // Visit loops top down and assign them an index. 1183 std::deque<std::pair<const LoopT *, LoopData *>> Q; 1184 for (const LoopT *L : *LI) 1185 Q.emplace_back(L, nullptr); 1186 while (!Q.empty()) { 1187 const LoopT *Loop = Q.front().first; 1188 LoopData *Parent = Q.front().second; 1189 Q.pop_front(); 1190 1191 BlockNode Header = getNode(Loop->getHeader()); 1192 assert(Header.isValid()); 1193 1194 Loops.emplace_back(Parent, Header); 1195 Working[Header.Index].Loop = &Loops.back(); 1196 LLVM_DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n"); 1197 1198 for (const LoopT *L : *Loop) 1199 Q.emplace_back(L, &Loops.back()); 1200 } 1201 1202 // Visit nodes in reverse post-order and add them to their deepest containing 1203 // loop. 1204 for (size_t Index = 0; Index < RPOT.size(); ++Index) { 1205 // Loop headers have already been mostly mapped. 1206 if (Working[Index].isLoopHeader()) { 1207 LoopData *ContainingLoop = Working[Index].getContainingLoop(); 1208 if (ContainingLoop) 1209 ContainingLoop->Nodes.push_back(Index); 1210 continue; 1211 } 1212 1213 const LoopT *Loop = LI->getLoopFor(RPOT[Index]); 1214 if (!Loop) 1215 continue; 1216 1217 // Add this node to its containing loop's member list. 1218 BlockNode Header = getNode(Loop->getHeader()); 1219 assert(Header.isValid()); 1220 const auto &HeaderData = Working[Header.Index]; 1221 assert(HeaderData.isLoopHeader()); 1222 1223 Working[Index].Loop = HeaderData.Loop; 1224 HeaderData.Loop->Nodes.push_back(Index); 1225 LLVM_DEBUG(dbgs() << " - loop = " << getBlockName(Header) 1226 << ": member = " << getBlockName(Index) << "\n"); 1227 } 1228 } 1229 1230 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() { 1231 // Visit loops with the deepest first, and the top-level loops last. 1232 for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L) { 1233 if (computeMassInLoop(*L)) 1234 continue; 1235 auto Next = std::next(L); 1236 computeIrreducibleMass(&*L, L.base()); 1237 L = std::prev(Next); 1238 if (computeMassInLoop(*L)) 1239 continue; 1240 llvm_unreachable("unhandled irreducible control flow"); 1241 } 1242 } 1243 1244 template <class BT> 1245 bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) { 1246 // Compute mass in loop. 1247 LLVM_DEBUG(dbgs() << "compute-mass-in-loop: " << getLoopName(Loop) << "\n"); 1248 1249 if (Loop.isIrreducible()) { 1250 LLVM_DEBUG(dbgs() << "isIrreducible = true\n"); 1251 Distribution Dist; 1252 unsigned NumHeadersWithWeight = 0; 1253 std::optional<uint64_t> MinHeaderWeight; 1254 DenseSet<uint32_t> HeadersWithoutWeight; 1255 HeadersWithoutWeight.reserve(Loop.NumHeaders); 1256 for (uint32_t H = 0; H < Loop.NumHeaders; ++H) { 1257 auto &HeaderNode = Loop.Nodes[H]; 1258 const BlockT *Block = getBlock(HeaderNode); 1259 IsIrrLoopHeader.set(Loop.Nodes[H].Index); 1260 std::optional<uint64_t> HeaderWeight = Block->getIrrLoopHeaderWeight(); 1261 if (!HeaderWeight) { 1262 LLVM_DEBUG(dbgs() << "Missing irr loop header metadata on " 1263 << getBlockName(HeaderNode) << "\n"); 1264 HeadersWithoutWeight.insert(H); 1265 continue; 1266 } 1267 LLVM_DEBUG(dbgs() << getBlockName(HeaderNode) 1268 << " has irr loop header weight " << *HeaderWeight 1269 << "\n"); 1270 NumHeadersWithWeight++; 1271 uint64_t HeaderWeightValue = *HeaderWeight; 1272 if (!MinHeaderWeight || HeaderWeightValue < MinHeaderWeight) 1273 MinHeaderWeight = HeaderWeightValue; 1274 if (HeaderWeightValue) { 1275 Dist.addLocal(HeaderNode, HeaderWeightValue); 1276 } 1277 } 1278 // As a heuristic, if some headers don't have a weight, give them the 1279 // minimum weight seen (not to disrupt the existing trends too much by 1280 // using a weight that's in the general range of the other headers' weights, 1281 // and the minimum seems to perform better than the average.) 1282 // FIXME: better update in the passes that drop the header weight. 1283 // If no headers have a weight, give them even weight (use weight 1). 1284 if (!MinHeaderWeight) 1285 MinHeaderWeight = 1; 1286 for (uint32_t H : HeadersWithoutWeight) { 1287 auto &HeaderNode = Loop.Nodes[H]; 1288 assert(!getBlock(HeaderNode)->getIrrLoopHeaderWeight() && 1289 "Shouldn't have a weight metadata"); 1290 uint64_t MinWeight = *MinHeaderWeight; 1291 LLVM_DEBUG(dbgs() << "Giving weight " << MinWeight << " to " 1292 << getBlockName(HeaderNode) << "\n"); 1293 if (MinWeight) 1294 Dist.addLocal(HeaderNode, MinWeight); 1295 } 1296 distributeIrrLoopHeaderMass(Dist); 1297 for (const BlockNode &M : Loop.Nodes) 1298 if (!propagateMassToSuccessors(&Loop, M)) 1299 llvm_unreachable("unhandled irreducible control flow"); 1300 if (NumHeadersWithWeight == 0) 1301 // No headers have a metadata. Adjust header mass. 1302 adjustLoopHeaderMass(Loop); 1303 } else { 1304 Working[Loop.getHeader().Index].getMass() = BlockMass::getFull(); 1305 if (!propagateMassToSuccessors(&Loop, Loop.getHeader())) 1306 llvm_unreachable("irreducible control flow to loop header!?"); 1307 for (const BlockNode &M : Loop.members()) 1308 if (!propagateMassToSuccessors(&Loop, M)) 1309 // Irreducible backedge. 1310 return false; 1311 } 1312 1313 computeLoopScale(Loop); 1314 packageLoop(Loop); 1315 return true; 1316 } 1317 1318 template <class BT> 1319 bool BlockFrequencyInfoImpl<BT>::tryToComputeMassInFunction() { 1320 // Compute mass in function. 1321 LLVM_DEBUG(dbgs() << "compute-mass-in-function\n"); 1322 assert(!Working.empty() && "no blocks in function"); 1323 assert(!Working[0].isLoopHeader() && "entry block is a loop header"); 1324 1325 Working[0].getMass() = BlockMass::getFull(); 1326 for (rpot_iterator I = rpot_begin(), IE = rpot_end(); I != IE; ++I) { 1327 // Check for nodes that have been packaged. 1328 BlockNode Node = getNode(I); 1329 if (Working[Node.Index].isPackaged()) 1330 continue; 1331 1332 if (!propagateMassToSuccessors(nullptr, Node)) 1333 return false; 1334 } 1335 return true; 1336 } 1337 1338 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() { 1339 if (tryToComputeMassInFunction()) 1340 return; 1341 computeIrreducibleMass(nullptr, Loops.begin()); 1342 if (tryToComputeMassInFunction()) 1343 return; 1344 llvm_unreachable("unhandled irreducible control flow"); 1345 } 1346 1347 template <class BT> 1348 bool BlockFrequencyInfoImpl<BT>::needIterativeInference() const { 1349 if (!UseIterativeBFIInference) 1350 return false; 1351 if (!F->getFunction().hasProfileData()) 1352 return false; 1353 // Apply iterative inference only if the function contains irreducible loops; 1354 // otherwise, computed block frequencies are reasonably correct. 1355 for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L) { 1356 if (L->isIrreducible()) 1357 return true; 1358 } 1359 return false; 1360 } 1361 1362 template <class BT> void BlockFrequencyInfoImpl<BT>::applyIterativeInference() { 1363 // Extract blocks for processing: a block is considered for inference iff it 1364 // can be reached from the entry by edges with a positive probability. 1365 // Non-processed blocks are assigned with the zero frequency and are ignored 1366 // in the computation 1367 std::vector<const BlockT *> ReachableBlocks; 1368 findReachableBlocks(ReachableBlocks); 1369 if (ReachableBlocks.empty()) 1370 return; 1371 1372 // The map is used to index successors/predecessors of reachable blocks in 1373 // the ReachableBlocks vector 1374 DenseMap<const BlockT *, size_t> BlockIndex; 1375 // Extract initial frequencies for the reachable blocks 1376 auto Freq = std::vector<Scaled64>(ReachableBlocks.size()); 1377 Scaled64 SumFreq; 1378 for (size_t I = 0; I < ReachableBlocks.size(); I++) { 1379 const BlockT *BB = ReachableBlocks[I]; 1380 BlockIndex[BB] = I; 1381 Freq[I] = getFloatingBlockFreq(BB); 1382 SumFreq += Freq[I]; 1383 } 1384 assert(!SumFreq.isZero() && "empty initial block frequencies"); 1385 1386 LLVM_DEBUG(dbgs() << "Applying iterative inference for " << F->getName() 1387 << " with " << ReachableBlocks.size() << " blocks\n"); 1388 1389 // Normalizing frequencies so they sum up to 1.0 1390 for (auto &Value : Freq) { 1391 Value /= SumFreq; 1392 } 1393 1394 // Setting up edge probabilities using sparse matrix representation: 1395 // ProbMatrix[I] holds a vector of pairs (J, P) where Pr[J -> I | J] = P 1396 ProbMatrixType ProbMatrix; 1397 initTransitionProbabilities(ReachableBlocks, BlockIndex, ProbMatrix); 1398 1399 // Run the propagation 1400 iterativeInference(ProbMatrix, Freq); 1401 1402 // Assign computed frequency values 1403 for (const BlockT &BB : *F) { 1404 auto Node = getNode(&BB); 1405 if (!Node.isValid()) 1406 continue; 1407 if (auto It = BlockIndex.find(&BB); It != BlockIndex.end()) 1408 Freqs[Node.Index].Scaled = Freq[It->second]; 1409 else 1410 Freqs[Node.Index].Scaled = Scaled64::getZero(); 1411 } 1412 } 1413 1414 template <class BT> 1415 void BlockFrequencyInfoImpl<BT>::iterativeInference( 1416 const ProbMatrixType &ProbMatrix, std::vector<Scaled64> &Freq) const { 1417 assert(0.0 < IterativeBFIPrecision && IterativeBFIPrecision < 1.0 && 1418 "incorrectly specified precision"); 1419 // Convert double precision to Scaled64 1420 const auto Precision = 1421 Scaled64::getInverse(static_cast<uint64_t>(1.0 / IterativeBFIPrecision)); 1422 const size_t MaxIterations = IterativeBFIMaxIterationsPerBlock * Freq.size(); 1423 1424 #ifndef NDEBUG 1425 LLVM_DEBUG(dbgs() << " Initial discrepancy = " 1426 << discrepancy(ProbMatrix, Freq).toString() << "\n"); 1427 #endif 1428 1429 // Successors[I] holds unique sucessors of the I-th block 1430 auto Successors = std::vector<std::vector<size_t>>(Freq.size()); 1431 for (size_t I = 0; I < Freq.size(); I++) { 1432 for (const auto &Jump : ProbMatrix[I]) { 1433 Successors[Jump.first].push_back(I); 1434 } 1435 } 1436 1437 // To speedup computation, we maintain a set of "active" blocks whose 1438 // frequencies need to be updated based on the incoming edges. 1439 // The set is dynamic and changes after every update. Initially all blocks 1440 // with a positive frequency are active 1441 auto IsActive = BitVector(Freq.size(), false); 1442 std::queue<size_t> ActiveSet; 1443 for (size_t I = 0; I < Freq.size(); I++) { 1444 if (Freq[I] > 0) { 1445 ActiveSet.push(I); 1446 IsActive[I] = true; 1447 } 1448 } 1449 1450 // Iterate over the blocks propagating frequencies 1451 size_t It = 0; 1452 while (It++ < MaxIterations && !ActiveSet.empty()) { 1453 size_t I = ActiveSet.front(); 1454 ActiveSet.pop(); 1455 IsActive[I] = false; 1456 1457 // Compute a new frequency for the block: NewFreq := Freq \times ProbMatrix. 1458 // A special care is taken for self-edges that needs to be scaled by 1459 // (1.0 - SelfProb), where SelfProb is the sum of probabilities on the edges 1460 Scaled64 NewFreq; 1461 Scaled64 OneMinusSelfProb = Scaled64::getOne(); 1462 for (const auto &Jump : ProbMatrix[I]) { 1463 if (Jump.first == I) { 1464 OneMinusSelfProb -= Jump.second; 1465 } else { 1466 NewFreq += Freq[Jump.first] * Jump.second; 1467 } 1468 } 1469 if (OneMinusSelfProb != Scaled64::getOne()) 1470 NewFreq /= OneMinusSelfProb; 1471 1472 // If the block's frequency has changed enough, then 1473 // make sure the block and its successors are in the active set 1474 auto Change = Freq[I] >= NewFreq ? Freq[I] - NewFreq : NewFreq - Freq[I]; 1475 if (Change > Precision) { 1476 ActiveSet.push(I); 1477 IsActive[I] = true; 1478 for (size_t Succ : Successors[I]) { 1479 if (!IsActive[Succ]) { 1480 ActiveSet.push(Succ); 1481 IsActive[Succ] = true; 1482 } 1483 } 1484 } 1485 1486 // Update the frequency for the block 1487 Freq[I] = NewFreq; 1488 } 1489 1490 LLVM_DEBUG(dbgs() << " Completed " << It << " inference iterations" 1491 << format(" (%0.0f per block)", double(It) / Freq.size()) 1492 << "\n"); 1493 #ifndef NDEBUG 1494 LLVM_DEBUG(dbgs() << " Final discrepancy = " 1495 << discrepancy(ProbMatrix, Freq).toString() << "\n"); 1496 #endif 1497 } 1498 1499 template <class BT> 1500 void BlockFrequencyInfoImpl<BT>::findReachableBlocks( 1501 std::vector<const BlockT *> &Blocks) const { 1502 // Find all blocks to apply inference on, that is, reachable from the entry 1503 // along edges with non-zero probablities 1504 std::queue<const BlockT *> Queue; 1505 SmallPtrSet<const BlockT *, 8> Reachable; 1506 const BlockT *Entry = &F->front(); 1507 Queue.push(Entry); 1508 Reachable.insert(Entry); 1509 while (!Queue.empty()) { 1510 const BlockT *SrcBB = Queue.front(); 1511 Queue.pop(); 1512 for (const BlockT *DstBB : children<const BlockT *>(SrcBB)) { 1513 auto EP = BPI->getEdgeProbability(SrcBB, DstBB); 1514 if (EP.isZero()) 1515 continue; 1516 if (Reachable.insert(DstBB).second) 1517 Queue.push(DstBB); 1518 } 1519 } 1520 1521 // Find all blocks to apply inference on, that is, backward reachable from 1522 // the entry along (backward) edges with non-zero probablities 1523 SmallPtrSet<const BlockT *, 8> InverseReachable; 1524 for (const BlockT &BB : *F) { 1525 // An exit block is a block without any successors 1526 bool HasSucc = !llvm::children<const BlockT *>(&BB).empty(); 1527 if (!HasSucc && Reachable.count(&BB)) { 1528 Queue.push(&BB); 1529 InverseReachable.insert(&BB); 1530 } 1531 } 1532 while (!Queue.empty()) { 1533 const BlockT *SrcBB = Queue.front(); 1534 Queue.pop(); 1535 for (const BlockT *DstBB : inverse_children<const BlockT *>(SrcBB)) { 1536 auto EP = BPI->getEdgeProbability(DstBB, SrcBB); 1537 if (EP.isZero()) 1538 continue; 1539 if (InverseReachable.insert(DstBB).second) 1540 Queue.push(DstBB); 1541 } 1542 } 1543 1544 // Collect the result 1545 Blocks.reserve(F->size()); 1546 for (const BlockT &BB : *F) { 1547 if (Reachable.count(&BB) && InverseReachable.count(&BB)) { 1548 Blocks.push_back(&BB); 1549 } 1550 } 1551 } 1552 1553 template <class BT> 1554 void BlockFrequencyInfoImpl<BT>::initTransitionProbabilities( 1555 const std::vector<const BlockT *> &Blocks, 1556 const DenseMap<const BlockT *, size_t> &BlockIndex, 1557 ProbMatrixType &ProbMatrix) const { 1558 const size_t NumBlocks = Blocks.size(); 1559 auto Succs = std::vector<std::vector<std::pair<size_t, Scaled64>>>(NumBlocks); 1560 auto SumProb = std::vector<Scaled64>(NumBlocks); 1561 1562 // Find unique successors and corresponding probabilities for every block 1563 for (size_t Src = 0; Src < NumBlocks; Src++) { 1564 const BlockT *BB = Blocks[Src]; 1565 SmallPtrSet<const BlockT *, 2> UniqueSuccs; 1566 for (const auto SI : children<const BlockT *>(BB)) { 1567 // Ignore cold blocks 1568 auto BlockIndexIt = BlockIndex.find(SI); 1569 if (BlockIndexIt == BlockIndex.end()) 1570 continue; 1571 // Ignore parallel edges between BB and SI blocks 1572 if (!UniqueSuccs.insert(SI).second) 1573 continue; 1574 // Ignore jumps with zero probability 1575 auto EP = BPI->getEdgeProbability(BB, SI); 1576 if (EP.isZero()) 1577 continue; 1578 1579 auto EdgeProb = 1580 Scaled64::getFraction(EP.getNumerator(), EP.getDenominator()); 1581 size_t Dst = BlockIndexIt->second; 1582 Succs[Src].push_back(std::make_pair(Dst, EdgeProb)); 1583 SumProb[Src] += EdgeProb; 1584 } 1585 } 1586 1587 // Add transitions for every jump with positive branch probability 1588 ProbMatrix = ProbMatrixType(NumBlocks); 1589 for (size_t Src = 0; Src < NumBlocks; Src++) { 1590 // Ignore blocks w/o successors 1591 if (Succs[Src].empty()) 1592 continue; 1593 1594 assert(!SumProb[Src].isZero() && "Zero sum probability of non-exit block"); 1595 for (auto &Jump : Succs[Src]) { 1596 size_t Dst = Jump.first; 1597 Scaled64 Prob = Jump.second; 1598 ProbMatrix[Dst].push_back(std::make_pair(Src, Prob / SumProb[Src])); 1599 } 1600 } 1601 1602 // Add transitions from sinks to the source 1603 size_t EntryIdx = BlockIndex.find(&F->front())->second; 1604 for (size_t Src = 0; Src < NumBlocks; Src++) { 1605 if (Succs[Src].empty()) { 1606 ProbMatrix[EntryIdx].push_back(std::make_pair(Src, Scaled64::getOne())); 1607 } 1608 } 1609 } 1610 1611 #ifndef NDEBUG 1612 template <class BT> 1613 BlockFrequencyInfoImplBase::Scaled64 BlockFrequencyInfoImpl<BT>::discrepancy( 1614 const ProbMatrixType &ProbMatrix, const std::vector<Scaled64> &Freq) const { 1615 assert(Freq[0] > 0 && "Incorrectly computed frequency of the entry block"); 1616 Scaled64 Discrepancy; 1617 for (size_t I = 0; I < ProbMatrix.size(); I++) { 1618 Scaled64 Sum; 1619 for (const auto &Jump : ProbMatrix[I]) { 1620 Sum += Freq[Jump.first] * Jump.second; 1621 } 1622 Discrepancy += Freq[I] >= Sum ? Freq[I] - Sum : Sum - Freq[I]; 1623 } 1624 // Normalizing by the frequency of the entry block 1625 return Discrepancy / Freq[0]; 1626 } 1627 #endif 1628 1629 template <class BT> 1630 void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass( 1631 LoopData *OuterLoop, std::list<LoopData>::iterator Insert) { 1632 LLVM_DEBUG(dbgs() << "analyze-irreducible-in-"; 1633 if (OuterLoop) dbgs() 1634 << "loop: " << getLoopName(*OuterLoop) << "\n"; 1635 else dbgs() << "function\n"); 1636 1637 using namespace bfi_detail; 1638 1639 auto addBlockEdges = [&](IrreducibleGraph &G, IrreducibleGraph::IrrNode &Irr, 1640 const LoopData *OuterLoop) { 1641 const BlockT *BB = RPOT[Irr.Node.Index]; 1642 for (const auto *Succ : children<const BlockT *>(BB)) 1643 G.addEdge(Irr, getNode(Succ), OuterLoop); 1644 }; 1645 IrreducibleGraph G(*this, OuterLoop, addBlockEdges); 1646 1647 for (auto &L : analyzeIrreducible(G, OuterLoop, Insert)) 1648 computeMassInLoop(L); 1649 1650 if (!OuterLoop) 1651 return; 1652 updateLoopWithIrreducible(*OuterLoop); 1653 } 1654 1655 // A helper function that converts a branch probability into weight. 1656 inline uint32_t getWeightFromBranchProb(const BranchProbability Prob) { 1657 return Prob.getNumerator(); 1658 } 1659 1660 template <class BT> 1661 bool 1662 BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop, 1663 const BlockNode &Node) { 1664 LLVM_DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n"); 1665 // Calculate probability for successors. 1666 Distribution Dist; 1667 if (auto *Loop = Working[Node.Index].getPackagedLoop()) { 1668 assert(Loop != OuterLoop && "Cannot propagate mass in a packaged loop"); 1669 if (!addLoopSuccessorsToDist(OuterLoop, *Loop, Dist)) 1670 // Irreducible backedge. 1671 return false; 1672 } else { 1673 const BlockT *BB = getBlock(Node); 1674 for (auto SI = GraphTraits<const BlockT *>::child_begin(BB), 1675 SE = GraphTraits<const BlockT *>::child_end(BB); 1676 SI != SE; ++SI) 1677 if (!addToDist( 1678 Dist, OuterLoop, Node, getNode(*SI), 1679 getWeightFromBranchProb(BPI->getEdgeProbability(BB, SI)))) 1680 // Irreducible backedge. 1681 return false; 1682 } 1683 1684 // Distribute mass to successors, saving exit and backedge data in the 1685 // loop header. 1686 distributeMass(Node, OuterLoop, Dist); 1687 return true; 1688 } 1689 1690 template <class BT> 1691 raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const { 1692 if (!F) 1693 return OS; 1694 OS << "block-frequency-info: " << F->getName() << "\n"; 1695 for (const BlockT &BB : *F) { 1696 OS << " - " << bfi_detail::getBlockName(&BB) << ": float = "; 1697 getFloatingBlockFreq(&BB).print(OS, 5) 1698 << ", int = " << getBlockFreq(&BB).getFrequency(); 1699 if (std::optional<uint64_t> ProfileCount = 1700 BlockFrequencyInfoImplBase::getBlockProfileCount( 1701 F->getFunction(), getNode(&BB))) 1702 OS << ", count = " << *ProfileCount; 1703 if (std::optional<uint64_t> IrrLoopHeaderWeight = 1704 BB.getIrrLoopHeaderWeight()) 1705 OS << ", irr_loop_header_weight = " << *IrrLoopHeaderWeight; 1706 OS << "\n"; 1707 } 1708 1709 // Add an extra newline for readability. 1710 OS << "\n"; 1711 return OS; 1712 } 1713 1714 template <class BT> 1715 void BlockFrequencyInfoImpl<BT>::verifyMatch( 1716 BlockFrequencyInfoImpl<BT> &Other) const { 1717 bool Match = true; 1718 DenseMap<const BlockT *, BlockNode> ValidNodes; 1719 DenseMap<const BlockT *, BlockNode> OtherValidNodes; 1720 for (auto &Entry : Nodes) { 1721 const BlockT *BB = Entry.first; 1722 if (BB) { 1723 ValidNodes[BB] = Entry.second.first; 1724 } 1725 } 1726 for (auto &Entry : Other.Nodes) { 1727 const BlockT *BB = Entry.first; 1728 if (BB) { 1729 OtherValidNodes[BB] = Entry.second.first; 1730 } 1731 } 1732 unsigned NumValidNodes = ValidNodes.size(); 1733 unsigned NumOtherValidNodes = OtherValidNodes.size(); 1734 if (NumValidNodes != NumOtherValidNodes) { 1735 Match = false; 1736 dbgs() << "Number of blocks mismatch: " << NumValidNodes << " vs " 1737 << NumOtherValidNodes << "\n"; 1738 } else { 1739 for (auto &Entry : ValidNodes) { 1740 const BlockT *BB = Entry.first; 1741 BlockNode Node = Entry.second; 1742 if (auto It = OtherValidNodes.find(BB); It != OtherValidNodes.end()) { 1743 BlockNode OtherNode = It->second; 1744 const auto &Freq = Freqs[Node.Index]; 1745 const auto &OtherFreq = Other.Freqs[OtherNode.Index]; 1746 if (Freq.Integer != OtherFreq.Integer) { 1747 Match = false; 1748 dbgs() << "Freq mismatch: " << bfi_detail::getBlockName(BB) << " " 1749 << Freq.Integer << " vs " << OtherFreq.Integer << "\n"; 1750 } 1751 } else { 1752 Match = false; 1753 dbgs() << "Block " << bfi_detail::getBlockName(BB) << " index " 1754 << Node.Index << " does not exist in Other.\n"; 1755 } 1756 } 1757 // If there's a valid node in OtherValidNodes that's not in ValidNodes, 1758 // either the above num check or the check on OtherValidNodes will fail. 1759 } 1760 if (!Match) { 1761 dbgs() << "This\n"; 1762 print(dbgs()); 1763 dbgs() << "Other\n"; 1764 Other.print(dbgs()); 1765 } 1766 assert(Match && "BFI mismatch"); 1767 } 1768 1769 // Graph trait base class for block frequency information graph 1770 // viewer. 1771 1772 enum GVDAGType { GVDT_None, GVDT_Fraction, GVDT_Integer, GVDT_Count }; 1773 1774 template <class BlockFrequencyInfoT, class BranchProbabilityInfoT> 1775 struct BFIDOTGraphTraitsBase : public DefaultDOTGraphTraits { 1776 using GTraits = GraphTraits<BlockFrequencyInfoT *>; 1777 using NodeRef = typename GTraits::NodeRef; 1778 using EdgeIter = typename GTraits::ChildIteratorType; 1779 using NodeIter = typename GTraits::nodes_iterator; 1780 1781 uint64_t MaxFrequency = 0; 1782 1783 explicit BFIDOTGraphTraitsBase(bool isSimple = false) 1784 : DefaultDOTGraphTraits(isSimple) {} 1785 1786 static StringRef getGraphName(const BlockFrequencyInfoT *G) { 1787 return G->getFunction()->getName(); 1788 } 1789 1790 std::string getNodeAttributes(NodeRef Node, const BlockFrequencyInfoT *Graph, 1791 unsigned HotPercentThreshold = 0) { 1792 std::string Result; 1793 if (!HotPercentThreshold) 1794 return Result; 1795 1796 // Compute MaxFrequency on the fly: 1797 if (!MaxFrequency) { 1798 for (NodeIter I = GTraits::nodes_begin(Graph), 1799 E = GTraits::nodes_end(Graph); 1800 I != E; ++I) { 1801 NodeRef N = *I; 1802 MaxFrequency = 1803 std::max(MaxFrequency, Graph->getBlockFreq(N).getFrequency()); 1804 } 1805 } 1806 BlockFrequency Freq = Graph->getBlockFreq(Node); 1807 BlockFrequency HotFreq = 1808 (BlockFrequency(MaxFrequency) * 1809 BranchProbability::getBranchProbability(HotPercentThreshold, 100)); 1810 1811 if (Freq < HotFreq) 1812 return Result; 1813 1814 raw_string_ostream OS(Result); 1815 OS << "color=\"red\""; 1816 OS.flush(); 1817 return Result; 1818 } 1819 1820 std::string getNodeLabel(NodeRef Node, const BlockFrequencyInfoT *Graph, 1821 GVDAGType GType, int layout_order = -1) { 1822 std::string Result; 1823 raw_string_ostream OS(Result); 1824 1825 if (layout_order != -1) 1826 OS << Node->getName() << "[" << layout_order << "] : "; 1827 else 1828 OS << Node->getName() << " : "; 1829 switch (GType) { 1830 case GVDT_Fraction: 1831 OS << printBlockFreq(*Graph, *Node); 1832 break; 1833 case GVDT_Integer: 1834 OS << Graph->getBlockFreq(Node).getFrequency(); 1835 break; 1836 case GVDT_Count: { 1837 auto Count = Graph->getBlockProfileCount(Node); 1838 if (Count) 1839 OS << *Count; 1840 else 1841 OS << "Unknown"; 1842 break; 1843 } 1844 case GVDT_None: 1845 llvm_unreachable("If we are not supposed to render a graph we should " 1846 "never reach this point."); 1847 } 1848 return Result; 1849 } 1850 1851 std::string getEdgeAttributes(NodeRef Node, EdgeIter EI, 1852 const BlockFrequencyInfoT *BFI, 1853 const BranchProbabilityInfoT *BPI, 1854 unsigned HotPercentThreshold = 0) { 1855 std::string Str; 1856 if (!BPI) 1857 return Str; 1858 1859 BranchProbability BP = BPI->getEdgeProbability(Node, EI); 1860 uint32_t N = BP.getNumerator(); 1861 uint32_t D = BP.getDenominator(); 1862 double Percent = 100.0 * N / D; 1863 raw_string_ostream OS(Str); 1864 OS << format("label=\"%.1f%%\"", Percent); 1865 1866 if (HotPercentThreshold) { 1867 BlockFrequency EFreq = BFI->getBlockFreq(Node) * BP; 1868 BlockFrequency HotFreq = BlockFrequency(MaxFrequency) * 1869 BranchProbability(HotPercentThreshold, 100); 1870 1871 if (EFreq >= HotFreq) { 1872 OS << ",color=\"red\""; 1873 } 1874 } 1875 1876 OS.flush(); 1877 return Str; 1878 } 1879 }; 1880 1881 } // end namespace llvm 1882 1883 #undef DEBUG_TYPE 1884 1885 #endif // LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H 1886