LLVM 24.0.0git
MachineBlockPlacement.cpp
Go to the documentation of this file.
1//===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===//
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 basic block placement transformations using the CFG
10// structure and branch probability estimates.
11//
12// The pass strives to preserve the structure of the CFG (that is, retain
13// a topological ordering of basic blocks) in the absence of a *strong* signal
14// to the contrary from probabilities. However, within the CFG structure, it
15// attempts to choose an ordering which favors placing more likely sequences of
16// blocks adjacent to each other.
17//
18// The algorithm works from the inner-most loop within a function outward, and
19// at each stage walks through the basic blocks, trying to coalesce them into
20// sequential chains where allowed by the CFG (or demanded by heavy
21// probabilities). Finally, it walks the blocks in topological order, and the
22// first time it reaches a chain of basic blocks, it schedules them in the
23// function in-order.
24//
25//===----------------------------------------------------------------------===//
26
28#include "BranchFolding.h"
29#include "llvm/ADT/ArrayRef.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SetVector.h"
35#include "llvm/ADT/Statistic.h"
54#include "llvm/IR/DebugLoc.h"
55#include "llvm/IR/Function.h"
56#include "llvm/IR/PrintPasses.h"
58#include "llvm/Pass.h"
65#include "llvm/Support/Debug.h"
69#include <algorithm>
70#include <cassert>
71#include <cstdint>
72#include <iterator>
73#include <memory>
74#include <string>
75#include <tuple>
76#include <utility>
77#include <vector>
78
79using namespace llvm;
80
81#define DEBUG_TYPE "block-placement"
82
83STATISTIC(NumCondBranches, "Number of conditional branches");
84STATISTIC(NumUncondBranches, "Number of unconditional branches");
85STATISTIC(CondBranchTakenFreq,
86 "Potential frequency of taking conditional branches");
87STATISTIC(UncondBranchTakenFreq,
88 "Potential frequency of taking unconditional branches");
89
91 "align-all-blocks",
92 cl::desc("Force the alignment of all blocks in the function in log2 format "
93 "(e.g 4 means align on 16B boundaries)."),
95
97 "align-all-nofallthru-blocks",
98 cl::desc("Force the alignment of all blocks that have no fall-through "
99 "predecessors (i.e. don't add nops that are executed). In log2 "
100 "format (e.g 4 means align on 16B boundaries)."),
101 cl::init(0), cl::Hidden);
102
104 "max-bytes-for-alignment",
105 cl::desc("Forces the maximum bytes allowed to be emitted when padding for "
106 "alignment"),
107 cl::init(0), cl::Hidden);
108
110 "block-placement-predecessor-limit",
111 cl::desc("For blocks with more predecessors, certain layout optimizations"
112 "will be disabled to prevent quadratic compile time."),
113 cl::init(1000), cl::Hidden);
114
115// FIXME: Find a good default for this flag and remove the flag.
117 "block-placement-exit-block-bias",
118 cl::desc("Block frequency percentage a loop exit block needs "
119 "over the original exit to be considered the new exit."),
120 cl::init(0), cl::Hidden);
121
122// Definition:
123// - Outlining: placement of a basic block outside the chain or hot path.
124
126 "loop-to-cold-block-ratio",
127 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
128 "(frequency of block) is greater than this ratio"),
129 cl::init(5), cl::Hidden);
130
131static cl::opt<bool>
132 ForceLoopColdBlock("force-loop-cold-block",
133 cl::desc("Force outlining cold blocks from loops."),
134 cl::init(false), cl::Hidden);
135
136static cl::opt<bool>
137 PreciseRotationCost("precise-rotation-cost",
138 cl::desc("Model the cost of loop rotation more "
139 "precisely by using profile data."),
140 cl::init(false), cl::Hidden);
141
142static cl::opt<bool>
143 ForcePreciseRotationCost("force-precise-rotation-cost",
144 cl::desc("Force the use of precise cost "
145 "loop rotation strategy."),
146 cl::init(false), cl::Hidden);
147
149 "misfetch-cost",
150 cl::desc("Cost that models the probabilistic risk of an instruction "
151 "misfetch due to a jump comparing to falling through, whose cost "
152 "is zero."),
153 cl::init(1), cl::Hidden);
154
155static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
156 cl::desc("Cost of jump instructions."),
157 cl::init(1), cl::Hidden);
158static cl::opt<bool>
159 TailDupPlacement("tail-dup-placement",
160 cl::desc("Perform tail duplication during placement. "
161 "Creates more fallthrough opportunities in "
162 "outline branches."),
163 cl::init(true), cl::Hidden);
164
165static cl::opt<bool>
166 BranchFoldPlacement("branch-fold-placement",
167 cl::desc("Perform branch folding during placement. "
168 "Reduces code size."),
169 cl::init(true), cl::Hidden);
170
171// Heuristic for tail duplication.
173 "tail-dup-placement-threshold",
174 cl::desc("Instruction cutoff for tail duplication during layout. "
175 "Tail merging during layout is forced to have a threshold "
176 "that won't conflict."),
177 cl::init(2), cl::Hidden);
178
179// Heuristic for aggressive tail duplication.
181 "tail-dup-placement-aggressive-threshold",
182 cl::desc("Instruction cutoff for aggressive tail duplication during "
183 "layout. Used at -O3. Tail merging during layout is forced to "
184 "have a threshold that won't conflict."),
185 cl::init(4), cl::Hidden);
186
187// Heuristic for tail duplication.
189 "tail-dup-placement-penalty",
190 cl::desc(
191 "Cost penalty for blocks that can avoid breaking CFG by copying. "
192 "Copying can increase fallthrough, but it also increases icache "
193 "pressure. This parameter controls the penalty to account for that. "
194 "Percent as integer."),
195 cl::init(2), cl::Hidden);
196
197// Heuristic for tail duplication if profile count is used in cost model.
199 "tail-dup-profile-percent-threshold",
200 cl::desc("If profile count information is used in tail duplication cost "
201 "model, the gained fall through number from tail duplication "
202 "should be at least this percent of hot count."),
203 cl::init(50), cl::Hidden);
204
205// Heuristic for triangle chains.
207 "triangle-chain-count",
208 cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
209 "triangle tail duplication heuristic to kick in. 0 to disable."),
210 cl::init(2), cl::Hidden);
211
212// Use case: When block layout is visualized after MBP pass, the basic blocks
213// are labeled in layout order; meanwhile blocks could be numbered in a
214// different order. It's hard to map between the graph and pass output.
215// With this option on, the basic blocks are renumbered in function layout
216// order. For debugging only.
218 "renumber-blocks-before-view",
219 cl::desc(
220 "If true, basic blocks are re-numbered before MBP layout is printed "
221 "into a dot graph. Only used when a function is being printed."),
222 cl::init(false), cl::Hidden);
223
225 "ext-tsp-block-placement-max-blocks",
226 cl::desc("Maximum number of basic blocks in a function to run ext-TSP "
227 "block placement."),
228 cl::init(UINT_MAX), cl::Hidden);
229
230// Apply the ext-tsp algorithm minimizing the size of a binary.
231static cl::opt<bool>
232 ApplyExtTspForSize("apply-ext-tsp-for-size", cl::init(false), cl::Hidden,
233 cl::desc("Use ext-tsp for size-aware block placement."));
234
235namespace llvm {
240
241// Internal option used to control BFI display only after MBP pass.
242// Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
243// -view-block-layout-with-bfi=
245
246} // namespace llvm
247
248namespace {
249
250class BlockChain;
251
252/// Type for our function-wide basic block -> block chain mapping.
253using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>;
254
255/// A chain of blocks which will be laid out contiguously.
256///
257/// This is the datastructure representing a chain of consecutive blocks that
258/// are profitable to layout together in order to maximize fallthrough
259/// probabilities and code locality. We also can use a block chain to represent
260/// a sequence of basic blocks which have some external (correctness)
261/// requirement for sequential layout.
262///
263/// Chains can be built around a single basic block and can be merged to grow
264/// them. They participate in a block-to-chain mapping, which is updated
265/// automatically as chains are merged together.
266class BlockChain {
267 /// The sequence of blocks belonging to this chain.
268 ///
269 /// This is the sequence of blocks for a particular chain. These will be laid
270 /// out in-order within the function.
272
273 /// A handle to the function-wide basic block to block chain mapping.
274 ///
275 /// This is retained in each block chain to simplify the computation of child
276 /// block chains for SCC-formation and iteration. We store the edges to child
277 /// basic blocks, and map them back to their associated chains using this
278 /// structure.
279 BlockToChainMapType &BlockToChain;
280
281public:
282 /// Construct a new BlockChain.
283 ///
284 /// This builds a new block chain representing a single basic block in the
285 /// function. It also registers itself as the chain that block participates
286 /// in with the BlockToChain mapping.
287 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
288 : Blocks(1, BB), BlockToChain(BlockToChain) {
289 assert(BB && "Cannot create a chain with a null basic block");
290 BlockToChain[BB] = this;
291 }
292
293 /// Iterator over blocks within the chain.
296
297 /// Beginning of blocks within the chain.
298 iterator begin() { return Blocks.begin(); }
299 const_iterator begin() const { return Blocks.begin(); }
300
301 /// End of blocks within the chain.
302 iterator end() { return Blocks.end(); }
303 const_iterator end() const { return Blocks.end(); }
304
305 bool remove(MachineBasicBlock *BB) {
306 for (iterator i = begin(); i != end(); ++i) {
307 if (*i == BB) {
308 Blocks.erase(i);
309 return true;
310 }
311 }
312 return false;
313 }
314
315 /// Merge a block chain into this one.
316 ///
317 /// This routine merges a block chain into this one. It takes care of forming
318 /// a contiguous sequence of basic blocks, updating the edge list, and
319 /// updating the block -> chain mapping. It does not free or tear down the
320 /// old chain, but the old chain's block list is no longer valid.
321 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
322 assert(BB && "Can't merge a null block.");
323 assert(!Blocks.empty() && "Can't merge into an empty chain.");
324
325 // Fast path in case we don't have a chain already.
326 if (!Chain) {
327 assert(!BlockToChain[BB] &&
328 "Passed chain is null, but BB has entry in BlockToChain.");
329 Blocks.push_back(BB);
330 BlockToChain[BB] = this;
331 return;
332 }
333
334 assert(BB == *Chain->begin() && "Passed BB is not head of Chain.");
335 assert(Chain->begin() != Chain->end());
336
337 // Update the incoming blocks to point to this chain, and add them to the
338 // chain structure.
339 for (MachineBasicBlock *ChainBB : *Chain) {
340 Blocks.push_back(ChainBB);
341 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain.");
342 BlockToChain[ChainBB] = this;
343 }
344 }
345
346#ifndef NDEBUG
347 /// Dump the blocks in this chain.
348 LLVM_DUMP_METHOD void dump() {
349 for (MachineBasicBlock *MBB : *this)
350 MBB->dump();
351 }
352#endif // NDEBUG
353
354 /// Count of predecessors of any block within the chain which have not
355 /// yet been scheduled. In general, we will delay scheduling this chain
356 /// until those predecessors are scheduled (or we find a sufficiently good
357 /// reason to override this heuristic.) Note that when forming loop chains,
358 /// blocks outside the loop are ignored and treated as if they were already
359 /// scheduled.
360 ///
361 /// Note: This field is reinitialized multiple times - once for each loop,
362 /// and then once for the function as a whole.
363 unsigned UnscheduledPredecessors = 0;
364};
365
366class MachineBlockPlacement {
367 /// A type for a block filter set.
368 using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
369
370 /// Pair struct containing basic block and taildup profitability
371 struct BlockAndTailDupResult {
372 MachineBasicBlock *BB = nullptr;
373 bool ShouldTailDup;
374 };
375
376 /// Triple struct containing edge weight and the edge.
377 struct WeightedEdge {
378 BlockFrequency Weight;
379 MachineBasicBlock *Src = nullptr;
380 MachineBasicBlock *Dest = nullptr;
381 };
382
383 /// A work list entry; Seq is its insertion order and breaks frequency ties.
384 struct WorkListEntry {
385 BlockFrequency Freq;
386 unsigned Seq;
387 MachineBasicBlock *BB;
388 };
389
390 /// Work lists of blocks that are ready to be laid out, kept as heaps with
391 /// the best candidate for selectBestCandidateBlock() on top. Entries of
392 /// placed or deleted blocks are only dropped once they reach the top. An
393 /// entry's BB may dangle and must not be used before checking BlockToChain.
394 SmallVector<WorkListEntry, 16> BlockWorkList;
395 SmallVector<WorkListEntry, 16> EHPadWorkList;
396 unsigned NextWorkListSeq = 0;
397
398 /// Edges that have already been computed as optimal.
399 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
400
401 /// Machine Function
402 MachineFunction *F = nullptr;
403
404 /// A handle to the branch probability pass.
405 const MachineBranchProbabilityInfo *MBPI = nullptr;
406
407 /// A handle to the function-wide block frequency pass.
408 std::unique_ptr<MBFIWrapper> MBFI;
409
410 /// A handle to the loop info.
411 MachineLoopInfo *MLI = nullptr;
412
413 /// Preferred loop exit.
414 /// Member variable for convenience. It may be removed by duplication deep
415 /// in the call stack.
416 MachineBasicBlock *PreferredLoopExit = nullptr;
417
418 /// A handle to the target's instruction info.
419 const TargetInstrInfo *TII = nullptr;
420
421 /// A handle to the target's lowering info.
422 const TargetLoweringBase *TLI = nullptr;
423
424 /// A handle to the post dominator tree.
425 MachinePostDominatorTree *MPDT = nullptr;
426
427 ProfileSummaryInfo *PSI = nullptr;
428
429 // Tail merging is also determined based on
430 // whether structured CFG is required.
431 bool AllowTailMerge;
432
433 CodeGenOptLevel OptLevel;
434
435 /// Duplicator used to duplicate tails during placement.
436 ///
437 /// Placement decisions can open up new tail duplication opportunities, but
438 /// since tail duplication affects placement decisions of later blocks, it
439 /// must be done inline.
440 TailDuplicator TailDup;
441
442 /// Partial tail duplication threshold.
443 BlockFrequency DupThreshold;
444
445 unsigned TailDupSize;
446
447 /// True: use block profile count to compute tail duplication cost.
448 /// False: use block frequency to compute tail duplication cost.
449 bool UseProfileCount = false;
450
451 /// Allocator and owner of BlockChain structures.
452 ///
453 /// We build BlockChains lazily while processing the loop structure of
454 /// a function. To reduce malloc traffic, we allocate them using this
455 /// slab-like allocator, and destroy them after the pass completes. An
456 /// important guarantee is that this allocator produces stable pointers to
457 /// the chains.
458 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
459
460 /// Function wide BasicBlock to BlockChain mapping.
461 ///
462 /// This mapping allows efficiently moving from any given basic block to the
463 /// BlockChain it participates in, if any. We use it to, among other things,
464 /// allow implicitly defining edges between chains as the existing edges
465 /// between basic blocks.
466 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
467
468#ifndef NDEBUG
469 /// The set of basic blocks that have terminators that cannot be fully
470 /// analyzed. These basic blocks cannot be re-ordered safely by
471 /// MachineBlockPlacement, and we must preserve physical layout of these
472 /// blocks and their successors through the pass.
473 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
474#endif
475
476 /// Get block profile count or frequency according to UseProfileCount.
477 /// The return value is used to model tail duplication cost.
478 BlockFrequency getBlockCountOrFrequency(const MachineBasicBlock *BB) {
479 if (UseProfileCount) {
480 auto Count = MBFI->getBlockProfileCount(BB);
481 if (Count)
482 return BlockFrequency(*Count);
483 else
484 return BlockFrequency(0);
485 } else
486 return MBFI->getBlockFreq(BB);
487 }
488
489 /// Scale the DupThreshold according to basic block size.
490 BlockFrequency scaleThreshold(MachineBasicBlock *BB);
491 void initTailDupThreshold();
492
493 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
494 /// if the count goes to 0, add them to the appropriate work list.
495 void markChainSuccessors(const BlockChain &Chain,
496 const MachineBasicBlock *LoopHeaderBB,
497 const BlockFilterSet *BlockFilter = nullptr);
498
499 /// Decrease the UnscheduledPredecessors count for a single block, and
500 /// if the count goes to 0, add them to the appropriate work list.
501 void markBlockSuccessors(const BlockChain &Chain, const MachineBasicBlock *BB,
502 const MachineBasicBlock *LoopHeaderBB,
503 const BlockFilterSet *BlockFilter = nullptr);
504
505 BranchProbability
506 collectViableSuccessors(const MachineBasicBlock *BB, const BlockChain &Chain,
507 const BlockFilterSet *BlockFilter,
508 SmallVector<MachineBasicBlock *, 4> &Successors);
509 bool isBestSuccessor(MachineBasicBlock *BB, MachineBasicBlock *Pred,
510 BlockFilterSet *BlockFilter);
511 void findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock *> &Candidates,
512 MachineBasicBlock *BB,
513 BlockFilterSet *BlockFilter);
514 bool repeatedlyTailDuplicateBlock(
515 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
516 const MachineBasicBlock *LoopHeaderBB, BlockChain &Chain,
517 BlockFilterSet *BlockFilter,
518 MachineFunction::iterator &PrevUnplacedBlockIt,
519 BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt);
520 bool
521 maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred,
522 BlockChain &Chain, BlockFilterSet *BlockFilter,
523 MachineFunction::iterator &PrevUnplacedBlockIt,
524 BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
525 bool &DuplicatedToLPred);
526 bool hasBetterLayoutPredecessor(const MachineBasicBlock *BB,
527 const MachineBasicBlock *Succ,
528 const BlockChain &SuccChain,
529 BranchProbability SuccProb,
530 BranchProbability RealSuccProb,
531 const BlockChain &Chain,
532 const BlockFilterSet *BlockFilter);
533 BlockAndTailDupResult selectBestSuccessor(const MachineBasicBlock *BB,
534 const BlockChain &Chain,
535 const BlockFilterSet *BlockFilter);
536 MachineBasicBlock *selectBestCandidateBlock(const BlockChain &Chain,
537 bool IsEHPad);
538 static bool isWorseCandidate(bool IsEHPad, const WorkListEntry &A,
539 const WorkListEntry &B);
540 void addToWorkList(MachineBasicBlock *BB);
541 MachineBasicBlock *
542 getFirstUnplacedBlock(const BlockChain &PlacedChain,
543 MachineFunction::iterator &PrevUnplacedBlockIt);
544 MachineBasicBlock *
545 getFirstUnplacedBlock(const BlockChain &PlacedChain,
546 BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
547 const BlockFilterSet *BlockFilter);
548
549 /// Add a basic block to the work list if it is appropriate.
550 ///
551 /// If the optional parameter BlockFilter is provided, only MBB
552 /// present in the set will be added to the worklist. If nullptr
553 /// is provided, no filtering occurs.
554 void fillWorkLists(const MachineBasicBlock *MBB,
555 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
556 const BlockFilterSet *BlockFilter);
557
558 void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
559 BlockFilterSet *BlockFilter = nullptr);
560 bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock,
561 const MachineBasicBlock *OldTop);
562 bool hasViableTopFallthrough(const MachineBasicBlock *Top,
563 const BlockFilterSet &LoopBlockSet);
564 BlockFrequency TopFallThroughFreq(const MachineBasicBlock *Top,
565 const BlockFilterSet &LoopBlockSet);
566 BlockFrequency FallThroughGains(const MachineBasicBlock *NewTop,
567 const MachineBasicBlock *OldTop,
568 const MachineBasicBlock *ExitBB,
569 const BlockFilterSet &LoopBlockSet);
570 MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop,
571 const MachineLoop &L,
572 const BlockFilterSet &LoopBlockSet);
573 MachineBasicBlock *findBestLoopTop(const MachineLoop &L,
574 const BlockFilterSet &LoopBlockSet);
575 MachineBasicBlock *findBestLoopExit(const MachineLoop &L,
576 const BlockFilterSet &LoopBlockSet,
577 BlockFrequency &ExitFreq);
578 BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
579 void buildLoopChains(const MachineLoop &L);
580 void rotateLoop(BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
581 BlockFrequency ExitFreq, const BlockFilterSet &LoopBlockSet);
582 void rotateLoopWithProfile(BlockChain &LoopChain, const MachineLoop &L,
583 const BlockFilterSet &LoopBlockSet);
584 void buildCFGChains();
585 void optimizeBranches();
586 void alignBlocks();
587 /// Returns true if a block should be tail-duplicated to increase fallthrough
588 /// opportunities.
589 bool shouldTailDuplicate(MachineBasicBlock *BB);
590 /// Check the edge frequencies to see if tail duplication will increase
591 /// fallthroughs.
592 bool isProfitableToTailDup(const MachineBasicBlock *BB,
593 const MachineBasicBlock *Succ,
594 BranchProbability QProb, const BlockChain &Chain,
595 const BlockFilterSet *BlockFilter);
596
597 /// Check for a trellis layout.
598 bool isTrellis(const MachineBasicBlock *BB,
599 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
600 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
601
602 /// Get the best successor given a trellis layout.
603 BlockAndTailDupResult getBestTrellisSuccessor(
604 const MachineBasicBlock *BB,
605 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
606 BranchProbability AdjustedSumProb, const BlockChain &Chain,
607 const BlockFilterSet *BlockFilter);
608
609 /// Get the best pair of non-conflicting edges.
610 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
611 const MachineBasicBlock *BB,
613
614 /// Returns true if a block can tail duplicate into all unplaced
615 /// predecessors. Filters based on loop.
616 bool canTailDuplicateUnplacedPreds(const MachineBasicBlock *BB,
617 MachineBasicBlock *Succ,
618 const BlockChain &Chain,
619 const BlockFilterSet *BlockFilter);
620
621 /// Find chains of triangles to tail-duplicate where a global analysis works,
622 /// but a local analysis would not find them.
623 void precomputeTriangleChains();
624
625 /// Apply a post-processing step optimizing block placement.
626 void applyExtTsp(bool OptForSize);
627
628 /// Modify the existing block placement in the function and adjust all jumps.
629 void assignBlockOrder(const std::vector<const MachineBasicBlock *> &NewOrder);
630
631 /// Create a single CFG chain from the current block order.
632 void createCFGChainExtTsp();
633
634public:
635 MachineBlockPlacement(const MachineBranchProbabilityInfo *MBPI,
636 MachineLoopInfo *MLI, ProfileSummaryInfo *PSI,
637 std::unique_ptr<MBFIWrapper> MBFI,
638 MachinePostDominatorTree *MPDT, bool AllowTailMerge)
639 : MBPI(MBPI), MBFI(std::move(MBFI)), MLI(MLI), MPDT(MPDT), PSI(PSI),
640 AllowTailMerge(AllowTailMerge) {};
641
642 bool run(MachineFunction &F);
643
644 static bool allowTailDupPlacement(MachineFunction &MF) {
646 }
647};
648
649class MachineBlockPlacementLegacy : public MachineFunctionPass {
650public:
651 static char ID; // Pass identification, replacement for typeid
652
653 MachineBlockPlacementLegacy() : MachineFunctionPass(ID) {}
654
655 bool runOnMachineFunction(MachineFunction &MF) override {
656 if (skipFunction(MF.getFunction()))
657 return false;
658
659 auto *MBPI =
660 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
661 auto MBFI = std::make_unique<MBFIWrapper>(
662 getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI());
663 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
664 auto *MPDT = MachineBlockPlacement::allowTailDupPlacement(MF)
665 ? &getAnalysis<MachinePostDominatorTreeWrapperPass>()
666 .getPostDomTree()
667 : nullptr;
668 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
669 auto *PassConfig = &getAnalysis<TargetPassConfig>();
670 bool AllowTailMerge = PassConfig->getEnableTailMerge();
671 return MachineBlockPlacement(MBPI, MLI, PSI, std::move(MBFI), MPDT,
672 AllowTailMerge)
673 .run(MF);
674 }
675
676 void getAnalysisUsage(AnalysisUsage &AU) const override {
677 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
678 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
680 AU.addRequired<MachinePostDominatorTreeWrapperPass>();
681 AU.addRequired<MachineLoopInfoWrapperPass>();
682 AU.addRequired<ProfileSummaryInfoWrapperPass>();
683 AU.addRequired<TargetPassConfig>();
684 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
686 }
687};
688
689} // end anonymous namespace
690
691char MachineBlockPlacementLegacy::ID = 0;
692
693char &llvm::MachineBlockPlacementID = MachineBlockPlacementLegacy::ID;
694
695INITIALIZE_PASS_BEGIN(MachineBlockPlacementLegacy, DEBUG_TYPE,
696 "Branch Probability Basic Block Placement", false, false)
702INITIALIZE_PASS_END(MachineBlockPlacementLegacy, DEBUG_TYPE,
703 "Branch Probability Basic Block Placement", false, false)
704
705#ifndef NDEBUG
706/// Helper to print the name of a MBB.
707///
708/// Only used by debug logging.
709static std::string getBlockName(const MachineBasicBlock *BB) {
710 std::string Result;
711 raw_string_ostream OS(Result);
712 OS << printMBBReference(*BB);
713 OS << " ('" << BB->getName() << "')";
714 return Result;
715}
716#endif
717
718/// Mark a chain's successors as having one fewer preds.
719///
720/// When a chain is being merged into the "placed" chain, this routine will
721/// quickly walk the successors of each block in the chain and mark them as
722/// having one fewer active predecessor. It also adds any successors of this
723/// chain which reach the zero-predecessor state to the appropriate worklist.
724void MachineBlockPlacement::markChainSuccessors(
725 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
726 const BlockFilterSet *BlockFilter) {
727 // Walk all the blocks in this chain, marking their successors as having
728 // a predecessor placed.
729 for (MachineBasicBlock *MBB : Chain) {
730 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
731 }
732}
733
734/// Mark a single block's successors as having one fewer preds.
735///
736/// Under normal circumstances, this is only called by markChainSuccessors,
737/// but if a block that was to be placed is completely tail-duplicated away,
738/// and was duplicated into the chain end, we need to redo markBlockSuccessors
739/// for just that block.
740void MachineBlockPlacement::markBlockSuccessors(
741 const BlockChain &Chain, const MachineBasicBlock *MBB,
742 const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
743 // Add any successors for which this is the only un-placed in-loop
744 // predecessor to the worklist as a viable candidate for CFG-neutral
745 // placement. No subsequent placement of this block will violate the CFG
746 // shape, so we get to use heuristics to choose a favorable placement.
747 for (MachineBasicBlock *Succ : MBB->successors()) {
748 if (BlockFilter && !BlockFilter->count(Succ))
749 continue;
750 BlockChain &SuccChain = *BlockToChain[Succ];
751 // Disregard edges within a fixed chain, or edges to the loop header.
752 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
753 continue;
754
755 // This is a cross-chain edge that is within the loop, so decrement the
756 // loop predecessor count of the destination chain.
757 if (SuccChain.UnscheduledPredecessors == 0 ||
758 --SuccChain.UnscheduledPredecessors > 0)
759 continue;
760
761 addToWorkList(*SuccChain.begin());
762 }
763}
764
765/// This helper function collects the set of successors of block
766/// \p BB that are allowed to be its layout successors, and return
767/// the total branch probability of edges from \p BB to those
768/// blocks.
769BranchProbability MachineBlockPlacement::collectViableSuccessors(
770 const MachineBasicBlock *BB, const BlockChain &Chain,
771 const BlockFilterSet *BlockFilter,
772 SmallVector<MachineBasicBlock *, 4> &Successors) {
773 // Adjust edge probabilities by excluding edges pointing to blocks that is
774 // either not in BlockFilter or is already in the current chain. Consider the
775 // following CFG:
776 //
777 // --->A
778 // | / \
779 // | B C
780 // | \ / \
781 // ----D E
782 //
783 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
784 // A->C is chosen as a fall-through, D won't be selected as a successor of C
785 // due to CFG constraint (the probability of C->D is not greater than
786 // HotProb to break topo-order). If we exclude E that is not in BlockFilter
787 // when calculating the probability of C->D, D will be selected and we
788 // will get A C D B as the layout of this loop.
789 auto AdjustedSumProb = BranchProbability::getOne();
790 for (MachineBasicBlock *Succ : BB->successors()) {
791 bool SkipSucc = false;
792 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
793 SkipSucc = true;
794 } else {
795 BlockChain *SuccChain = BlockToChain[Succ];
796 if (SuccChain == &Chain) {
797 SkipSucc = true;
798 } else if (Succ != *SuccChain->begin()) {
799 LLVM_DEBUG(dbgs() << " " << getBlockName(Succ)
800 << " -> Mid chain!\n");
801 continue;
802 }
803 }
804 if (SkipSucc)
805 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
806 else
807 Successors.push_back(Succ);
808 }
809
810 return AdjustedSumProb;
811}
812
813/// The helper function returns the branch probability that is adjusted
814/// or normalized over the new total \p AdjustedSumProb.
815static BranchProbability
817 BranchProbability AdjustedSumProb) {
818 BranchProbability SuccProb;
819 uint32_t SuccProbN = OrigProb.getNumerator();
820 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
821 if (SuccProbN >= SuccProbD)
822 SuccProb = BranchProbability::getOne();
823 else
824 SuccProb = BranchProbability(SuccProbN, SuccProbD);
825
826 return SuccProb;
827}
828
829/// Check if \p BB has exactly the successors in \p Successors.
830static bool
833 if (BB.succ_size() != Successors.size())
834 return false;
835 // We don't want to count self-loops
836 if (Successors.count(&BB))
837 return false;
838 for (MachineBasicBlock *Succ : BB.successors())
839 if (!Successors.count(Succ))
840 return false;
841 return true;
842}
843
844/// Check if a block should be tail duplicated to increase fallthrough
845/// opportunities.
846/// \p BB Block to check.
847bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
848 // Blocks with single successors don't create additional fallthrough
849 // opportunities. Don't duplicate them. TODO: When conditional exits are
850 // analyzable, allow them to be duplicated.
851 bool IsSimple = TailDup.isSimpleBB(BB);
852
853 if (BB->succ_size() == 1)
854 return false;
855 return TailDup.shouldTailDuplicate(IsSimple, *BB);
856}
857
858/// Compare 2 BlockFrequency's with a small penalty for \p A.
859/// In order to be conservative, we apply a X% penalty to account for
860/// increased icache pressure and static heuristics. For small frequencies
861/// we use only the numerators to improve accuracy. For simplicity, we assume
862/// the penalty is less than 100%
863/// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
865 BlockFrequency EntryFreq) {
866 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
867 BlockFrequency Gain = A - B;
868 return (Gain / ThresholdProb) >= EntryFreq;
869}
870
871/// Check the edge frequencies to see if tail duplication will increase
872/// fallthroughs. It only makes sense to call this function when
873/// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
874/// always locally profitable if we would have picked \p Succ without
875/// considering duplication.
876bool MachineBlockPlacement::isProfitableToTailDup(
877 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
878 BranchProbability QProb, const BlockChain &Chain,
879 const BlockFilterSet *BlockFilter) {
880 // We need to do a probability calculation to make sure this is profitable.
881 // First: does succ have a successor that post-dominates? This affects the
882 // calculation. The 2 relevant cases are:
883 // BB BB
884 // | \Qout | \Qout
885 // P| C |P C
886 // = C' = C'
887 // | /Qin | /Qin
888 // | / | /
889 // Succ Succ
890 // / \ | \ V
891 // U/ =V |U \
892 // / \ = D
893 // D E | /
894 // | /
895 // |/
896 // PDom
897 // '=' : Branch taken for that CFG edge
898 // In the second case, Placing Succ while duplicating it into C prevents the
899 // fallthrough of Succ into either D or PDom, because they now have C as an
900 // unplaced predecessor
901
902 // Start by figuring out which case we fall into
903 MachineBasicBlock *PDom = nullptr;
904 SmallVector<MachineBasicBlock *, 4> SuccSuccs;
905 // Only scan the relevant successors
906 auto AdjustedSuccSumProb =
907 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
908 BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
909 auto BBFreq = MBFI->getBlockFreq(BB);
910 auto SuccFreq = MBFI->getBlockFreq(Succ);
911 BlockFrequency P = BBFreq * PProb;
912 BlockFrequency Qout = BBFreq * QProb;
913 BlockFrequency EntryFreq = MBFI->getEntryFreq();
914 // If there are no more successors, it is profitable to copy, as it strictly
915 // increases fallthrough.
916 if (SuccSuccs.size() == 0)
917 return greaterWithBias(P, Qout, EntryFreq);
918
919 auto BestSuccSucc = BranchProbability::getZero();
920 // Find the PDom or the best Succ if no PDom exists.
921 for (MachineBasicBlock *SuccSucc : SuccSuccs) {
922 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
923 if (Prob > BestSuccSucc)
924 BestSuccSucc = Prob;
925 if (PDom == nullptr)
926 if (MPDT->dominates(SuccSucc, Succ)) {
927 PDom = SuccSucc;
928 break;
929 }
930 }
931 // For the comparisons, we need to know Succ's best incoming edge that isn't
932 // from BB.
933 auto SuccBestPred = BlockFrequency(0);
934 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
935 if (SuccPred == Succ || SuccPred == BB ||
936 BlockToChain[SuccPred] == &Chain ||
937 (BlockFilter && !BlockFilter->count(SuccPred)))
938 continue;
939 auto Freq =
940 MBFI->getBlockFreq(SuccPred) * MBPI->getEdgeProbability(SuccPred, Succ);
941 if (Freq > SuccBestPred)
942 SuccBestPred = Freq;
943 }
944 // Qin is Succ's best unplaced incoming edge that isn't BB
945 BlockFrequency Qin = SuccBestPred;
946 // If it doesn't have a post-dominating successor, here is the calculation:
947 // BB BB
948 // | \Qout | \
949 // P| C | =
950 // = C' | C
951 // | /Qin | |
952 // | / | C' (+Succ)
953 // Succ Succ /|
954 // / \ | \/ |
955 // U/ =V | == |
956 // / \ | / \|
957 // D E D E
958 // '=' : Branch taken for that CFG edge
959 // Cost in the first case is: P + V
960 // For this calculation, we always assume P > Qout. If Qout > P
961 // The result of this function will be ignored at the caller.
962 // Let F = SuccFreq - Qin
963 // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
964
965 if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
966 BranchProbability UProb = BestSuccSucc;
967 BranchProbability VProb = AdjustedSuccSumProb - UProb;
968 BlockFrequency F = SuccFreq - Qin;
969 BlockFrequency V = SuccFreq * VProb;
970 BlockFrequency QinU = std::min(Qin, F) * UProb;
971 BlockFrequency BaseCost = P + V;
972 BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
973 return greaterWithBias(BaseCost, DupCost, EntryFreq);
974 }
975 BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
976 BranchProbability VProb = AdjustedSuccSumProb - UProb;
977 BlockFrequency U = SuccFreq * UProb;
978 BlockFrequency V = SuccFreq * VProb;
979 BlockFrequency F = SuccFreq - Qin;
980 // If there is a post-dominating successor, here is the calculation:
981 // BB BB BB BB
982 // | \Qout | \ | \Qout | \
983 // |P C | = |P C | =
984 // = C' |P C = C' |P C
985 // | /Qin | | | /Qin | |
986 // | / | C' (+Succ) | / | C' (+Succ)
987 // Succ Succ /| Succ Succ /|
988 // | \ V | \/ | | \ V | \/ |
989 // |U \ |U /\ =? |U = |U /\ |
990 // = D = = =?| | D | = =|
991 // | / |/ D | / |/ D
992 // | / | / | = | /
993 // |/ | / |/ | =
994 // Dom Dom Dom Dom
995 // '=' : Branch taken for that CFG edge
996 // The cost for taken branches in the first case is P + U
997 // Let F = SuccFreq - Qin
998 // The cost in the second case (assuming independence), given the layout:
999 // BB, Succ, (C+Succ), D, Dom or the layout:
1000 // BB, Succ, D, Dom, (C+Succ)
1001 // is Qout + max(F, Qin) * U + min(F, Qin)
1002 // compare P + U vs Qout + P * U + Qin.
1003 //
1004 // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
1005 //
1006 // For the 3rd case, the cost is P + 2 * V
1007 // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
1008 // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
1009 if (UProb > AdjustedSuccSumProb / 2 &&
1010 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
1011 Chain, BlockFilter))
1012 // Cases 3 & 4
1013 return greaterWithBias(
1014 (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
1015 EntryFreq);
1016 // Cases 1 & 2
1017 return greaterWithBias((P + U),
1018 (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
1019 std::max(Qin, F) * UProb),
1020 EntryFreq);
1021}
1022
1023/// Check for a trellis layout. \p BB is the upper part of a trellis if its
1024/// successors form the lower part of a trellis. A successor set S forms the
1025/// lower part of a trellis if all of the predecessors of S are either in S or
1026/// have all of S as successors. We ignore trellises where BB doesn't have 2
1027/// successors because for fewer than 2, it's trivial, and for 3 or greater they
1028/// are very uncommon and complex to compute optimally. Allowing edges within S
1029/// is not strictly a trellis, but the same algorithm works, so we allow it.
1030bool MachineBlockPlacement::isTrellis(
1031 const MachineBasicBlock *BB,
1032 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
1033 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
1034 // Technically BB could form a trellis with branching factor higher than 2.
1035 // But that's extremely uncommon.
1036 if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
1037 return false;
1038
1039 SmallPtrSet<const MachineBasicBlock *, 2> Successors(llvm::from_range,
1040 BB->successors());
1041 // To avoid reviewing the same predecessors twice.
1042 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
1043
1044 for (MachineBasicBlock *Succ : ViableSuccs) {
1045 // Compile-time optimization: runtime is quadratic in the number of
1046 // predecessors. For such uncommon cases, exit early.
1047 if (Succ->pred_size() > PredecessorLimit)
1048 return false;
1049
1050 int PredCount = 0;
1051 for (auto *SuccPred : Succ->predecessors()) {
1052 // Allow triangle successors, but don't count them.
1053 if (Successors.count(SuccPred)) {
1054 // Make sure that it is actually a triangle.
1055 for (MachineBasicBlock *CheckSucc : SuccPred->successors())
1056 if (!Successors.count(CheckSucc))
1057 return false;
1058 continue;
1059 }
1060 const BlockChain *PredChain = BlockToChain[SuccPred];
1061 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
1062 PredChain == &Chain || PredChain == BlockToChain[Succ])
1063 continue;
1064 ++PredCount;
1065 // Perform the successor check only once.
1066 if (!SeenPreds.insert(SuccPred).second)
1067 continue;
1068 if (!hasSameSuccessors(*SuccPred, Successors))
1069 return false;
1070 }
1071 // If one of the successors has only BB as a predecessor, it is not a
1072 // trellis.
1073 if (PredCount < 1)
1074 return false;
1075 }
1076 return true;
1077}
1078
1079/// Pick the highest total weight pair of edges that can both be laid out.
1080/// The edges in \p Edges[0] are assumed to have a different destination than
1081/// the edges in \p Edges[1]. Simple counting shows that the best pair is either
1082/// the individual highest weight edges to the 2 different destinations, or in
1083/// case of a conflict, one of them should be replaced with a 2nd best edge.
1084std::pair<MachineBlockPlacement::WeightedEdge,
1085 MachineBlockPlacement::WeightedEdge>
1086MachineBlockPlacement::getBestNonConflictingEdges(
1087 const MachineBasicBlock *BB,
1089 Edges) {
1090 // Sort the edges, and then for each successor, find the best incoming
1091 // predecessor. If the best incoming predecessors aren't the same,
1092 // then that is clearly the best layout. If there is a conflict, one of the
1093 // successors will have to fallthrough from the second best predecessor. We
1094 // compare which combination is better overall.
1095
1096 // Sort for highest frequency.
1097 auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
1098
1099 llvm::stable_sort(Edges[0], Cmp);
1100 llvm::stable_sort(Edges[1], Cmp);
1101 auto BestA = Edges[0].begin();
1102 auto BestB = Edges[1].begin();
1103 // Arrange for the correct answer to be in BestA and BestB
1104 // If the 2 best edges don't conflict, the answer is already there.
1105 if (BestA->Src == BestB->Src) {
1106 // Compare the total fallthrough of (Best + Second Best) for both pairs
1107 auto SecondBestA = std::next(BestA);
1108 auto SecondBestB = std::next(BestB);
1109 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
1110 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
1111 if (BestAScore < BestBScore)
1112 BestA = SecondBestA;
1113 else
1114 BestB = SecondBestB;
1115 }
1116 // Arrange for the BB edge to be in BestA if it exists.
1117 if (BestB->Src == BB)
1118 std::swap(BestA, BestB);
1119 return std::make_pair(*BestA, *BestB);
1120}
1121
1122/// Get the best successor from \p BB based on \p BB being part of a trellis.
1123/// We only handle trellises with 2 successors, so the algorithm is
1124/// straightforward: Find the best pair of edges that don't conflict. We find
1125/// the best incoming edge for each successor in the trellis. If those conflict,
1126/// we consider which of them should be replaced with the second best.
1127/// Upon return the two best edges will be in \p BestEdges. If one of the edges
1128/// comes from \p BB, it will be in \p BestEdges[0]
1129MachineBlockPlacement::BlockAndTailDupResult
1130MachineBlockPlacement::getBestTrellisSuccessor(
1131 const MachineBasicBlock *BB,
1132 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
1133 BranchProbability AdjustedSumProb, const BlockChain &Chain,
1134 const BlockFilterSet *BlockFilter) {
1135
1136 BlockAndTailDupResult Result = {nullptr, false};
1137 SmallPtrSet<const MachineBasicBlock *, 4> Successors(llvm::from_range,
1138 BB->successors());
1139
1140 // We assume size 2 because it's common. For general n, we would have to do
1141 // the Hungarian algorithm, but it's not worth the complexity because more
1142 // than 2 successors is fairly uncommon, and a trellis even more so.
1143 if (Successors.size() != 2 || ViableSuccs.size() != 2)
1144 return Result;
1145
1146 // Collect the edge frequencies of all edges that form the trellis.
1148 int SuccIndex = 0;
1149 for (auto *Succ : ViableSuccs) {
1150 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
1151 // Skip any placed predecessors that are not BB
1152 if (SuccPred != BB) {
1153 if (BlockFilter && !BlockFilter->count(SuccPred))
1154 continue;
1155 const BlockChain *SuccPredChain = BlockToChain[SuccPred];
1156 if (SuccPredChain == &Chain || SuccPredChain == BlockToChain[Succ])
1157 continue;
1158 }
1159 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
1160 MBPI->getEdgeProbability(SuccPred, Succ);
1161 Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
1162 }
1163 ++SuccIndex;
1164 }
1165
1166 // Pick the best combination of 2 edges from all the edges in the trellis.
1167 WeightedEdge BestA, BestB;
1168 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
1169
1170 if (BestA.Src != BB) {
1171 // If we have a trellis, and BB doesn't have the best fallthrough edges,
1172 // we shouldn't choose any successor. We've already looked and there's a
1173 // better fallthrough edge for all the successors.
1174 LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
1175 return Result;
1176 }
1177
1178 // Did we pick the triangle edge? If tail-duplication is profitable, do
1179 // that instead. Otherwise merge the triangle edge now while we know it is
1180 // optimal.
1181 if (BestA.Dest == BestB.Src) {
1182 // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
1183 // would be better.
1184 MachineBasicBlock *Succ1 = BestA.Dest;
1185 MachineBasicBlock *Succ2 = BestB.Dest;
1186 // Check to see if tail-duplication would be profitable.
1187 if (allowTailDupPlacement(*F) && shouldTailDuplicate(Succ2) &&
1188 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
1189 isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
1190 Chain, BlockFilter)) {
1191 LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
1192 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
1193 dbgs() << " Selected: " << getBlockName(Succ2)
1194 << ", probability: " << Succ2Prob
1195 << " (Tail Duplicate)\n");
1196 Result.BB = Succ2;
1197 Result.ShouldTailDup = true;
1198 return Result;
1199 }
1200 }
1201 // We have already computed the optimal edge for the other side of the
1202 // trellis.
1203 ComputedEdges[BestB.Src] = {BestB.Dest, false};
1204
1205 auto TrellisSucc = BestA.Dest;
1206 LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability(
1207 MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
1208 dbgs() << " Selected: " << getBlockName(TrellisSucc)
1209 << ", probability: " << SuccProb << " (Trellis)\n");
1210 Result.BB = TrellisSucc;
1211 return Result;
1212}
1213
1214/// When the option allowTailDupPlacement() is on, this method checks if the
1215/// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
1216/// into all of its unplaced, unfiltered predecessors, that are not BB.
1217bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
1218 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1219 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
1220 if (!shouldTailDuplicate(Succ))
1221 return false;
1222
1223 // The result of canTailDuplicate.
1224 bool Duplicate = true;
1225 // Number of possible duplication.
1226 unsigned int NumDup = 0;
1227
1228 // For CFG checking.
1229 SmallPtrSet<const MachineBasicBlock *, 4> Successors(llvm::from_range,
1230 BB->successors());
1231 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1232 // Make sure all unplaced and unfiltered predecessors can be
1233 // tail-duplicated into.
1234 // Skip any blocks that are already placed or not in this loop.
1235 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred)) ||
1236 (BlockToChain[Pred] == &Chain && !Succ->succ_empty()))
1237 continue;
1238 if (!TailDup.canTailDuplicate(Succ, Pred)) {
1239 if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
1240 // This will result in a trellis after tail duplication, so we don't
1241 // need to copy Succ into this predecessor. In the presence
1242 // of a trellis tail duplication can continue to be profitable.
1243 // For example:
1244 // A A
1245 // |\ |\
1246 // | \ | \
1247 // | C | C+BB
1248 // | / | |
1249 // |/ | |
1250 // BB => BB |
1251 // |\ |\/|
1252 // | \ |/\|
1253 // | D | D
1254 // | / | /
1255 // |/ |/
1256 // Succ Succ
1257 //
1258 // After BB was duplicated into C, the layout looks like the one on the
1259 // right. BB and C now have the same successors. When considering
1260 // whether Succ can be duplicated into all its unplaced predecessors, we
1261 // ignore C.
1262 // We can do this because C already has a profitable fallthrough, namely
1263 // D. TODO(iteratee): ignore sufficiently cold predecessors for
1264 // duplication and for this test.
1265 //
1266 // This allows trellises to be laid out in 2 separate chains
1267 // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
1268 // because it allows the creation of 2 fallthrough paths with links
1269 // between them, and we correctly identify the best layout for these
1270 // CFGs. We want to extend trellises that the user created in addition
1271 // to trellises created by tail-duplication, so we just look for the
1272 // CFG.
1273 continue;
1274 Duplicate = false;
1275 continue;
1276 }
1277 NumDup++;
1278 }
1279
1280 // No possible duplication in current filter set.
1281 if (NumDup == 0)
1282 return false;
1283
1284 // If profile information is available, findDuplicateCandidates can do more
1285 // precise benefit analysis.
1286 if (F->getFunction().hasProfileData())
1287 return true;
1288
1289 // This is mainly for function exit BB.
1290 // The integrated tail duplication is really designed for increasing
1291 // fallthrough from predecessors from Succ to its successors. We may need
1292 // other machanism to handle different cases.
1293 if (Succ->succ_empty())
1294 return true;
1295
1296 // Plus the already placed predecessor.
1297 NumDup++;
1298
1299 // If the duplication candidate has more unplaced predecessors than
1300 // successors, the extra duplication can't bring more fallthrough.
1301 //
1302 // Pred1 Pred2 Pred3
1303 // \ | /
1304 // \ | /
1305 // \ | /
1306 // Dup
1307 // / \
1308 // / \
1309 // Succ1 Succ2
1310 //
1311 // In this example Dup has 2 successors and 3 predecessors, duplication of Dup
1312 // can increase the fallthrough from Pred1 to Succ1 and from Pred2 to Succ2,
1313 // but the duplication into Pred3 can't increase fallthrough.
1314 //
1315 // A small number of extra duplication may not hurt too much. We need a better
1316 // heuristic to handle it.
1317 if ((NumDup > Succ->succ_size()) || !Duplicate)
1318 return false;
1319
1320 return true;
1321}
1322
1323/// Find chains of triangles where we believe it would be profitable to
1324/// tail-duplicate them all, but a local analysis would not find them.
1325/// There are 3 ways this can be profitable:
1326/// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
1327/// longer chains)
1328/// 2) The chains are statically correlated. Branch probabilities have a very
1329/// U-shaped distribution.
1330/// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
1331/// If the branches in a chain are likely to be from the same side of the
1332/// distribution as their predecessor, but are independent at runtime, this
1333/// transformation is profitable. (Because the cost of being wrong is a small
1334/// fixed cost, unlike the standard triangle layout where the cost of being
1335/// wrong scales with the # of triangles.)
1336/// 3) The chains are dynamically correlated. If the probability that a previous
1337/// branch was taken positively influences whether the next branch will be
1338/// taken
1339/// We believe that 2 and 3 are common enough to justify the small margin in 1.
1340void MachineBlockPlacement::precomputeTriangleChains() {
1341 struct TriangleChain {
1342 std::vector<MachineBasicBlock *> Edges;
1343
1344 TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
1345 : Edges({src, dst}) {}
1346
1347 void append(MachineBasicBlock *dst) {
1348 assert(getKey()->isSuccessor(dst) &&
1349 "Attempting to append a block that is not a successor.");
1350 Edges.push_back(dst);
1351 }
1352
1353 unsigned count() const { return Edges.size() - 1; }
1354
1355 MachineBasicBlock *getKey() const { return Edges.back(); }
1356 };
1357
1358 if (TriangleChainCount == 0)
1359 return;
1360
1361 LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n");
1362 // Map from last block to the chain that contains it. This allows us to extend
1363 // chains as we find new triangles.
1364 DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
1365 for (MachineBasicBlock &BB : *F) {
1366 // If BB doesn't have 2 successors, it doesn't start a triangle.
1367 if (BB.succ_size() != 2)
1368 continue;
1369 MachineBasicBlock *PDom = nullptr;
1370 for (MachineBasicBlock *Succ : BB.successors()) {
1371 if (!MPDT->dominates(Succ, &BB))
1372 continue;
1373 PDom = Succ;
1374 break;
1375 }
1376 // If BB doesn't have a post-dominating successor, it doesn't form a
1377 // triangle.
1378 if (PDom == nullptr)
1379 continue;
1380 // If PDom has a hint that it is low probability, skip this triangle.
1381 if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
1382 continue;
1383 // If PDom isn't eligible for duplication, this isn't the kind of triangle
1384 // we're looking for.
1385 if (!shouldTailDuplicate(PDom))
1386 continue;
1387 bool CanTailDuplicate = true;
1388 // If PDom can't tail-duplicate into it's non-BB predecessors, then this
1389 // isn't the kind of triangle we're looking for.
1390 for (MachineBasicBlock *Pred : PDom->predecessors()) {
1391 if (Pred == &BB)
1392 continue;
1393 if (!TailDup.canTailDuplicate(PDom, Pred)) {
1394 CanTailDuplicate = false;
1395 break;
1396 }
1397 }
1398 // If we can't tail-duplicate PDom to its predecessors, then skip this
1399 // triangle.
1400 if (!CanTailDuplicate)
1401 continue;
1402
1403 // Now we have an interesting triangle. Insert it if it's not part of an
1404 // existing chain.
1405 // Note: This cannot be replaced with a call insert() or emplace() because
1406 // the find key is BB, but the insert/emplace key is PDom.
1407 auto Found = TriangleChainMap.find(&BB);
1408 // If it is, remove the chain from the map, grow it, and put it back in the
1409 // map with the end as the new key.
1410 if (Found != TriangleChainMap.end()) {
1411 TriangleChain Chain = std::move(Found->second);
1412 TriangleChainMap.erase(Found);
1413 Chain.append(PDom);
1414 TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1415 } else {
1416 auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
1417 assert(InsertResult.second && "Block seen twice.");
1418 (void)InsertResult;
1419 }
1420 }
1421
1422 // Iterating over a DenseMap is safe here, because the only thing in the body
1423 // of the loop is inserting into another DenseMap (ComputedEdges).
1424 // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
1425 for (auto &ChainPair : TriangleChainMap) {
1426 TriangleChain &Chain = ChainPair.second;
1427 // Benchmarking has shown that due to branch correlation duplicating 2 or
1428 // more triangles is profitable, despite the calculations assuming
1429 // independence.
1430 if (Chain.count() < TriangleChainCount)
1431 continue;
1432 MachineBasicBlock *dst = Chain.Edges.back();
1433 Chain.Edges.pop_back();
1434 for (MachineBasicBlock *src : reverse(Chain.Edges)) {
1435 LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->"
1436 << getBlockName(dst)
1437 << " as pre-computed based on triangles.\n");
1438
1439 auto InsertResult = ComputedEdges.insert({src, {dst, true}});
1440 assert(InsertResult.second && "Block seen twice.");
1441 (void)InsertResult;
1442
1443 dst = src;
1444 }
1445 }
1446}
1447
1448// When profile is not present, return the StaticLikelyProb.
1449// When profile is available, we need to handle the triangle-shape CFG.
1450static BranchProbability
1452 if (!BB->getParent()->getFunction().hasProfileData())
1454 if (BB->succ_size() == 2) {
1455 const MachineBasicBlock *Succ1 = *BB->succ_begin();
1456 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
1457 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
1458 /* See case 1 below for the cost analysis. For BB->Succ to
1459 * be taken with smaller cost, the following needs to hold:
1460 * Prob(BB->Succ) > 2 * Prob(BB->Pred)
1461 * So the threshold T in the calculation below
1462 * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
1463 * So T / (1 - T) = 2, Yielding T = 2/3
1464 *
1465 * Then remap the user-controlled ProfileLikelyProb into
1466 * a triangle-specific threshold T.
1467 * T = (2/3) * (ProfileLikelyProb / 50)
1468 * = (2 * ProfileLikelyProb) / 150
1469 * This preserves T = 2/3 at ProfileLikelyProb = 50.
1470 * The result is capped at 1.
1471 */
1472 return BranchProbability(ProfileLikelyProb, 150) * 2;
1473 }
1474 }
1476}
1477
1478/// Checks to see if the layout candidate block \p Succ has a better layout
1479/// predecessor than \c BB. If yes, returns true.
1480/// \p SuccProb: The probability adjusted for only remaining blocks.
1481/// Only used for logging
1482/// \p RealSuccProb: The un-adjusted probability.
1483/// \p Chain: The chain that BB belongs to and Succ is being considered for.
1484/// \p BlockFilter: if non-null, the set of blocks that make up the loop being
1485/// considered
1486bool MachineBlockPlacement::hasBetterLayoutPredecessor(
1487 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1488 const BlockChain &SuccChain, BranchProbability SuccProb,
1489 BranchProbability RealSuccProb, const BlockChain &Chain,
1490 const BlockFilterSet *BlockFilter) {
1491
1492 // There isn't a better layout when there are no unscheduled predecessors.
1493 if (SuccChain.UnscheduledPredecessors == 0)
1494 return false;
1495
1496 // Compile-time optimization: runtime is quadratic in the number of
1497 // predecessors. For such uncommon cases, exit early.
1498 if (Succ->pred_size() > PredecessorLimit)
1499 return false;
1500
1501 // There are two basic scenarios here:
1502 // -------------------------------------
1503 // Case 1: triangular shape CFG (if-then):
1504 // BB
1505 // | \
1506 // | \
1507 // | Pred
1508 // | /
1509 // Succ
1510 // In this case, we are evaluating whether to select edge -> Succ, e.g.
1511 // set Succ as the layout successor of BB. Picking Succ as BB's
1512 // successor breaks the CFG constraints (FIXME: define these constraints).
1513 // With this layout, Pred BB
1514 // is forced to be outlined, so the overall cost will be cost of the
1515 // branch taken from BB to Pred, plus the cost of back taken branch
1516 // from Pred to Succ, as well as the additional cost associated
1517 // with the needed unconditional jump instruction from Pred To Succ.
1518
1519 // The cost of the topological order layout is the taken branch cost
1520 // from BB to Succ, so to make BB->Succ a viable candidate, the following
1521 // must hold:
1522 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
1523 // < freq(BB->Succ) * taken_branch_cost.
1524 // Ignoring unconditional jump cost, we get
1525 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
1526 // prob(BB->Succ) > 2 * prob(BB->Pred)
1527 //
1528 // When real profile data is available, we can precisely compute the
1529 // probability threshold that is needed for edge BB->Succ to be considered.
1530 // Without profile data, the heuristic requires the branch bias to be
1531 // a lot larger to make sure the signal is very strong (e.g. 80% default).
1532 // -----------------------------------------------------------------
1533 // Case 2: diamond like CFG (if-then-else):
1534 // S
1535 // / \
1536 // | \
1537 // BB Pred
1538 // \ /
1539 // Succ
1540 // ..
1541 //
1542 // The current block is BB and edge BB->Succ is now being evaluated.
1543 // Note that edge S->BB was previously already selected because
1544 // prob(S->BB) > prob(S->Pred).
1545 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
1546 // choose Pred, we will have a topological ordering as shown on the left
1547 // in the picture below. If we choose Succ, we have the solution as shown
1548 // on the right:
1549 //
1550 // topo-order:
1551 //
1552 // S----- ---S
1553 // | | | |
1554 // ---BB | | BB
1555 // | | | |
1556 // | Pred-- | Succ--
1557 // | | | |
1558 // ---Succ ---Pred--
1559 //
1560 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
1561 // = freq(S->Pred) + freq(S->BB)
1562 //
1563 // If we have profile data (i.e, branch probabilities can be trusted), the
1564 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
1565 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
1566 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
1567 // means the cost of topological order is greater.
1568 // When profile data is not available, however, we need to be more
1569 // conservative. If the branch prediction is wrong, breaking the topo-order
1570 // will actually yield a layout with large cost. For this reason, we need
1571 // strong biased branch at block S with Prob(S->BB) in order to select
1572 // BB->Succ. This is equivalent to looking the CFG backward with backward
1573 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
1574 // profile data).
1575 // --------------------------------------------------------------------------
1576 // Case 3: forked diamond
1577 // S
1578 // / \
1579 // / \
1580 // BB Pred
1581 // | \ / |
1582 // | \ / |
1583 // | X |
1584 // | / \ |
1585 // | / \ |
1586 // S1 S2
1587 //
1588 // The current block is BB and edge BB->S1 is now being evaluated.
1589 // As above S->BB was already selected because
1590 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1591 //
1592 // topo-order:
1593 //
1594 // S-------| ---S
1595 // | | | |
1596 // ---BB | | BB
1597 // | | | |
1598 // | Pred----| | S1----
1599 // | | | |
1600 // --(S1 or S2) ---Pred--
1601 // |
1602 // S2
1603 //
1604 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1605 // + min(freq(Pred->S1), freq(Pred->S2))
1606 // Non-topo-order cost:
1607 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1608 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1609 // is 0. Then the non topo layout is better when
1610 // freq(S->Pred) < freq(BB->S1).
1611 // This is exactly what is checked below.
1612 // Note there are other shapes that apply (Pred may not be a single block,
1613 // but they all fit this general pattern.)
1614 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
1615
1616 // Make sure that a hot successor doesn't have a globally more
1617 // important predecessor.
1618 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1619 bool BadCFGConflict = false;
1620
1621 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1622 BlockChain *PredChain = BlockToChain[Pred];
1623 if (Pred == Succ || PredChain == &SuccChain ||
1624 (BlockFilter && !BlockFilter->count(Pred)) || PredChain == &Chain ||
1625 Pred != *std::prev(PredChain->end()) ||
1626 // This check is redundant except for look ahead. This function is
1627 // called for lookahead by isProfitableToTailDup when BB hasn't been
1628 // placed yet.
1629 (Pred == BB))
1630 continue;
1631 // Do backward checking.
1632 // For all cases above, we need a backward checking to filter out edges that
1633 // are not 'strongly' biased.
1634 // BB Pred
1635 // \ /
1636 // Succ
1637 // We select edge BB->Succ if
1638 // freq(BB->Succ) > freq(Succ) * HotProb
1639 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1640 // HotProb
1641 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
1642 // Case 1 is covered too, because the first equation reduces to:
1643 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
1644 BlockFrequency PredEdgeFreq =
1645 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1646 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1647 BadCFGConflict = true;
1648 break;
1649 }
1650 }
1651
1652 if (BadCFGConflict) {
1653 LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> "
1654 << SuccProb << " (prob) (non-cold CFG conflict)\n");
1655 return true;
1656 }
1657
1658 return false;
1659}
1660
1661/// Select the best successor for a block.
1662///
1663/// This looks across all successors of a particular block and attempts to
1664/// select the "best" one to be the layout successor. It only considers direct
1665/// successors which also pass the block filter. It will attempt to avoid
1666/// breaking CFG structure, but cave and break such structures in the case of
1667/// very hot successor edges.
1668///
1669/// \returns The best successor block found, or null if none are viable, along
1670/// with a boolean indicating if tail duplication is necessary.
1671MachineBlockPlacement::BlockAndTailDupResult
1672MachineBlockPlacement::selectBestSuccessor(const MachineBasicBlock *BB,
1673 const BlockChain &Chain,
1674 const BlockFilterSet *BlockFilter) {
1675 const BranchProbability HotProb(StaticLikelyProb, 100);
1676
1677 BlockAndTailDupResult BestSucc = {nullptr, false};
1678 auto BestProb = BranchProbability::getZero();
1679
1680 SmallVector<MachineBasicBlock *, 4> Successors;
1681 auto AdjustedSumProb =
1682 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1683
1684 LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB)
1685 << "\n");
1686
1687 // if we already precomputed the best successor for BB, return that if still
1688 // applicable.
1689 auto FoundEdge = ComputedEdges.find(BB);
1690 if (FoundEdge != ComputedEdges.end()) {
1691 BlockAndTailDupResult Result = FoundEdge->second;
1692 ComputedEdges.erase(FoundEdge);
1693 BlockChain *SuccChain = BlockToChain[Result.BB];
1694 if (BB->isSuccessor(Result.BB) &&
1695 (!BlockFilter || BlockFilter->count(Result.BB)) &&
1696 SuccChain != &Chain && Result.BB == *SuccChain->begin())
1697 return Result;
1698 }
1699
1700 // if BB is part of a trellis, Use the trellis to determine the optimal
1701 // fallthrough edges
1702 if (isTrellis(BB, Successors, Chain, BlockFilter))
1703 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1704 BlockFilter);
1705
1706 // For blocks with CFG violations, we may be able to lay them out anyway with
1707 // tail-duplication. We keep this vector so we can perform the probability
1708 // calculations the minimum number of times.
1710 DupCandidates;
1711 for (MachineBasicBlock *Succ : Successors) {
1712 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1713 BranchProbability SuccProb =
1714 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
1715
1716 BlockChain &SuccChain = *BlockToChain[Succ];
1717 // Skip the edge \c BB->Succ if block \c Succ has a better layout
1718 // predecessor that yields lower global cost.
1719 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
1720 Chain, BlockFilter)) {
1721 // If tail duplication would make Succ profitable, place it.
1722 if (allowTailDupPlacement(*F) && shouldTailDuplicate(Succ))
1723 DupCandidates.emplace_back(SuccProb, Succ);
1724 continue;
1725 }
1726
1727 LLVM_DEBUG(
1728 dbgs() << " Candidate: " << getBlockName(Succ)
1729 << ", probability: " << SuccProb
1730 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1731 << "\n");
1732
1733 if (BestSucc.BB && BestProb >= SuccProb) {
1734 LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n");
1735 continue;
1736 }
1737
1738 LLVM_DEBUG(dbgs() << " Setting it as best candidate\n");
1739 BestSucc.BB = Succ;
1740 BestProb = SuccProb;
1741 }
1742 // Handle the tail duplication candidates in order of decreasing probability.
1743 // Stop at the first one that is profitable. Also stop if they are less
1744 // profitable than BestSucc. Position is important because we preserve it and
1745 // prefer first best match. Here we aren't comparing in order, so we capture
1746 // the position instead.
1747 llvm::stable_sort(DupCandidates,
1748 [](std::tuple<BranchProbability, MachineBasicBlock *> L,
1749 std::tuple<BranchProbability, MachineBasicBlock *> R) {
1750 return std::get<0>(L) > std::get<0>(R);
1751 });
1752 for (auto &Tup : DupCandidates) {
1753 BranchProbability DupProb;
1754 MachineBasicBlock *Succ;
1755 std::tie(DupProb, Succ) = Tup;
1756 if (DupProb < BestProb)
1757 break;
1758 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter) &&
1759 (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
1760 LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ)
1761 << ", probability: " << DupProb
1762 << " (Tail Duplicate)\n");
1763 BestSucc.BB = Succ;
1764 BestSucc.ShouldTailDup = true;
1765 break;
1766 }
1767 }
1768
1769 if (BestSucc.BB)
1770 LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
1771
1772 return BestSucc;
1773}
1774
1775/// Return whether \p A is a worse candidate than \p B for
1776/// selectBestCandidateBlock().
1777bool MachineBlockPlacement::isWorseCandidate(bool IsEHPad,
1778 const WorkListEntry &A,
1779 const WorkListEntry &B) {
1780 if (A.Freq != B.Freq) {
1781 // EH pads go least frequent first, to avoid jumping back from less
1782 // frequent landing pads to more frequent ones.
1783 //
1784 // FIXME: Using probability is probably (!) not the best way to achieve
1785 // this. We should probably have a more principled approach to layout
1786 // cleanup code.
1787 //
1788 // The goal is to get:
1789 //
1790 // +--------------------------+
1791 // | V
1792 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
1793 //
1794 // Rather than:
1795 //
1796 // +-------------------------------------+
1797 // V |
1798 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
1799 return IsEHPad ? A.Freq > B.Freq : A.Freq < B.Freq;
1800 }
1801 // Break ties by insertion order.
1802 return IsEHPad ? A.Seq < B.Seq : A.Seq > B.Seq;
1803}
1804
1805/// Add a block that is ready to be laid out to the work lists.
1806void MachineBlockPlacement::addToWorkList(MachineBasicBlock *BB) {
1807 bool IsEHPad = BB->isEHPad();
1808 SmallVectorImpl<WorkListEntry> &WorkList =
1809 IsEHPad ? EHPadWorkList : BlockWorkList;
1810 WorkList.push_back({MBFI->getBlockFreq(BB), NextWorkListSeq++, BB});
1811 std::push_heap(WorkList.begin(), WorkList.end(),
1812 [IsEHPad](const WorkListEntry &A, const WorkListEntry &B) {
1813 return isWorseCandidate(IsEHPad, A, B);
1814 });
1815}
1816
1817/// Drop stale entries off the top of the work list's heap and return the
1818/// block left on top (EHPadWorkList if \p IsEHPad is set, BlockWorkList
1819/// otherwise).
1820///
1821/// The block on top is the most frequently visited one, which in the case of
1822/// a loop is the one most desirable to be physically close to the rest of the
1823/// loop body in order to improve i-cache behavior. For EH pads it is the least
1824/// frequent one.
1825///
1826/// \returns The best block found, or null if none are viable.
1827MachineBasicBlock *
1828MachineBlockPlacement::selectBestCandidateBlock(const BlockChain &Chain,
1829 bool IsEHPad) {
1830 SmallVectorImpl<WorkListEntry> &WorkList =
1831 IsEHPad ? EHPadWorkList : BlockWorkList;
1832 while (!WorkList.empty()) {
1833 const BlockChain *SuccChain = BlockToChain.lookup(WorkList.front().BB);
1834 bool IsStale = !SuccChain || SuccChain == &Chain;
1835 if (!IsStale)
1836 break;
1837 std::pop_heap(WorkList.begin(), WorkList.end(),
1838 [IsEHPad](const WorkListEntry &A, const WorkListEntry &B) {
1839 return isWorseCandidate(IsEHPad, A, B);
1840 });
1841 WorkList.pop_back();
1842 }
1843
1844 if (WorkList.empty())
1845 return nullptr;
1846
1847 // Not popped; it becomes stale once buildChain() merges it into Chain.
1848 MachineBasicBlock *BestBlock = WorkList.front().BB;
1849 assert(BestBlock->isEHPad() == IsEHPad &&
1850 "EHPad mismatch between block and work list.");
1851 assert(BlockToChain[BestBlock]->UnscheduledPredecessors == 0 &&
1852 "Found CFG-violating block");
1853
1854#ifdef EXPENSIVE_CHECKS
1855 for (const WorkListEntry &E : WorkList) {
1856 const BlockChain *C = BlockToChain.lookup(E.BB);
1857 bool IsStale = !C || C == &Chain;
1858 if (IsStale)
1859 continue;
1860 assert(E.BB->isEHPad() == IsEHPad &&
1861 "EHPad mismatch between block and work list.");
1862 assert(C->UnscheduledPredecessors == 0 && "Found CFG-violating block");
1863 }
1864#endif
1865
1866 LLVM_DEBUG({
1867 for (const WorkListEntry &E : WorkList) {
1868 const BlockChain *C = BlockToChain.lookup(E.BB);
1869 bool IsStale = !C || C == &Chain;
1870 if (IsStale)
1871 continue;
1872 dbgs() << " " << getBlockName(E.BB) << " -> "
1873 << printBlockFreq(MBFI->getMBFI(), E.Freq) << " (freq)\n";
1874 }
1875 });
1876
1877 return BestBlock;
1878}
1879
1880/// Retrieve the first unplaced basic block in the entire function.
1881///
1882/// This routine is called when we are unable to use the CFG to walk through
1883/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
1884/// We walk through the function's blocks in order, starting from the
1885/// LastUnplacedBlockIt. We update this iterator on each call to avoid
1886/// re-scanning the entire sequence on repeated calls to this routine.
1887MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1888 const BlockChain &PlacedChain,
1889 MachineFunction::iterator &PrevUnplacedBlockIt) {
1890
1891 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
1892 ++I) {
1893 if (BlockChain *Chain = BlockToChain[&*I]; Chain != &PlacedChain) {
1894 PrevUnplacedBlockIt = I;
1895 // Now select the head of the chain to which the unplaced block belongs
1896 // as the block to place. This will force the entire chain to be placed,
1897 // and satisfies the requirements of merging chains.
1898 return *Chain->begin();
1899 }
1900 }
1901 return nullptr;
1902}
1903
1904/// Retrieve the first unplaced basic block among the blocks in BlockFilter.
1905///
1906/// This is similar to getFirstUnplacedBlock for the entire function, but since
1907/// the size of BlockFilter is typically far less than the number of blocks in
1908/// the entire function, iterating through the BlockFilter is more efficient.
1909/// When processing the entire funciton, using the version without BlockFilter
1910/// has a complexity of #(loops in function) * #(blocks in function), while this
1911/// version has a complexity of sum(#(loops in block) foreach block in function)
1912/// which is always smaller. For long function mostly sequential in structure,
1913/// the complexity is amortized to 1 * #(blocks in function).
1914MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1915 const BlockChain &PlacedChain,
1916 BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
1917 const BlockFilterSet *BlockFilter) {
1918 assert(BlockFilter);
1919 for (; PrevUnplacedBlockInFilterIt != BlockFilter->end();
1920 ++PrevUnplacedBlockInFilterIt) {
1921 BlockChain *C = BlockToChain[*PrevUnplacedBlockInFilterIt];
1922 if (C != &PlacedChain) {
1923 return *C->begin();
1924 }
1925 }
1926 return nullptr;
1927}
1928
1929void MachineBlockPlacement::fillWorkLists(
1930 const MachineBasicBlock *MBB, SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
1931 const BlockFilterSet *BlockFilter = nullptr) {
1932 BlockChain &Chain = *BlockToChain[MBB];
1933 if (!UpdatedPreds.insert(&Chain).second)
1934 return;
1935
1936 assert(
1937 Chain.UnscheduledPredecessors == 0 &&
1938 "Attempting to place block with unscheduled predecessors in worklist.");
1939 for (MachineBasicBlock *ChainBB : Chain) {
1940 assert(BlockToChain[ChainBB] == &Chain &&
1941 "Block in chain doesn't match BlockToChain map.");
1942 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1943 if (BlockFilter && !BlockFilter->count(Pred))
1944 continue;
1945 if (BlockToChain[Pred] == &Chain)
1946 continue;
1947 ++Chain.UnscheduledPredecessors;
1948 }
1949 }
1950
1951 if (Chain.UnscheduledPredecessors != 0)
1952 return;
1953
1954 addToWorkList(*Chain.begin());
1955}
1956
1957void MachineBlockPlacement::buildChain(const MachineBasicBlock *HeadBB,
1958 BlockChain &Chain,
1959 BlockFilterSet *BlockFilter) {
1960 assert(HeadBB && "BB must not be null.\n");
1961 assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
1962 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
1963 BlockFilterSet::iterator PrevUnplacedBlockInFilterIt;
1964 if (BlockFilter)
1965 PrevUnplacedBlockInFilterIt = BlockFilter->begin();
1966
1967 const MachineBasicBlock *LoopHeaderBB = HeadBB;
1968 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
1969 MachineBasicBlock *BB = *std::prev(Chain.end());
1970 while (true) {
1971 assert(BB && "null block found at end of chain in loop.");
1972 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1973 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1974
1975 // Look for the best viable successor if there is one to place immediately
1976 // after this block.
1977 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1978 MachineBasicBlock *BestSucc = Result.BB;
1979 bool ShouldTailDup = Result.ShouldTailDup;
1980 if (allowTailDupPlacement(*F))
1981 ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(
1982 BB, BestSucc, Chain, BlockFilter));
1983
1984 // If an immediate successor isn't available, look for the best viable
1985 // block among those we've identified as not violating the loop's CFG at
1986 // this point. This won't be a fallthrough, but it will increase locality.
1987 if (!BestSucc)
1988 BestSucc = selectBestCandidateBlock(Chain, /*IsEHPad=*/false);
1989 if (!BestSucc)
1990 BestSucc = selectBestCandidateBlock(Chain, /*IsEHPad=*/true);
1991
1992 if (!BestSucc) {
1993 if (BlockFilter)
1994 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockInFilterIt,
1995 BlockFilter);
1996 else
1997 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt);
1998 if (!BestSucc)
1999 break;
2000
2001 LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
2002 "layout successor until the CFG reduces\n");
2003 }
2004
2005 // Placement may have changed tail duplication opportunities.
2006 // Check for that now.
2007 if (allowTailDupPlacement(*F) && BestSucc && ShouldTailDup) {
2008 repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
2009 BlockFilter, PrevUnplacedBlockIt,
2010 PrevUnplacedBlockInFilterIt);
2011 // If the chosen successor was duplicated into BB, don't bother laying
2012 // it out, just go round the loop again with BB as the chain end.
2013 if (!BB->isSuccessor(BestSucc))
2014 continue;
2015 }
2016
2017 // Place this block, updating the datastructures to reflect its placement.
2018 BlockChain &SuccChain = *BlockToChain[BestSucc];
2019 // Zero out UnscheduledPredecessors for the successor we're about to merge
2020 // in case we selected a successor that didn't fit naturally into the CFG.
2021 SuccChain.UnscheduledPredecessors = 0;
2022 LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
2023 << getBlockName(BestSucc) << "\n");
2024 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
2025 Chain.merge(BestSucc, &SuccChain);
2026 BB = *std::prev(Chain.end());
2027 }
2028
2029 LLVM_DEBUG(dbgs() << "Finished forming chain for header block "
2030 << getBlockName(*Chain.begin()) << "\n");
2031}
2032
2033// If bottom of block BB has only one successor OldTop, in most cases it is
2034// profitable to move it before OldTop, except the following case:
2035//
2036// -->OldTop<-
2037// | . |
2038// | . |
2039// | . |
2040// ---Pred |
2041// | |
2042// BB-----
2043//
2044// If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't
2045// layout the other successor below it, so it can't reduce taken branch.
2046// In this case we keep its original layout.
2047bool MachineBlockPlacement::canMoveBottomBlockToTop(
2048 const MachineBasicBlock *BottomBlock, const MachineBasicBlock *OldTop) {
2049 if (BottomBlock->pred_size() != 1)
2050 return true;
2051 MachineBasicBlock *Pred = *BottomBlock->pred_begin();
2052 if (Pred->succ_size() != 2)
2053 return true;
2054
2055 MachineBasicBlock *OtherBB = *Pred->succ_begin();
2056 if (OtherBB == BottomBlock)
2057 OtherBB = *Pred->succ_rbegin();
2058 if (OtherBB == OldTop)
2059 return false;
2060
2061 return true;
2062}
2063
2064// Find out the possible fall through frequence to the top of a loop.
2065BlockFrequency
2066MachineBlockPlacement::TopFallThroughFreq(const MachineBasicBlock *Top,
2067 const BlockFilterSet &LoopBlockSet) {
2068 BlockFrequency MaxFreq = BlockFrequency(0);
2069 for (MachineBasicBlock *Pred : Top->predecessors()) {
2070 BlockChain *PredChain = BlockToChain[Pred];
2071 if (!LoopBlockSet.count(Pred) &&
2072 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2073 // Found a Pred block can be placed before Top.
2074 // Check if Top is the best successor of Pred.
2075 auto TopProb = MBPI->getEdgeProbability(Pred, Top);
2076 bool TopOK = true;
2077 for (MachineBasicBlock *Succ : Pred->successors()) {
2078 auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
2079 BlockChain *SuccChain = BlockToChain[Succ];
2080 // Check if Succ can be placed after Pred.
2081 // Succ should not be in any chain, or it is the head of some chain.
2082 if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) &&
2083 (!SuccChain || Succ == *SuccChain->begin())) {
2084 TopOK = false;
2085 break;
2086 }
2087 }
2088 if (TopOK) {
2089 BlockFrequency EdgeFreq =
2090 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Top);
2091 if (EdgeFreq > MaxFreq)
2092 MaxFreq = EdgeFreq;
2093 }
2094 }
2095 }
2096 return MaxFreq;
2097}
2098
2099// Compute the fall through gains when move NewTop before OldTop.
2100//
2101// In following diagram, edges marked as "-" are reduced fallthrough, edges
2102// marked as "+" are increased fallthrough, this function computes
2103//
2104// SUM(increased fallthrough) - SUM(decreased fallthrough)
2105//
2106// |
2107// | -
2108// V
2109// --->OldTop
2110// | .
2111// | .
2112// +| . +
2113// | Pred --->
2114// | |-
2115// | V
2116// --- NewTop <---
2117// |-
2118// V
2119//
2120BlockFrequency MachineBlockPlacement::FallThroughGains(
2121 const MachineBasicBlock *NewTop, const MachineBasicBlock *OldTop,
2122 const MachineBasicBlock *ExitBB, const BlockFilterSet &LoopBlockSet) {
2123 BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet);
2124 BlockFrequency FallThrough2Exit = BlockFrequency(0);
2125 if (ExitBB)
2126 FallThrough2Exit =
2127 MBFI->getBlockFreq(NewTop) * MBPI->getEdgeProbability(NewTop, ExitBB);
2128 BlockFrequency BackEdgeFreq =
2129 MBFI->getBlockFreq(NewTop) * MBPI->getEdgeProbability(NewTop, OldTop);
2130
2131 // Find the best Pred of NewTop.
2132 MachineBasicBlock *BestPred = nullptr;
2133 BlockFrequency FallThroughFromPred = BlockFrequency(0);
2134 for (MachineBasicBlock *Pred : NewTop->predecessors()) {
2135 if (!LoopBlockSet.count(Pred))
2136 continue;
2137 BlockChain *PredChain = BlockToChain[Pred];
2138 if (!PredChain || Pred == *std::prev(PredChain->end())) {
2139 BlockFrequency EdgeFreq =
2140 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, NewTop);
2141 if (EdgeFreq > FallThroughFromPred) {
2142 FallThroughFromPred = EdgeFreq;
2143 BestPred = Pred;
2144 }
2145 }
2146 }
2147
2148 // If NewTop is not placed after Pred, another successor can be placed
2149 // after Pred.
2150 BlockFrequency NewFreq = BlockFrequency(0);
2151 if (BestPred) {
2152 for (MachineBasicBlock *Succ : BestPred->successors()) {
2153 if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ))
2154 continue;
2155 if (ComputedEdges.contains(Succ))
2156 continue;
2157 BlockChain *SuccChain = BlockToChain[Succ];
2158 if ((SuccChain && (Succ != *SuccChain->begin())) ||
2159 (SuccChain == BlockToChain[BestPred]))
2160 continue;
2161 BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) *
2162 MBPI->getEdgeProbability(BestPred, Succ);
2163 if (EdgeFreq > NewFreq)
2164 NewFreq = EdgeFreq;
2165 }
2166 BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) *
2167 MBPI->getEdgeProbability(BestPred, NewTop);
2168 if (NewFreq > OrigEdgeFreq) {
2169 // If NewTop is not the best successor of Pred, then Pred doesn't
2170 // fallthrough to NewTop. So there is no FallThroughFromPred and
2171 // NewFreq.
2172 NewFreq = BlockFrequency(0);
2173 FallThroughFromPred = BlockFrequency(0);
2174 }
2175 }
2176
2177 BlockFrequency Result = BlockFrequency(0);
2178 BlockFrequency Gains = BackEdgeFreq + NewFreq;
2179 BlockFrequency Lost =
2180 FallThrough2Top + FallThrough2Exit + FallThroughFromPred;
2181 if (Gains > Lost)
2182 Result = Gains - Lost;
2183 return Result;
2184}
2185
2186/// Helper function of findBestLoopTop. Find the best loop top block
2187/// from predecessors of old top.
2188///
2189/// Look for a block which is strictly better than the old top for laying
2190/// out before the old top of the loop. This looks for only two patterns:
2191///
2192/// 1. a block has only one successor, the old loop top
2193///
2194/// Because such a block will always result in an unconditional jump,
2195/// rotating it in front of the old top is always profitable.
2196///
2197/// 2. a block has two successors, one is old top, another is exit
2198/// and it has more than one predecessors
2199///
2200/// If it is below one of its predecessors P, only P can fall through to
2201/// it, all other predecessors need a jump to it, and another conditional
2202/// jump to loop header. If it is moved before loop header, all its
2203/// predecessors jump to it, then fall through to loop header. So all its
2204/// predecessors except P can reduce one taken branch.
2205/// At the same time, move it before old top increases the taken branch
2206/// to loop exit block, so the reduced taken branch will be compared with
2207/// the increased taken branch to the loop exit block.
2208MachineBasicBlock *MachineBlockPlacement::findBestLoopTopHelper(
2209 MachineBasicBlock *OldTop, const MachineLoop &L,
2210 const BlockFilterSet &LoopBlockSet) {
2211 // Check that the header hasn't been fused with a preheader block due to
2212 // crazy branches. If it has, we need to start with the header at the top to
2213 // prevent pulling the preheader into the loop body.
2214 BlockChain &HeaderChain = *BlockToChain[OldTop];
2215 if (!LoopBlockSet.count(*HeaderChain.begin()))
2216 return OldTop;
2217 if (OldTop != *HeaderChain.begin())
2218 return OldTop;
2219
2220 LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop)
2221 << "\n");
2222
2223 BlockFrequency BestGains = BlockFrequency(0);
2224 MachineBasicBlock *BestPred = nullptr;
2225 for (MachineBasicBlock *Pred : OldTop->predecessors()) {
2226 if (!LoopBlockSet.count(Pred))
2227 continue;
2228 if (Pred == L.getHeader())
2229 continue;
2230 LLVM_DEBUG(dbgs() << " old top pred: " << getBlockName(Pred) << ", has "
2231 << Pred->succ_size() << " successors, "
2232 << printBlockFreq(MBFI->getMBFI(), *Pred) << " freq\n");
2233 if (Pred->succ_size() > 2)
2234 continue;
2235
2236 MachineBasicBlock *OtherBB = nullptr;
2237 if (Pred->succ_size() == 2) {
2238 OtherBB = *Pred->succ_begin();
2239 if (OtherBB == OldTop)
2240 OtherBB = *Pred->succ_rbegin();
2241 }
2242
2243 if (!canMoveBottomBlockToTop(Pred, OldTop))
2244 continue;
2245
2246 BlockFrequency Gains =
2247 FallThroughGains(Pred, OldTop, OtherBB, LoopBlockSet);
2248 if ((Gains > BlockFrequency(0)) &&
2249 (Gains > BestGains ||
2250 ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) {
2251 BestPred = Pred;
2252 BestGains = Gains;
2253 }
2254 }
2255
2256 // If no direct predecessor is fine, just use the loop header.
2257 if (!BestPred) {
2258 LLVM_DEBUG(dbgs() << " final top unchanged\n");
2259 return OldTop;
2260 }
2261
2262 // Walk backwards through any straight line of predecessors.
2263 while (BestPred->pred_size() == 1 &&
2264 (*BestPred->pred_begin())->succ_size() == 1 &&
2265 *BestPred->pred_begin() != L.getHeader())
2266 BestPred = *BestPred->pred_begin();
2267
2268 LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
2269 return BestPred;
2270}
2271
2272/// Find the best loop top block for layout.
2273///
2274/// This function iteratively calls findBestLoopTopHelper, until no new better
2275/// BB can be found.
2276MachineBasicBlock *
2277MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
2278 const BlockFilterSet &LoopBlockSet) {
2279 // Placing the latch block before the header may introduce an extra branch
2280 // that skips this block the first time the loop is executed, which we want
2281 // to avoid when optimising for size.
2282 // FIXME: in theory there is a case that does not introduce a new branch,
2283 // i.e. when the layout predecessor does not fallthrough to the loop header.
2284 // In practice this never happens though: there always seems to be a preheader
2285 // that can fallthrough and that is also placed before the header.
2286 if (llvm::shouldOptimizeForSize(L.getHeader(), PSI, MBFI.get()))
2287 return L.getHeader();
2288
2289 MachineBasicBlock *OldTop = nullptr;
2290 MachineBasicBlock *NewTop = L.getHeader();
2291 while (NewTop != OldTop) {
2292 OldTop = NewTop;
2293 NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet);
2294 if (NewTop != OldTop)
2295 ComputedEdges[NewTop] = {OldTop, false};
2296 }
2297 return NewTop;
2298}
2299
2300/// Find the best loop exiting block for layout.
2301///
2302/// This routine implements the logic to analyze the loop looking for the best
2303/// block to layout at the top of the loop. Typically this is done to maximize
2304/// fallthrough opportunities.
2305MachineBasicBlock *
2306MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
2307 const BlockFilterSet &LoopBlockSet,
2308 BlockFrequency &ExitFreq) {
2309 // We don't want to layout the loop linearly in all cases. If the loop header
2310 // is just a normal basic block in the loop, we want to look for what block
2311 // within the loop is the best one to layout at the top. However, if the loop
2312 // header has be pre-merged into a chain due to predecessors not having
2313 // analyzable branches, *and* the predecessor it is merged with is *not* part
2314 // of the loop, rotating the header into the middle of the loop will create
2315 // a non-contiguous range of blocks which is Very Bad. So start with the
2316 // header and only rotate if safe.
2317 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
2318 if (!LoopBlockSet.count(*HeaderChain.begin()))
2319 return nullptr;
2320
2321 BlockFrequency BestExitEdgeFreq;
2322 unsigned BestExitLoopDepth = 0;
2323 MachineBasicBlock *ExitingBB = nullptr;
2324 // If there are exits to outer loops, loop rotation can severely limit
2325 // fallthrough opportunities unless it selects such an exit. Keep a set of
2326 // blocks where rotating to exit with that block will reach an outer loop.
2327 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
2328
2329 LLVM_DEBUG(dbgs() << "Finding best loop exit for: "
2330 << getBlockName(L.getHeader()) << "\n");
2331 for (MachineBasicBlock *MBB : L.getBlocks()) {
2332 BlockChain &Chain = *BlockToChain[MBB];
2333 // Ensure that this block is at the end of a chain; otherwise it could be
2334 // mid-way through an inner loop or a successor of an unanalyzable branch.
2335 if (MBB != *std::prev(Chain.end()))
2336 continue;
2337
2338 // Now walk the successors. We need to establish whether this has a viable
2339 // exiting successor and whether it has a viable non-exiting successor.
2340 // We store the old exiting state and restore it if a viable looping
2341 // successor isn't found.
2342 MachineBasicBlock *OldExitingBB = ExitingBB;
2343 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
2344 bool HasLoopingSucc = false;
2345 for (MachineBasicBlock *Succ : MBB->successors()) {
2346 if (Succ->isEHPad())
2347 continue;
2348 if (Succ == MBB)
2349 continue;
2350 BlockChain &SuccChain = *BlockToChain[Succ];
2351 // Don't split chains, either this chain or the successor's chain.
2352 if (&Chain == &SuccChain) {
2353 LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
2354 << getBlockName(Succ) << " (chain conflict)\n");
2355 continue;
2356 }
2357
2358 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
2359 if (LoopBlockSet.count(Succ)) {
2360 LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
2361 << getBlockName(Succ) << " (" << SuccProb << ")\n");
2362 HasLoopingSucc = true;
2363 continue;
2364 }
2365
2366 unsigned SuccLoopDepth = 0;
2367 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
2368 SuccLoopDepth = ExitLoop->getLoopDepth();
2369 if (ExitLoop->contains(&L))
2370 BlocksExitingToOuterLoop.insert(MBB);
2371 }
2372
2373 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
2374 LLVM_DEBUG(
2375 dbgs() << " exiting: " << getBlockName(MBB) << " -> "
2376 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] ("
2377 << printBlockFreq(MBFI->getMBFI(), ExitEdgeFreq) << ")\n");
2378 // Note that we bias this toward an existing layout successor to retain
2379 // incoming order in the absence of better information. The exit must have
2380 // a frequency higher than the current exit before we consider breaking
2381 // the layout.
2382 BranchProbability Bias(100 - ExitBlockBias, 100);
2383 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
2384 ExitEdgeFreq > BestExitEdgeFreq ||
2385 (MBB->isLayoutSuccessor(Succ) &&
2386 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
2387 BestExitEdgeFreq = ExitEdgeFreq;
2388 ExitingBB = MBB;
2389 }
2390 }
2391
2392 if (!HasLoopingSucc) {
2393 // Restore the old exiting state, no viable looping successor was found.
2394 ExitingBB = OldExitingBB;
2395 BestExitEdgeFreq = OldBestExitEdgeFreq;
2396 }
2397 }
2398 // Without a candidate exiting block or with only a single block in the
2399 // loop, just use the loop header to layout the loop.
2400 if (!ExitingBB) {
2401 LLVM_DEBUG(
2402 dbgs() << " No other candidate exit blocks, using loop header\n");
2403 return nullptr;
2404 }
2405 if (L.getNumBlocks() == 1) {
2406 LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
2407 return nullptr;
2408 }
2409
2410 // Also, if we have exit blocks which lead to outer loops but didn't select
2411 // one of them as the exiting block we are rotating toward, disable loop
2412 // rotation altogether.
2413 if (!BlocksExitingToOuterLoop.empty() &&
2414 !BlocksExitingToOuterLoop.count(ExitingBB))
2415 return nullptr;
2416
2417 LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB)
2418 << "\n");
2419 ExitFreq = BestExitEdgeFreq;
2420 return ExitingBB;
2421}
2422
2423/// Check if there is a fallthrough to loop header Top.
2424///
2425/// 1. Look for a Pred that can be layout before Top.
2426/// 2. Check if Top is the most possible successor of Pred.
2427bool MachineBlockPlacement::hasViableTopFallthrough(
2428 const MachineBasicBlock *Top, const BlockFilterSet &LoopBlockSet) {
2429 for (MachineBasicBlock *Pred : Top->predecessors()) {
2430 BlockChain *PredChain = BlockToChain[Pred];
2431 if (!LoopBlockSet.count(Pred) &&
2432 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2433 // Found a Pred block can be placed before Top.
2434 // Check if Top is the best successor of Pred.
2435 auto TopProb = MBPI->getEdgeProbability(Pred, Top);
2436 bool TopOK = true;
2437 for (MachineBasicBlock *Succ : Pred->successors()) {
2438 auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
2439 BlockChain *SuccChain = BlockToChain[Succ];
2440 // Check if Succ can be placed after Pred.
2441 // Succ should not be in any chain, or it is the head of some chain.
2442 if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
2443 TopOK = false;
2444 break;
2445 }
2446 }
2447 if (TopOK)
2448 return true;
2449 }
2450 }
2451 return false;
2452}
2453
2454/// Attempt to rotate an exiting block to the bottom of the loop.
2455///
2456/// Once we have built a chain, try to rotate it to line up the hot exit block
2457/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
2458/// branches. For example, if the loop has fallthrough into its header and out
2459/// of its bottom already, don't rotate it.
2460void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
2461 const MachineBasicBlock *ExitingBB,
2462 BlockFrequency ExitFreq,
2463 const BlockFilterSet &LoopBlockSet) {
2464 if (!ExitingBB)
2465 return;
2466
2467 MachineBasicBlock *Top = *LoopChain.begin();
2468 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
2469
2470 // If ExitingBB is already the last one in a chain then nothing to do.
2471 if (Bottom == ExitingBB)
2472 return;
2473
2474 // The entry block should always be the first BB in a function.
2475 if (Top->isEntryBlock())
2476 return;
2477
2478 bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
2479
2480 // If the header has viable fallthrough, check whether the current loop
2481 // bottom is a viable exiting block. If so, bail out as rotating will
2482 // introduce an unnecessary branch.
2483 if (ViableTopFallthrough) {
2484 for (MachineBasicBlock *Succ : Bottom->successors()) {
2485 BlockChain *SuccChain = BlockToChain[Succ];
2486 if (!LoopBlockSet.count(Succ) &&
2487 (!SuccChain || Succ == *SuccChain->begin()))
2488 return;
2489 }
2490
2491 // Rotate will destroy the top fallthrough, we need to ensure the new exit
2492 // frequency is larger than top fallthrough.
2493 BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet);
2494 if (FallThrough2Top >= ExitFreq)
2495 return;
2496 }
2497
2498 BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
2499 if (ExitIt == LoopChain.end())
2500 return;
2501
2502 // Rotating a loop exit to the bottom when there is a fallthrough to top
2503 // trades the entry fallthrough for an exit fallthrough.
2504 // If there is no bottom->top edge, but the chosen exit block does have
2505 // a fallthrough, we break that fallthrough for nothing in return.
2506
2507 // Let's consider an example. We have a built chain of basic blocks
2508 // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
2509 // By doing a rotation we get
2510 // Bk+1, ..., Bn, B1, ..., Bk
2511 // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
2512 // If we had a fallthrough Bk -> Bk+1 it is broken now.
2513 // It might be compensated by fallthrough Bn -> B1.
2514 // So we have a condition to avoid creation of extra branch by loop rotation.
2515 // All below must be true to avoid loop rotation:
2516 // If there is a fallthrough to top (B1)
2517 // There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
2518 // There is no fallthrough from bottom (Bn) to top (B1).
2519 // Please note that there is no exit fallthrough from Bn because we checked it
2520 // above.
2521 if (ViableTopFallthrough) {
2522 assert(std::next(ExitIt) != LoopChain.end() &&
2523 "Exit should not be last BB");
2524 MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
2525 if (ExitingBB->isSuccessor(NextBlockInChain))
2526 if (!Bottom->isSuccessor(Top))
2527 return;
2528 }
2529
2530 LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
2531 << " at bottom\n");
2532 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
2533}
2534
2535/// Attempt to rotate a loop based on profile data to reduce branch cost.
2536///
2537/// With profile data, we can determine the cost in terms of missed fall through
2538/// opportunities when rotating a loop chain and select the best rotation.
2539/// Basically, there are three kinds of cost to consider for each rotation:
2540/// 1. The possibly missed fall through edge (if it exists) from BB out of
2541/// the loop to the loop header.
2542/// 2. The possibly missed fall through edges (if they exist) from the loop
2543/// exits to BB out of the loop.
2544/// 3. The missed fall through edge (if it exists) from the last BB to the
2545/// first BB in the loop chain.
2546/// Therefore, the cost for a given rotation is the sum of costs listed above.
2547/// We select the best rotation with the smallest cost.
2548void MachineBlockPlacement::rotateLoopWithProfile(
2549 BlockChain &LoopChain, const MachineLoop &L,
2550 const BlockFilterSet &LoopBlockSet) {
2551 auto RotationPos = LoopChain.end();
2552 MachineBasicBlock *ChainHeaderBB = *LoopChain.begin();
2553
2554 // The entry block should always be the first BB in a function.
2555 if (ChainHeaderBB->isEntryBlock())
2556 return;
2557
2558 BlockFrequency SmallestRotationCost = BlockFrequency::max();
2559
2560 // A utility lambda that scales up a block frequency by dividing it by a
2561 // branch probability which is the reciprocal of the scale.
2562 auto ScaleBlockFrequency = [](BlockFrequency Freq,
2563 unsigned Scale) -> BlockFrequency {
2564 if (Scale == 0)
2565 return BlockFrequency(0);
2566 // Use operator / between BlockFrequency and BranchProbability to implement
2567 // saturating multiplication.
2568 return Freq / BranchProbability(1, Scale);
2569 };
2570
2571 // Compute the cost of the missed fall-through edge to the loop header if the
2572 // chain head is not the loop header. As we only consider natural loops with
2573 // single header, this computation can be done only once.
2574 BlockFrequency HeaderFallThroughCost(0);
2575 for (auto *Pred : ChainHeaderBB->predecessors()) {
2576 BlockChain *PredChain = BlockToChain[Pred];
2577 if (!LoopBlockSet.count(Pred) &&
2578 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2579 auto EdgeFreq = MBFI->getBlockFreq(Pred) *
2580 MBPI->getEdgeProbability(Pred, ChainHeaderBB);
2581 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
2582 // If the predecessor has only an unconditional jump to the header, we
2583 // need to consider the cost of this jump.
2584 if (Pred->succ_size() == 1)
2585 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
2586 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
2587 }
2588 }
2589
2590 // Here we collect all exit blocks in the loop, and for each exit we find out
2591 // its hottest exit edge. For each loop rotation, we define the loop exit cost
2592 // as the sum of frequencies of exit edges we collect here, excluding the exit
2593 // edge from the tail of the loop chain.
2595 for (auto *BB : LoopChain) {
2596 auto LargestExitEdgeProb = BranchProbability::getZero();
2597 for (auto *Succ : BB->successors()) {
2598 BlockChain *SuccChain = BlockToChain[Succ];
2599 if (!LoopBlockSet.count(Succ) &&
2600 (!SuccChain || Succ == *SuccChain->begin())) {
2601 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2602 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
2603 }
2604 }
2605 if (LargestExitEdgeProb > BranchProbability::getZero()) {
2606 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
2607 ExitsWithFreq.emplace_back(BB, ExitFreq);
2608 }
2609 }
2610
2611 // In this loop we iterate every block in the loop chain and calculate the
2612 // cost assuming the block is the head of the loop chain. When the loop ends,
2613 // we should have found the best candidate as the loop chain's head.
2614 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2615 EndIter = LoopChain.end();
2616 Iter != EndIter; Iter++, TailIter++) {
2617 // TailIter is used to track the tail of the loop chain if the block we are
2618 // checking (pointed by Iter) is the head of the chain.
2619 if (TailIter == LoopChain.end())
2620 TailIter = LoopChain.begin();
2621
2622 auto TailBB = *TailIter;
2623
2624 // Calculate the cost by putting this BB to the top.
2625 BlockFrequency Cost = BlockFrequency(0);
2626
2627 // If the current BB is the loop header, we need to take into account the
2628 // cost of the missed fall through edge from outside of the loop to the
2629 // header.
2630 if (Iter != LoopChain.begin())
2631 Cost += HeaderFallThroughCost;
2632
2633 // Collect the loop exit cost by summing up frequencies of all exit edges
2634 // except the one from the chain tail.
2635 for (auto &ExitWithFreq : ExitsWithFreq)
2636 if (TailBB != ExitWithFreq.first)
2637 Cost += ExitWithFreq.second;
2638
2639 // The cost of breaking the once fall-through edge from the tail to the top
2640 // of the loop chain. Here we need to consider three cases:
2641 // 1. If the tail node has only one successor, then we will get an
2642 // additional jmp instruction. So the cost here is (MisfetchCost +
2643 // JumpInstCost) * tail node frequency.
2644 // 2. If the tail node has two successors, then we may still get an
2645 // additional jmp instruction if the layout successor after the loop
2646 // chain is not its CFG successor. Note that the more frequently executed
2647 // jmp instruction will be put ahead of the other one. Assume the
2648 // frequency of those two branches are x and y, where x is the frequency
2649 // of the edge to the chain head, then the cost will be
2650 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
2651 // 3. If the tail node has more than two successors (this rarely happens),
2652 // we won't consider any additional cost.
2653 if (TailBB->isSuccessor(*Iter)) {
2654 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2655 if (TailBB->succ_size() == 1)
2656 Cost += ScaleBlockFrequency(TailBBFreq, MisfetchCost + JumpInstCost);
2657 else if (TailBB->succ_size() == 2) {
2658 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2659 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2660 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2661 ? TailBBFreq * TailToHeadProb.getCompl()
2662 : TailToHeadFreq;
2663 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
2664 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
2665 }
2666 }
2667
2668 LLVM_DEBUG(dbgs() << "The cost of loop rotation by making "
2669 << getBlockName(*Iter) << " to the top: "
2670 << printBlockFreq(MBFI->getMBFI(), Cost) << "\n");
2671
2672 if (Cost < SmallestRotationCost) {
2673 SmallestRotationCost = Cost;
2674 RotationPos = Iter;
2675 }
2676 }
2677
2678 if (RotationPos != LoopChain.end()) {
2679 LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
2680 << " to the top\n");
2681 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2682 }
2683}
2684
2685/// Collect blocks in the given loop that are to be placed.
2686///
2687/// When profile data is available, exclude cold blocks from the returned set;
2688/// otherwise, collect all blocks in the loop.
2689MachineBlockPlacement::BlockFilterSet
2690MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
2691 // Collect the blocks in a set ordered by block number, as this gives the same
2692 // order as they appear in the function.
2693 struct MBBCompare {
2694 bool operator()(const MachineBasicBlock *X,
2695 const MachineBasicBlock *Y) const {
2696 return X->getNumber() < Y->getNumber();
2697 }
2698 };
2699 std::set<const MachineBasicBlock *, MBBCompare> LoopBlockSet;
2700
2701 // Filter cold blocks off from LoopBlockSet when profile data is available.
2702 // Collect the sum of frequencies of incoming edges to the loop header from
2703 // outside. If we treat the loop as a super block, this is the frequency of
2704 // the loop. Then for each block in the loop, we calculate the ratio between
2705 // its frequency and the frequency of the loop block. When it is too small,
2706 // don't add it to the loop chain. If there are outer loops, then this block
2707 // will be merged into the first outer loop chain for which this block is not
2708 // cold anymore. This needs precise profile data and we only do this when
2709 // profile data is available.
2710 if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
2711 BlockFrequency LoopFreq(0);
2712 for (auto *LoopPred : L.getHeader()->predecessors())
2713 if (!L.contains(LoopPred))
2714 LoopFreq += MBFI->getBlockFreq(LoopPred) *
2715 MBPI->getEdgeProbability(LoopPred, L.getHeader());
2716
2717 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2718 if (LoopBlockSet.count(LoopBB))
2719 continue;
2720 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2721 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2722 continue;
2723 BlockChain *Chain = BlockToChain[LoopBB];
2724 for (MachineBasicBlock *ChainBB : *Chain)
2725 LoopBlockSet.insert(ChainBB);
2726 }
2727 } else
2728 LoopBlockSet.insert(L.block_begin(), L.block_end());
2729
2730 // Copy the blocks into a BlockFilterSet, as iterating it is faster than
2731 // std::set. We will only remove blocks and never insert them, which will
2732 // preserve the ordering.
2733 BlockFilterSet Ret(LoopBlockSet.begin(), LoopBlockSet.end());
2734 return Ret;
2735}
2736
2737/// Forms basic block chains from the natural loop structures.
2738///
2739/// These chains are designed to preserve the existing *structure* of the code
2740/// as much as possible. We can then stitch the chains together in a way which
2741/// both preserves the topological structure and minimizes taken conditional
2742/// branches.
2743void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
2744 // First recurse through any nested loops, building chains for those inner
2745 // loops.
2746 for (const MachineLoop *InnerLoop : L)
2747 buildLoopChains(*InnerLoop);
2748
2749 assert(BlockWorkList.empty() &&
2750 "BlockWorkList not empty when starting to build loop chains.");
2751 assert(EHPadWorkList.empty() &&
2752 "EHPadWorkList not empty when starting to build loop chains.");
2753 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
2754
2755 // Check if we have profile data for this function. If yes, we will rotate
2756 // this loop by modeling costs more precisely which requires the profile data
2757 // for better layout.
2758 bool RotateLoopWithProfile =
2760 (PreciseRotationCost && F->getFunction().hasProfileData());
2761
2762 // First check to see if there is an obviously preferable top block for the
2763 // loop. This will default to the header, but may end up as one of the
2764 // predecessors to the header if there is one which will result in strictly
2765 // fewer branches in the loop body.
2766 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
2767
2768 // If we selected just the header for the loop top, look for a potentially
2769 // profitable exit block in the event that rotating the loop can eliminate
2770 // branches by placing an exit edge at the bottom.
2771 //
2772 // Loops are processed innermost to uttermost, make sure we clear
2773 // PreferredLoopExit before processing a new loop.
2774 PreferredLoopExit = nullptr;
2775 BlockFrequency ExitFreq;
2776 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
2777 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq);
2778
2779 BlockChain &LoopChain = *BlockToChain[LoopTop];
2780
2781 // FIXME: This is a really lame way of walking the chains in the loop: we
2782 // walk the blocks, and use a set to prevent visiting a particular chain
2783 // twice.
2784 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2785 assert(LoopChain.UnscheduledPredecessors == 0 &&
2786 "LoopChain should not have unscheduled predecessors.");
2787 UpdatedPreds.insert(&LoopChain);
2788
2789 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2790 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
2791
2792 buildChain(LoopTop, LoopChain, &LoopBlockSet);
2793
2794 if (RotateLoopWithProfile)
2795 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2796 else
2797 rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet);
2798
2799 LLVM_DEBUG({
2800 // Crash at the end so we get all of the debugging output first.
2801 bool BadLoop = false;
2802 if (LoopChain.UnscheduledPredecessors) {
2803 BadLoop = true;
2804 dbgs() << "Loop chain contains a block without its preds placed!\n"
2805 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2806 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
2807 }
2808 for (MachineBasicBlock *ChainBB : LoopChain) {
2809 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
2810 if (!LoopBlockSet.remove(ChainBB)) {
2811 // We don't mark the loop as bad here because there are real situations
2812 // where this can occur. For example, with an unanalyzable fallthrough
2813 // from a loop block to a non-loop block or vice versa.
2814 dbgs() << "Loop chain contains a block not contained by the loop!\n"
2815 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2816 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2817 << " Bad block: " << getBlockName(ChainBB) << "\n";
2818 }
2819 }
2820
2821 if (!LoopBlockSet.empty()) {
2822 BadLoop = true;
2823 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2824 dbgs() << "Loop contains blocks never placed into a chain!\n"
2825 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2826 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2827 << " Bad block: " << getBlockName(LoopBB) << "\n";
2828 }
2829 assert(!BadLoop && "Detected problems with the placement of this loop.");
2830 });
2831
2832 BlockWorkList.clear();
2833 EHPadWorkList.clear();
2834}
2835
2836void MachineBlockPlacement::buildCFGChains() {
2837 // Ensure that every BB in the function has an associated chain to simplify
2838 // the assumptions of the remaining algorithm.
2839 SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
2840 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2841 ++FI) {
2842 MachineBasicBlock *BB = &*FI;
2843 BlockChain *Chain =
2844 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
2845 // Also, merge any blocks which we cannot reason about and must preserve
2846 // the exact fallthrough behavior for.
2847 while (true) {
2848 Cond.clear();
2849 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2850 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
2851 break;
2852
2853 MachineFunction::iterator NextFI = std::next(FI);
2854 MachineBasicBlock *NextBB = &*NextFI;
2855 // Ensure that the layout successor is a viable block, as we know that
2856 // fallthrough is a possibility.
2857 assert(NextFI != FE && "Can't fallthrough past the last block.");
2858 LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2859 << getBlockName(BB) << " -> " << getBlockName(NextBB)
2860 << "\n");
2861 Chain->merge(NextBB, nullptr);
2862#ifndef NDEBUG
2863 BlocksWithUnanalyzableExits.insert(&*BB);
2864#endif
2865 FI = NextFI;
2866 BB = NextBB;
2867 }
2868 }
2869
2870 // Build any loop-based chains.
2871 PreferredLoopExit = nullptr;
2872 for (MachineLoop *L : *MLI)
2873 buildLoopChains(*L);
2874
2875 assert(BlockWorkList.empty() &&
2876 "BlockWorkList should be empty before building final chain.");
2877 assert(EHPadWorkList.empty() &&
2878 "EHPadWorkList should be empty before building final chain.");
2879
2880 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2881 for (MachineBasicBlock &MBB : *F)
2882 fillWorkLists(&MBB, UpdatedPreds);
2883
2884 BlockChain &FunctionChain = *BlockToChain[&F->front()];
2885 buildChain(&F->front(), FunctionChain);
2886
2887#ifndef NDEBUG
2888 using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
2889#endif
2890 LLVM_DEBUG({
2891 // Crash at the end so we get all of the debugging output first.
2892 bool BadFunc = false;
2893 FunctionBlockSetType FunctionBlockSet;
2894 for (MachineBasicBlock &MBB : *F)
2895 FunctionBlockSet.insert(&MBB);
2896
2897 for (MachineBasicBlock *ChainBB : FunctionChain)
2898 if (!FunctionBlockSet.erase(ChainBB)) {
2899 BadFunc = true;
2900 dbgs() << "Function chain contains a block not in the function!\n"
2901 << " Bad block: " << getBlockName(ChainBB) << "\n";
2902 }
2903
2904 if (!FunctionBlockSet.empty()) {
2905 BadFunc = true;
2906 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
2907 dbgs() << "Function contains blocks never placed into a chain!\n"
2908 << " Bad block: " << getBlockName(RemainingBB) << "\n";
2909 }
2910 assert(!BadFunc && "Detected problems with the block placement.");
2911 });
2912
2913 // Remember original layout ordering, so we can update terminators after
2914 // reordering to point to the original layout successor.
2915 SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors(
2916 F->getNumBlockIDs());
2917 {
2918 MachineBasicBlock *LastMBB = nullptr;
2919 for (auto &MBB : *F) {
2920 if (LastMBB != nullptr)
2921 OriginalLayoutSuccessors[LastMBB->getNumber()] = &MBB;
2922 LastMBB = &MBB;
2923 }
2924 OriginalLayoutSuccessors[F->back().getNumber()] = nullptr;
2925 }
2926
2927 // Splice the blocks into place.
2928 MachineFunction::iterator InsertPos = F->begin();
2929 LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n");
2930 for (MachineBasicBlock *ChainBB : FunctionChain) {
2931 LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2932 : " ... ")
2933 << getBlockName(ChainBB) << "\n");
2934 if (InsertPos != MachineFunction::iterator(ChainBB))
2935 F->splice(InsertPos, ChainBB);
2936 else
2937 ++InsertPos;
2938
2939 // Update the terminator of the previous block.
2940 if (ChainBB == *FunctionChain.begin())
2941 continue;
2942 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
2943
2944 // FIXME: It would be awesome of updateTerminator would just return rather
2945 // than assert when the branch cannot be analyzed in order to remove this
2946 // boiler plate.
2947 Cond.clear();
2948 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2949
2950#ifndef NDEBUG
2951 if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2952 // Given the exact block placement we chose, we may actually not _need_ to
2953 // be able to edit PrevBB's terminator sequence, but not being _able_ to
2954 // do that at this point is a bug.
2955 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2956 !PrevBB->canFallThrough()) &&
2957 "Unexpected block with un-analyzable fallthrough!");
2958 Cond.clear();
2959 TBB = FBB = nullptr;
2960 }
2961#endif
2962
2963 // The "PrevBB" is not yet updated to reflect current code layout, so,
2964 // o. it may fall-through to a block without explicit "goto" instruction
2965 // before layout, and no longer fall-through it after layout; or
2966 // o. just opposite.
2967 //
2968 // analyzeBranch() may return erroneous value for FBB when these two
2969 // situations take place. For the first scenario FBB is mistakenly set NULL;
2970 // for the 2nd scenario, the FBB, which is expected to be NULL, is
2971 // mistakenly pointing to "*BI".
2972 // Thus, if the future change needs to use FBB before the layout is set, it
2973 // has to correct FBB first by using the code similar to the following:
2974 //
2975 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2976 // PrevBB->updateTerminator();
2977 // Cond.clear();
2978 // TBB = FBB = nullptr;
2979 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
2980 // // FIXME: This should never take place.
2981 // TBB = FBB = nullptr;
2982 // }
2983 // }
2984 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
2985 PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]);
2986 }
2987 }
2988
2989 // Fixup the last block.
2990 Cond.clear();
2991 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2992 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) {
2993 MachineBasicBlock *PrevBB = &F->back();
2994 PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]);
2995 }
2996
2997 BlockWorkList.clear();
2998 EHPadWorkList.clear();
2999}
3000
3001void MachineBlockPlacement::optimizeBranches() {
3002 BlockChain &FunctionChain = *BlockToChain[&F->front()];
3003 SmallVector<MachineOperand, 4> Cond;
3004
3005 // Now that all the basic blocks in the chain have the proper layout,
3006 // make a final call to analyzeBranch with AllowModify set.
3007 // Indeed, the target may be able to optimize the branches in a way we
3008 // cannot because all branches may not be analyzable.
3009 // E.g., the target may be able to remove an unconditional branch to
3010 // a fallthrough when it occurs after predicated terminators.
3011 for (MachineBasicBlock *ChainBB : FunctionChain) {
3012 Cond.clear();
3013 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
3014 if (TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true))
3015 continue;
3016 if (!TBB || !FBB || Cond.empty())
3017 continue;
3018 // If we are optimizing for size we do not consider the runtime performance.
3019 // Instead, we retain the original branch condition so we have more uniform
3020 // instructions which will benefit ICF.
3021 if (llvm::shouldOptimizeForSize(ChainBB, PSI, MBFI.get()))
3022 continue;
3023 // If ChainBB has a two-way branch, try to re-order the branches
3024 // such that we branch to the successor with higher probability first.
3025 if (MBPI->getEdgeProbability(ChainBB, TBB) >=
3026 MBPI->getEdgeProbability(ChainBB, FBB))
3027 continue;
3029 continue;
3030 LLVM_DEBUG(dbgs() << "Reverse order of the two branches: "
3031 << getBlockName(ChainBB) << "\n");
3032 LLVM_DEBUG(dbgs() << " " << getBlockName(TBB) << " < " << getBlockName(FBB)
3033 << "\n");
3034 auto Dl = ChainBB->findBranchDebugLoc();
3035 TII->removeBranch(*ChainBB);
3036 TII->insertBranch(*ChainBB, FBB, TBB, Cond, Dl);
3037 }
3038}
3039
3040void MachineBlockPlacement::alignBlocks() {
3041 // Walk through the backedges of the function now that we have fully laid out
3042 // the basic blocks and align the destination of each backedge. We don't rely
3043 // exclusively on the loop info here so that we can align backedges in
3044 // unnatural CFGs and backedges that were introduced purely because of the
3045 // loop rotations done during this layout pass.
3047 if (F->getFunction().hasMinSize() ||
3048 (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize()))
3049 return;
3050 }
3051
3052 BlockChain &FunctionChain = *BlockToChain[&F->front()];
3053 // Empty chain.
3054 if (FunctionChain.begin() == FunctionChain.end())
3055 return;
3056
3057 const BranchProbability ColdProb(1, 5); // 20%
3058 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
3059 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
3060 for (MachineBasicBlock *ChainBB : FunctionChain) {
3061 if (ChainBB == *FunctionChain.begin())
3062 continue;
3063
3064 // Don't align non-looping basic blocks. These are unlikely to execute
3065 // enough times to matter in practice. Note that we'll still handle
3066 // unnatural CFGs inside of a natural outer loop (the common case) and
3067 // rotated loops.
3068 MachineLoop *L = MLI->getLoopFor(ChainBB);
3069 if (!L)
3070 continue;
3071
3072 // Query the block being aligned rather than only the LoopInfo header.
3073 // After loop rotation, ChainBB can be a different backedge destination.
3074 const Align TLIAlign = TLI->getPrefLoopAlignment(L, ChainBB);
3075 unsigned MDAlign = 1;
3076 MDNode *LoopID = L->getLoopID();
3077 if (LoopID) {
3078 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
3079 MDNode *MD = dyn_cast<MDNode>(MDO);
3080 if (MD == nullptr)
3081 continue;
3082 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
3083 if (S == nullptr)
3084 continue;
3085 if (S->getString() == "llvm.loop.align") {
3086 MDAlign =
3087 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
3088 }
3089 }
3090 }
3091
3092 // Use max of the TLIAlign and MDAlign
3093 const Align LoopAlign = std::max(TLIAlign, Align(MDAlign));
3094 if (LoopAlign == 1)
3095 continue; // Don't care about loop alignment.
3096
3097 // If the block is cold relative to the function entry don't waste space
3098 // aligning it.
3099 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
3100 if (Freq < WeightedEntryFreq)
3101 continue;
3102
3103 // If the block is cold relative to its loop header, don't align it
3104 // regardless of what edges into the block exist.
3105 MachineBasicBlock *LoopHeader = L->getHeader();
3106 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
3107 if (Freq < (LoopHeaderFreq * ColdProb))
3108 continue;
3109
3110 // If the global profiles indicates so, don't align it.
3111 if (llvm::shouldOptimizeForSize(ChainBB, PSI, MBFI.get()) &&
3113 continue;
3114
3115 // Check for the existence of a non-layout predecessor which would benefit
3116 // from aligning this block.
3117 MachineBasicBlock *LayoutPred =
3118 &*std::prev(MachineFunction::iterator(ChainBB));
3119
3120 auto DetermineMaxAlignmentPadding = [&]() {
3121 // Set the maximum bytes allowed to be emitted for alignment.
3122 unsigned MaxBytes;
3123 if (MaxBytesForAlignmentOverride.getNumOccurrences() > 0)
3125 else
3126 MaxBytes = TLI->getMaxPermittedBytesForAlignment(ChainBB);
3127 ChainBB->setMaxBytesForAlignment(MaxBytes);
3128 };
3129
3130 // Force alignment if all the predecessors are jumps. We already checked
3131 // that the block isn't cold above.
3132 if (!LayoutPred->isSuccessor(ChainBB)) {
3133 ChainBB->setAlignment(LoopAlign);
3134 DetermineMaxAlignmentPadding();
3135 continue;
3136 }
3137
3138 // Align this block if the layout predecessor's edge into this block is
3139 // cold relative to the block. When this is true, other predecessors make up
3140 // all of the hot entries into the block and thus alignment is likely to be
3141 // important.
3142 BranchProbability LayoutProb =
3143 MBPI->getEdgeProbability(LayoutPred, ChainBB);
3144 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
3145 if (LayoutEdgeFreq <= (Freq * ColdProb)) {
3146 ChainBB->setAlignment(LoopAlign);
3147 DetermineMaxAlignmentPadding();
3148 }
3149 }
3150
3151 const bool HasMaxBytesOverride =
3152 MaxBytesForAlignmentOverride.getNumOccurrences() > 0;
3153
3154 if (AlignAllBlock)
3155 // Align all of the blocks in the function to a specific alignment.
3156 for (MachineBasicBlock &MBB : *F) {
3157 if (HasMaxBytesOverride)
3160 else
3162 }
3163 else if (AlignAllNonFallThruBlocks) {
3164 // Align all of the blocks that have no fall-through predecessors to a
3165 // specific alignment.
3166 for (auto MBI = std::next(F->begin()), MBE = F->end(); MBI != MBE; ++MBI) {
3167 auto LayoutPred = std::prev(MBI);
3168 if (!LayoutPred->isSuccessor(&*MBI)) {
3169 if (HasMaxBytesOverride)
3170 MBI->setAlignment(Align::fromLog2(AlignAllNonFallThruBlocks),
3172 else
3173 MBI->setAlignment(Align::fromLog2(AlignAllNonFallThruBlocks));
3174 }
3175 }
3176 }
3177}
3178
3179/// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
3180/// it was duplicated into its chain predecessor and removed.
3181/// \p BB - Basic block that may be duplicated.
3182///
3183/// \p LPred - Chosen layout predecessor of \p BB.
3184/// Updated to be the chain end if LPred is removed.
3185/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
3186/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
3187/// Used to identify which blocks to update predecessor
3188/// counts.
3189/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
3190/// chosen in the given order due to unnatural CFG
3191/// only needed if \p BB is removed and
3192/// \p PrevUnplacedBlockIt pointed to \p BB.
3193/// @return true if \p BB was removed.
3194bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
3195 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
3196 const MachineBasicBlock *LoopHeaderBB, BlockChain &Chain,
3197 BlockFilterSet *BlockFilter, MachineFunction::iterator &PrevUnplacedBlockIt,
3198 BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt) {
3199 bool Removed, DuplicatedToLPred;
3200 bool DuplicatedToOriginalLPred;
3201 Removed = maybeTailDuplicateBlock(
3202 BB, LPred, Chain, BlockFilter, PrevUnplacedBlockIt,
3203 PrevUnplacedBlockInFilterIt, DuplicatedToLPred);
3204 if (!Removed)
3205 return false;
3206 DuplicatedToOriginalLPred = DuplicatedToLPred;
3207 // Iteratively try to duplicate again. It can happen that a block that is
3208 // duplicated into is still small enough to be duplicated again.
3209 // No need to call markBlockSuccessors in this case, as the blocks being
3210 // duplicated from here on are already scheduled.
3211 while (DuplicatedToLPred && Removed) {
3212 MachineBasicBlock *DupBB, *DupPred;
3213 // The removal callback causes Chain.end() to be updated when a block is
3214 // removed. On the first pass through the loop, the chain end should be the
3215 // same as it was on function entry. On subsequent passes, because we are
3216 // duplicating the block at the end of the chain, if it is removed the
3217 // chain will have shrunk by one block.
3218 BlockChain::iterator ChainEnd = Chain.end();
3219 DupBB = *(--ChainEnd);
3220 // Now try to duplicate again.
3221 if (ChainEnd == Chain.begin())
3222 break;
3223 DupPred = *std::prev(ChainEnd);
3224 Removed = maybeTailDuplicateBlock(
3225 DupBB, DupPred, Chain, BlockFilter, PrevUnplacedBlockIt,
3226 PrevUnplacedBlockInFilterIt, DuplicatedToLPred);
3227 }
3228 // If BB was duplicated into LPred, it is now scheduled. But because it was
3229 // removed, markChainSuccessors won't be called for its chain. Instead we
3230 // call markBlockSuccessors for LPred to achieve the same effect. This must go
3231 // at the end because repeating the tail duplication can increase the number
3232 // of unscheduled predecessors.
3233 LPred = *std::prev(Chain.end());
3234 if (DuplicatedToOriginalLPred)
3235 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
3236 return true;
3237}
3238
3239/// Tail duplicate \p BB into (some) predecessors if profitable.
3240/// \p BB - Basic block that may be duplicated
3241/// \p LPred - Chosen layout predecessor of \p BB
3242/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
3243/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
3244/// Used to identify which blocks to update predecessor
3245/// counts.
3246/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
3247/// chosen in the given order due to unnatural CFG
3248/// only needed if \p BB is removed and
3249/// \p PrevUnplacedBlockIt pointed to \p BB.
3250/// \p DuplicatedToLPred - True if the block was duplicated into LPred.
3251/// \return - True if the block was duplicated into all preds and removed.
3252bool MachineBlockPlacement::maybeTailDuplicateBlock(
3253 MachineBasicBlock *BB, MachineBasicBlock *LPred, BlockChain &Chain,
3254 BlockFilterSet *BlockFilter, MachineFunction::iterator &PrevUnplacedBlockIt,
3255 BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
3256 bool &DuplicatedToLPred) {
3257 DuplicatedToLPred = false;
3258 if (!shouldTailDuplicate(BB))
3259 return false;
3260
3261 LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber()
3262 << "\n");
3263
3264 // This has to be a callback because none of it can be done after
3265 // BB is deleted.
3266 bool Removed = false;
3267 auto RemovalCallback = [&](MachineBasicBlock *RemBB) {
3268 // Signal to outer function
3269 Removed = true;
3270
3271 // Remove from the Chain and Chain Map
3272 if (auto It = BlockToChain.find(RemBB); It != BlockToChain.end()) {
3273 It->second->remove(RemBB);
3274 BlockToChain.erase(It);
3275 }
3276
3277 // Handle the unplaced block iterator
3278 if (&(*PrevUnplacedBlockIt) == RemBB) {
3279 PrevUnplacedBlockIt++;
3280 }
3281
3282 // Not erased from the work lists: they are heaps and drop stale entries
3283 // lazily, see BlockWorkList.
3284
3285 // Handle the filter set
3286 if (BlockFilter) {
3287 auto It = llvm::find(*BlockFilter, RemBB);
3288 // Erase RemBB from BlockFilter, and keep PrevUnplacedBlockInFilterIt
3289 // pointing to the same element as before.
3290 if (It != BlockFilter->end()) {
3291 if (It < PrevUnplacedBlockInFilterIt) {
3292 const MachineBasicBlock *PrevBB = *PrevUnplacedBlockInFilterIt;
3293 // BlockFilter is a SmallVector so all elements after RemBB are
3294 // shifted to the front by 1 after its deletion.
3295 auto Distance = PrevUnplacedBlockInFilterIt - It - 1;
3296 PrevUnplacedBlockInFilterIt = BlockFilter->erase(It) + Distance;
3297 assert(*PrevUnplacedBlockInFilterIt == PrevBB);
3298 (void)PrevBB;
3299 } else if (It == PrevUnplacedBlockInFilterIt)
3300 // The block pointed by PrevUnplacedBlockInFilterIt is erased, we
3301 // have to set it to the next element.
3302 PrevUnplacedBlockInFilterIt = BlockFilter->erase(It);
3303 else
3304 BlockFilter->erase(It);
3305 }
3306 }
3307
3308 // Remove the block from loop info.
3309 MLI->removeBlock(RemBB);
3310 if (RemBB == PreferredLoopExit)
3311 PreferredLoopExit = nullptr;
3312
3313 LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: " << getBlockName(RemBB)
3314 << "\n");
3315 };
3316 auto RemovalCallbackRef =
3317 function_ref<void(MachineBasicBlock *)>(RemovalCallback);
3318
3320 bool IsSimple = TailDup.isSimpleBB(BB);
3322 SmallVectorImpl<MachineBasicBlock *> *CandidatePtr = nullptr;
3323 if (F->getFunction().hasProfileData()) {
3324 // We can do partial duplication with precise profile information.
3325 findDuplicateCandidates(CandidatePreds, BB, BlockFilter);
3326 if (CandidatePreds.size() == 0)
3327 return false;
3328 if (CandidatePreds.size() < BB->pred_size())
3329 CandidatePtr = &CandidatePreds;
3330 }
3331 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, &DuplicatedPreds,
3332 &RemovalCallbackRef, CandidatePtr);
3333
3334 // Update UnscheduledPredecessors to reflect tail-duplication.
3335 DuplicatedToLPred = false;
3336 for (MachineBasicBlock *Pred : DuplicatedPreds) {
3337 // We're only looking for unscheduled predecessors that match the filter.
3338 BlockChain *PredChain = BlockToChain[Pred];
3339 if (Pred == LPred)
3340 DuplicatedToLPred = true;
3341 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred)) ||
3342 PredChain == &Chain)
3343 continue;
3344 for (MachineBasicBlock *NewSucc : Pred->successors()) {
3345 if (BlockFilter && !BlockFilter->count(NewSucc))
3346 continue;
3347 BlockChain *NewChain = BlockToChain[NewSucc];
3348 if (NewChain != &Chain && NewChain != PredChain)
3349 NewChain->UnscheduledPredecessors++;
3350 }
3351 }
3352 return Removed;
3353}
3354
3355// Count the number of actual machine instructions.
3357 uint64_t InstrCount = 0;
3358 for (MachineInstr &MI : *MBB) {
3359 if (!MI.isPHI() && !MI.isMetaInstruction())
3360 InstrCount += 1;
3361 }
3362 return InstrCount;
3363}
3364
3365// The size cost of duplication is the instruction size of the duplicated block.
3366// So we should scale the threshold accordingly. But the instruction size is not
3367// available on all targets, so we use the number of instructions instead.
3368BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) {
3369 return BlockFrequency(DupThreshold.getFrequency() * countMBBInstruction(BB));
3370}
3371
3372// Returns true if BB is Pred's best successor.
3373bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB,
3374 MachineBasicBlock *Pred,
3375 BlockFilterSet *BlockFilter) {
3376 if (BB == Pred)
3377 return false;
3378 if (BlockFilter && !BlockFilter->count(Pred))
3379 return false;
3380 BlockChain *PredChain = BlockToChain[Pred];
3381 if (PredChain && (Pred != *std::prev(PredChain->end())))
3382 return false;
3383
3384 // Find the successor with largest probability excluding BB.
3385 BranchProbability BestProb = BranchProbability::getZero();
3386 for (MachineBasicBlock *Succ : Pred->successors())
3387 if (Succ != BB) {
3388 if (BlockFilter && !BlockFilter->count(Succ))
3389 continue;
3390 BlockChain *SuccChain = BlockToChain[Succ];
3391 if (SuccChain && (Succ != *SuccChain->begin()))
3392 continue;
3393 BranchProbability SuccProb = MBPI->getEdgeProbability(Pred, Succ);
3394 if (SuccProb > BestProb)
3395 BestProb = SuccProb;
3396 }
3397
3398 BranchProbability BBProb = MBPI->getEdgeProbability(Pred, BB);
3399 if (BBProb <= BestProb)
3400 return false;
3401
3402 // Compute the number of reduced taken branches if Pred falls through to BB
3403 // instead of another successor. Then compare it with threshold.
3404 BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
3405 BlockFrequency Gain = PredFreq * (BBProb - BestProb);
3406 return Gain > scaleThreshold(BB);
3407}
3408
3409// Find out the predecessors of BB and BB can be beneficially duplicated into
3410// them.
3411void MachineBlockPlacement::findDuplicateCandidates(
3412 SmallVectorImpl<MachineBasicBlock *> &Candidates, MachineBasicBlock *BB,
3413 BlockFilterSet *BlockFilter) {
3414 MachineBasicBlock *Fallthrough = nullptr;
3415 BranchProbability DefaultBranchProb = BranchProbability::getZero();
3416 BlockFrequency BBDupThreshold(scaleThreshold(BB));
3419
3420 // Sort for highest frequency.
3421 auto CmpSucc = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3422 return MBPI->getEdgeProbability(BB, A) > MBPI->getEdgeProbability(BB, B);
3423 };
3424 auto CmpPred = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3425 return MBFI->getBlockFreq(A) > MBFI->getBlockFreq(B);
3426 };
3427 llvm::stable_sort(Succs, CmpSucc);
3428 llvm::stable_sort(Preds, CmpPred);
3429
3430 auto SuccIt = Succs.begin();
3431 if (SuccIt != Succs.end()) {
3432 DefaultBranchProb = MBPI->getEdgeProbability(BB, *SuccIt).getCompl();
3433 }
3434
3435 // For each predecessors of BB, compute the benefit of duplicating BB,
3436 // if it is larger than the threshold, add it into Candidates.
3437 //
3438 // If we have following control flow.
3439 //
3440 // PB1 PB2 PB3 PB4
3441 // \ | / /\
3442 // \ | / / \
3443 // \ |/ / \
3444 // BB----/ OB
3445 // /\
3446 // / \
3447 // SB1 SB2
3448 //
3449 // And it can be partially duplicated as
3450 //
3451 // PB2+BB
3452 // | PB1 PB3 PB4
3453 // | | / /\
3454 // | | / / \
3455 // | |/ / \
3456 // | BB----/ OB
3457 // |\ /|
3458 // | X |
3459 // |/ \|
3460 // SB2 SB1
3461 //
3462 // The benefit of duplicating into a predecessor is defined as
3463 // Orig_taken_branch - Duplicated_taken_branch
3464 //
3465 // The Orig_taken_branch is computed with the assumption that predecessor
3466 // jumps to BB and the most possible successor is laid out after BB.
3467 //
3468 // The Duplicated_taken_branch is computed with the assumption that BB is
3469 // duplicated into PB, and one successor is layout after it (SB1 for PB1 and
3470 // SB2 for PB2 in our case). If there is no available successor, the combined
3471 // block jumps to all BB's successor, like PB3 in this example.
3472 //
3473 // If a predecessor has multiple successors, so BB can't be duplicated into
3474 // it. But it can beneficially fall through to BB, and duplicate BB into other
3475 // predecessors.
3476 for (MachineBasicBlock *Pred : Preds) {
3477 BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
3478
3479 if (!TailDup.canTailDuplicate(BB, Pred)) {
3480 // BB can't be duplicated into Pred, but it is possible to be layout
3481 // below Pred.
3482 if (!Fallthrough && isBestSuccessor(BB, Pred, BlockFilter)) {
3483 Fallthrough = Pred;
3484 if (SuccIt != Succs.end())
3485 SuccIt++;
3486 }
3487 continue;
3488 }
3489
3490 BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb;
3491 BlockFrequency DupCost;
3492 if (SuccIt == Succs.end()) {
3493 // Jump to all successors;
3494 if (Succs.size() > 0)
3495 DupCost += PredFreq;
3496 } else {
3497 // Fallthrough to *SuccIt, jump to all other successors;
3498 DupCost += PredFreq;
3499 DupCost -= PredFreq * MBPI->getEdgeProbability(BB, *SuccIt);
3500 }
3501
3502 assert(OrigCost >= DupCost);
3503 OrigCost -= DupCost;
3504 if (OrigCost > BBDupThreshold) {
3505 Candidates.push_back(Pred);
3506 if (SuccIt != Succs.end())
3507 SuccIt++;
3508 }
3509 }
3510
3511 // No predecessors can optimally fallthrough to BB.
3512 // So we can change one duplication into fallthrough.
3513 if (!Fallthrough) {
3514 if ((Candidates.size() < Preds.size()) && (Candidates.size() > 0)) {
3515 Candidates[0] = Candidates.back();
3516 Candidates.pop_back();
3517 }
3518 }
3519}
3520
3521void MachineBlockPlacement::initTailDupThreshold() {
3522 DupThreshold = BlockFrequency(0);
3523 if (F->getFunction().hasProfileData()) {
3524 // We prefer to use prifile count.
3525 uint64_t HotThreshold = PSI->getOrCompHotCountThreshold();
3526 if (HotThreshold != UINT64_MAX) {
3527 UseProfileCount = true;
3528 DupThreshold =
3529 BlockFrequency(HotThreshold * TailDupProfilePercentThreshold / 100);
3530 } else {
3531 // Profile count is not available, we can use block frequency instead.
3532 BlockFrequency MaxFreq = BlockFrequency(0);
3533 for (MachineBasicBlock &MBB : *F) {
3534 BlockFrequency Freq = MBFI->getBlockFreq(&MBB);
3535 if (Freq > MaxFreq)
3536 MaxFreq = Freq;
3537 }
3538
3539 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
3540 DupThreshold = BlockFrequency(MaxFreq * ThresholdProb);
3541 UseProfileCount = false;
3542 }
3543 }
3544
3545 TailDupSize = TailDupPlacementThreshold;
3546 // If only the aggressive threshold is explicitly set, use it.
3547 if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
3548 TailDupPlacementThreshold.getNumOccurrences() == 0)
3550
3551 // For aggressive optimization, we can adjust some thresholds to be less
3552 // conservative.
3553 if (OptLevel >= CodeGenOptLevel::Aggressive) {
3554 // At O3 we should be more willing to copy blocks for tail duplication. This
3555 // increases size pressure, so we only do it at O3
3556 // Do this unless only the regular threshold is explicitly set.
3557 if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
3558 TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
3560 }
3561
3562 // If there's no threshold provided through options, query the target
3563 // information for a threshold instead.
3564 if (TailDupPlacementThreshold.getNumOccurrences() == 0 &&
3565 (OptLevel < CodeGenOptLevel::Aggressive ||
3566 TailDupPlacementAggressiveThreshold.getNumOccurrences() == 0))
3567 TailDupSize = TII->getTailDuplicateSize(OptLevel);
3568}
3569
3570PreservedAnalyses
3573 auto *MBPI = &MFAM.getResult<MachineBranchProbabilityAnalysis>(MF);
3574 auto MBFI = std::make_unique<MBFIWrapper>(
3576 auto *MLI = &MFAM.getResult<MachineLoopAnalysis>(MF);
3577 auto *MPDT = MachineBlockPlacement::allowTailDupPlacement(MF)
3579 : nullptr;
3581 .getCachedResult<ProfileSummaryAnalysis>(
3582 *MF.getFunction().getParent());
3583 if (!PSI)
3584 report_fatal_error("MachineBlockPlacement requires ProfileSummaryAnalysis",
3585 false);
3586 MachineBlockPlacement MBP(MBPI, MLI, PSI, std::move(MBFI), MPDT,
3587 AllowTailMerge);
3588
3589 if (MBP.run(MF))
3591
3592 return PreservedAnalyses::all();
3593}
3594
3596 raw_ostream &OS,
3597 function_ref<StringRef(StringRef)> MapClassName2PassName) const {
3598 OS << MapClassName2PassName(name());
3599 if (!AllowTailMerge)
3600 OS << "<no-tail-merge>";
3601}
3602
3603bool MachineBlockPlacement::run(MachineFunction &MF) {
3604
3605 // Check for single-block functions and skip them.
3606 if (std::next(MF.begin()) == MF.end())
3607 return false;
3608
3609 F = &MF;
3610 OptLevel = F->getTarget().getOptLevel();
3611
3612 TII = MF.getSubtarget().getInstrInfo();
3614
3615 // Initialize PreferredLoopExit to nullptr here since it may never be set if
3616 // there are no MachineLoops.
3617 PreferredLoopExit = nullptr;
3618
3619 assert(BlockToChain.empty() &&
3620 "BlockToChain map should be empty before starting placement.");
3621 assert(ComputedEdges.empty() &&
3622 "Computed Edge map should be empty before starting placement.");
3623
3624 // Initialize tail duplication thresholds.
3625 initTailDupThreshold();
3626
3627 const bool OptForSize =
3628 llvm::shouldOptimizeForSize(&MF, PSI, &MBFI->getMBFI());
3629 // Determine whether to use ext-tsp for perf/size optimization. The method
3630 // is beneficial only for instances with at least 3 basic blocks and it can be
3631 // disabled for huge functions (exceeding a certain size).
3632 bool UseExtTspForPerf = false;
3633 bool UseExtTspForSize = false;
3634 if (3 <= MF.size() && MF.size() <= ExtTspBlockPlacementMaxBlocks) {
3635 UseExtTspForSize = OptForSize && ApplyExtTspForSize;
3636 UseExtTspForPerf =
3637 !UseExtTspForSize && EnableExtTspBlockPlacement &&
3639 }
3640
3641 // Apply tail duplication.
3642 if (allowTailDupPlacement(*F)) {
3643 if (OptForSize)
3644 TailDupSize = 1;
3645 const bool PreRegAlloc = false;
3646 TailDup.initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI,
3647 /* LayoutMode */ true, TailDupSize);
3648 if (!UseExtTspForSize)
3649 precomputeTriangleChains();
3650 }
3651
3652 // Run the main block placement.
3653 if (!UseExtTspForSize)
3654 buildCFGChains();
3655
3656 // Changing the layout can create new tail merging opportunities.
3657 // TailMerge can create jump into if branches that make CFG irreducible for
3658 // HW that requires structured CFG.
3659 const bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
3660 AllowTailMerge && BranchFoldPlacement &&
3661 MF.size() > 3;
3662 // No tail merging opportunities if the block number is less than four.
3663 if (EnableTailMerge) {
3664 const unsigned TailMergeSize = TailDupSize + 1;
3665 BranchFolder BF(/*DefaultEnableTailMerge=*/true, /*CommonHoist=*/false,
3666 *MBFI, *MBPI, PSI, TailMergeSize);
3667
3668 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), MLI,
3669 /*AfterPlacement=*/true)) {
3670 // Must redo the post-dominator tree if blocks were changed.
3671 if (MPDT)
3672 MPDT->recalculate(MF);
3673 if (!UseExtTspForSize) {
3674 // Redo the layout if tail merging creates/removes/moves blocks.
3675 BlockToChain.clear();
3676 ComputedEdges.clear();
3677 ChainAllocator.DestroyAll();
3678 buildCFGChains();
3679 }
3680 }
3681 }
3682
3683 // Apply a post-processing optimizing block placement:
3684 // - find a new placement and modify the layout of the blocks in the function;
3685 // - re-create CFG chains so that we can optimizeBranches and alignBlocks.
3686 if (UseExtTspForPerf || UseExtTspForSize) {
3687 assert(
3688 !(UseExtTspForPerf && UseExtTspForSize) &&
3689 "UseExtTspForPerf and UseExtTspForSize can not be set simultaneously");
3690 applyExtTsp(/*OptForSize=*/UseExtTspForSize);
3691 createCFGChainExtTsp();
3692 }
3693
3694 optimizeBranches();
3695 alignBlocks();
3696
3697 BlockToChain.clear();
3698 ComputedEdges.clear();
3699 ChainAllocator.DestroyAll();
3700
3701 // View the function.
3702 StringRef ViewFuncName =
3703 getViewBlockFreqFuncName(F->getFunction().getContext());
3704 if (ViewBlockLayoutWithBFI != GVDAGType::None &&
3705 (ViewFuncName.empty() || F->getFunction().getName() == ViewFuncName)) {
3707 MF.RenumberBlocks();
3708 MBFI->view("MBP." + MF.getName(), false);
3709 }
3710
3711 // We always return true as we have no way to track whether the final order
3712 // differs from the original order.
3713 return true;
3714}
3715
3716void MachineBlockPlacement::applyExtTsp(bool OptForSize) {
3717 // Prepare data; blocks are indexed by their index in the current ordering.
3718 DenseMap<const MachineBasicBlock *, uint64_t> BlockIndex;
3719 BlockIndex.reserve(F->size());
3720 std::vector<const MachineBasicBlock *> CurrentBlockOrder;
3721 CurrentBlockOrder.reserve(F->size());
3722 size_t NumBlocks = 0;
3723 for (const MachineBasicBlock &MBB : *F) {
3724 BlockIndex[&MBB] = NumBlocks++;
3725 CurrentBlockOrder.push_back(&MBB);
3726 }
3727
3728 SmallVector<uint64_t, 0> BlockCounts(F->size());
3729 SmallVector<uint64_t, 0> BlockSizes(F->size());
3731 SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
3733 for (MachineBasicBlock &MBB : *F) {
3734 // Getting the block frequency.
3735 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
3736 BlockCounts[BlockIndex[&MBB]] = OptForSize ? 1 : BlockFreq.getFrequency();
3737 // Getting the block size:
3738 // - approximate the size of an instruction by 4 bytes, and
3739 // - ignore debug instructions.
3740 // Note: getting the exact size of each block is target-dependent and can be
3741 // done by extending the interface of MCCodeEmitter. Experimentally we do
3742 // not see a perf improvement with the exact block sizes.
3743 auto NonDbgInsts =
3745 size_t NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
3746 BlockSizes[BlockIndex[&MBB]] = 4 * NumInsts;
3747
3748 // Getting jump frequencies.
3749 if (OptForSize) {
3750 Cond.clear();
3751 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
3752 if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
3753 continue;
3754
3755 const MachineBasicBlock *FTB = MBB.getFallThrough();
3756 // Succs is a collection of distinct destinations of the block reachable
3757 // from MBB via a jump instruction; initialize the list using the three
3758 // (non-necessarily distinct) blocks, FTB, TBB, and FBB.
3759 Succs.clear();
3760 if (TBB && TBB != FTB)
3761 Succs.push_back(TBB);
3762 if (FBB && FBB != FTB)
3763 Succs.push_back(FBB);
3764 if (FTB)
3765 Succs.push_back(FTB);
3766 // Absolute magnitude of non-zero counts does not matter for the
3767 // optimization; prioritize slightly jumps with a single successor, since
3768 // the corresponding jump instruction will be removed from the binary.
3769 const uint64_t Freq = Succs.size() == 1 ? 110 : 100;
3770 for (const MachineBasicBlock *Succ : Succs)
3771 JumpCounts.push_back({BlockIndex[&MBB], BlockIndex[Succ], Freq});
3772 } else {
3773 for (MachineBasicBlock *Succ : MBB.successors()) {
3774 auto EP = MBPI->getEdgeProbability(&MBB, Succ);
3775 BlockFrequency JumpFreq = BlockFreq * EP;
3776 JumpCounts.push_back(
3777 {BlockIndex[&MBB], BlockIndex[Succ], JumpFreq.getFrequency()});
3778 }
3779 }
3780 }
3781
3782 LLVM_DEBUG(dbgs() << "Applying ext-tsp layout for |V| = " << F->size()
3783 << " with profile = " << F->getFunction().hasProfileData()
3784 << " (" << F->getName() << ")" << "\n");
3785
3786 const double OrgScore = calcExtTspScore(BlockSizes, JumpCounts);
3787 LLVM_DEBUG(dbgs() << format(" original layout score: %0.2f\n", OrgScore));
3788
3789 // Run the layout algorithm.
3790 auto NewOrder = computeExtTspLayout(BlockSizes, BlockCounts, JumpCounts);
3791 std::vector<const MachineBasicBlock *> NewBlockOrder;
3792 NewBlockOrder.reserve(F->size());
3793 for (uint64_t Node : NewOrder) {
3794 NewBlockOrder.push_back(CurrentBlockOrder[Node]);
3795 }
3796 const double OptScore = calcExtTspScore(NewOrder, BlockSizes, JumpCounts);
3797 LLVM_DEBUG(dbgs() << format(" optimized layout score: %0.2f\n", OptScore));
3798
3799 // If the optimization is unsuccessful, fall back to the original block order.
3800 if (OptForSize && OrgScore > OptScore)
3801 assignBlockOrder(CurrentBlockOrder);
3802 else
3803 assignBlockOrder(NewBlockOrder);
3804}
3805
3806void MachineBlockPlacement::assignBlockOrder(
3807 const std::vector<const MachineBasicBlock *> &NewBlockOrder) {
3808 assert(F->size() == NewBlockOrder.size() && "Incorrect size of block order");
3809 F->RenumberBlocks();
3810
3811 bool HasChanges = false;
3812 for (size_t I = 0; I < NewBlockOrder.size(); I++) {
3813 if (NewBlockOrder[I] != F->getBlockNumbered(I)) {
3814 HasChanges = true;
3815 break;
3816 }
3817 }
3818 // Stop early if the new block order is identical to the existing one.
3819 if (!HasChanges)
3820 return;
3821
3822 SmallVector<MachineBasicBlock *, 4> PrevFallThroughs(F->getNumBlockIDs());
3823 for (auto &MBB : *F) {
3824 PrevFallThroughs[MBB.getNumber()] = MBB.getFallThrough();
3825 }
3826
3827 // Sort basic blocks in the function according to the computed order.
3828 DenseMap<const MachineBasicBlock *, size_t> NewIndex;
3829 for (const MachineBasicBlock *MBB : NewBlockOrder) {
3830 NewIndex[MBB] = NewIndex.size();
3831 }
3832 F->sort([&](MachineBasicBlock &L, MachineBasicBlock &R) {
3833 return NewIndex[&L] < NewIndex[&R];
3834 });
3835
3836 // Update basic block branches by inserting explicit fallthrough branches
3837 // when required and re-optimize branches when possible.
3838 const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
3839 SmallVector<MachineOperand, 4> Cond;
3840 for (auto &MBB : *F) {
3841 MachineFunction::iterator NextMBB = std::next(MBB.getIterator());
3843 auto *FTMBB = PrevFallThroughs[MBB.getNumber()];
3844 // If this block had a fallthrough before we need an explicit unconditional
3845 // branch to that block if the fallthrough block is not adjacent to the
3846 // block in the new order.
3847 if (FTMBB && (NextMBB == EndIt || &*NextMBB != FTMBB)) {
3848 TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
3849 }
3850
3851 // It might be possible to optimize branches by flipping the condition.
3852 Cond.clear();
3853 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
3854 if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
3855 continue;
3856 MBB.updateTerminator(FTMBB);
3857 }
3858}
3859
3860void MachineBlockPlacement::createCFGChainExtTsp() {
3861 BlockToChain.clear();
3862 ComputedEdges.clear();
3863 ChainAllocator.DestroyAll();
3864
3865 MachineBasicBlock *HeadBB = &F->front();
3866 BlockChain *FunctionChain =
3867 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, HeadBB);
3868
3869 for (MachineBasicBlock &MBB : *F) {
3870 if (HeadBB == &MBB)
3871 continue; // Ignore head of the chain
3872 FunctionChain->merge(&MBB, nullptr);
3873 }
3874}
3875
3876namespace {
3877
3878/// A pass to compute block placement statistics.
3879///
3880/// A separate pass to compute interesting statistics for evaluating block
3881/// placement. This is separate from the actual placement pass so that they can
3882/// be computed in the absence of any placement transformations or when using
3883/// alternative placement strategies.
3884class MachineBlockPlacementStats {
3885 /// A handle to the branch probability pass.
3886 const MachineBranchProbabilityInfo *MBPI;
3887
3888 /// A handle to the function-wide block frequency pass.
3889 const MachineBlockFrequencyInfo *MBFI;
3890
3891public:
3892 MachineBlockPlacementStats(const MachineBranchProbabilityInfo *MBPI,
3893 const MachineBlockFrequencyInfo *MBFI)
3894 : MBPI(MBPI), MBFI(MBFI) {}
3895 bool run(MachineFunction &MF);
3896};
3897
3898class MachineBlockPlacementStatsLegacy : public MachineFunctionPass {
3899public:
3900 static char ID; // Pass identification, replacement for typeid
3901
3902 MachineBlockPlacementStatsLegacy() : MachineFunctionPass(ID) {}
3903
3904 bool runOnMachineFunction(MachineFunction &F) override {
3905 auto *MBPI =
3906 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
3907 auto *MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
3908 return MachineBlockPlacementStats(MBPI, MBFI).run(F);
3909 }
3910
3911 void getAnalysisUsage(AnalysisUsage &AU) const override {
3912 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
3913 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
3914 AU.setPreservesAll();
3916 }
3917};
3918
3919} // end anonymous namespace
3920
3921char MachineBlockPlacementStatsLegacy::ID = 0;
3922
3923char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStatsLegacy::ID;
3924
3925INITIALIZE_PASS_BEGIN(MachineBlockPlacementStatsLegacy, "block-placement-stats",
3926 "Basic Block Placement Stats", false, false)
3929INITIALIZE_PASS_END(MachineBlockPlacementStatsLegacy, "block-placement-stats",
3930 "Basic Block Placement Stats", false, false)
3931
3935 auto &MBPI = MFAM.getResult<MachineBranchProbabilityAnalysis>(MF);
3936 auto &MBFI = MFAM.getResult<MachineBlockFrequencyAnalysis>(MF);
3937
3938 MachineBlockPlacementStats(&MBPI, &MBFI).run(MF);
3939 return PreservedAnalyses::all();
3940}
3941
3942bool MachineBlockPlacementStats::run(MachineFunction &F) {
3943 // Check for single-block functions and skip them.
3944 if (std::next(F.begin()) == F.end())
3945 return false;
3946
3947 if (!isFunctionInPrintList(F.getName()))
3948 return false;
3949
3950 for (MachineBasicBlock &MBB : F) {
3951 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
3952 Statistic &NumBranches =
3953 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
3954 Statistic &BranchTakenFreq =
3955 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
3956 for (MachineBasicBlock *Succ : MBB.successors()) {
3957 // Skip if this successor is a fallthrough.
3958 if (MBB.isLayoutSuccessor(Succ))
3959 continue;
3960
3961 BlockFrequency EdgeFreq =
3962 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
3963 ++NumBranches;
3964 BranchTakenFreq += EdgeFreq.getFrequency();
3965 }
3966 }
3967
3968 return false;
3969}
const TargetLowering & TLI
SDValue Pred
Ops append({Chain, DAG.getConstant(SVEStores[NumParts - 2], DL, MVT::i32)})
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
uint64_t uint64_t
MachineBasicBlock & MBB
This file defines the BumpPtrAllocator interface.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Declares methods and data structures for code layout algorithms.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
static unsigned InstrCount
This file defines the DenseMap class.
#define DEBUG_TYPE
IRTranslator LLVM IR MI
SmallVector< MachineOperand, 4 > Cond
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static BranchProbability getAdjustedProbability(BranchProbability OrigProb, BranchProbability AdjustedSumProb)
The helper function returns the branch probability that is adjusted or normalized over the new total ...
static cl::opt< bool > PreciseRotationCost("precise-rotation-cost", cl::desc("Model the cost of loop rotation more " "precisely by using profile data."), cl::init(false), cl::Hidden)
static cl::opt< unsigned > ExtTspBlockPlacementMaxBlocks("ext-tsp-block-placement-max-blocks", cl::desc("Maximum number of basic blocks in a function to run ext-TSP " "block placement."), cl::init(UINT_MAX), cl::Hidden)
static cl::opt< unsigned > AlignAllBlock("align-all-blocks", cl::desc("Force the alignment of all blocks in the function in log2 format " "(e.g 4 means align on 16B boundaries)."), cl::init(0), cl::Hidden)
static cl::opt< unsigned > PredecessorLimit("block-placement-predecessor-limit", cl::desc("For blocks with more predecessors, certain layout optimizations" "will be disabled to prevent quadratic compile time."), cl::init(1000), cl::Hidden)
static BranchProbability getLayoutSuccessorProbThreshold(const MachineBasicBlock *BB)
static cl::opt< bool > ForceLoopColdBlock("force-loop-cold-block", cl::desc("Force outlining cold blocks from loops."), cl::init(false), cl::Hidden)
static cl::opt< unsigned > ExitBlockBias("block-placement-exit-block-bias", cl::desc("Block frequency percentage a loop exit block needs " "over the original exit to be considered the new exit."), cl::init(0), cl::Hidden)
static cl::opt< unsigned > AlignAllNonFallThruBlocks("align-all-nofallthru-blocks", cl::desc("Force the alignment of all blocks that have no fall-through " "predecessors (i.e. don't add nops that are executed). In log2 " "format (e.g 4 means align on 16B boundaries)."), cl::init(0), cl::Hidden)
static cl::opt< unsigned > TailDupPlacementThreshold("tail-dup-placement-threshold", cl::desc("Instruction cutoff for tail duplication during layout. " "Tail merging during layout is forced to have a threshold " "that won't conflict."), cl::init(2), cl::Hidden)
static cl::opt< unsigned > JumpInstCost("jump-inst-cost", cl::desc("Cost of jump instructions."), cl::init(1), cl::Hidden)
static cl::opt< unsigned > TailDupPlacementPenalty("tail-dup-placement-penalty", cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. " "Copying can increase fallthrough, but it also increases icache " "pressure. This parameter controls the penalty to account for that. " "Percent as integer."), cl::init(2), cl::Hidden)
static bool greaterWithBias(BlockFrequency A, BlockFrequency B, BlockFrequency EntryFreq)
Compare 2 BlockFrequency's with a small penalty for A.
static cl::opt< unsigned > MisfetchCost("misfetch-cost", cl::desc("Cost that models the probabilistic risk of an instruction " "misfetch due to a jump comparing to falling through, whose cost " "is zero."), cl::init(1), cl::Hidden)
static cl::opt< unsigned > MaxBytesForAlignmentOverride("max-bytes-for-alignment", cl::desc("Forces the maximum bytes allowed to be emitted when padding for " "alignment"), cl::init(0), cl::Hidden)
static cl::opt< bool > BranchFoldPlacement("branch-fold-placement", cl::desc("Perform branch folding during placement. " "Reduces code size."), cl::init(true), cl::Hidden)
static cl::opt< unsigned > TailDupProfilePercentThreshold("tail-dup-profile-percent-threshold", cl::desc("If profile count information is used in tail duplication cost " "model, the gained fall through number from tail duplication " "should be at least this percent of hot count."), cl::init(50), cl::Hidden)
static cl::opt< unsigned > TriangleChainCount("triangle-chain-count", cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the " "triangle tail duplication heuristic to kick in. 0 to disable."), cl::init(2), cl::Hidden)
Branch Probability Basic Block static false std::string getBlockName(const MachineBasicBlock *BB)
Helper to print the name of a MBB.
static cl::opt< bool > ApplyExtTspForSize("apply-ext-tsp-for-size", cl::init(false), cl::Hidden, cl::desc("Use ext-tsp for size-aware block placement."))
static bool hasSameSuccessors(MachineBasicBlock &BB, SmallPtrSetImpl< const MachineBasicBlock * > &Successors)
Check if BB has exactly the successors in Successors.
static cl::opt< bool > TailDupPlacement("tail-dup-placement", cl::desc("Perform tail duplication during placement. " "Creates more fallthrough opportunities in " "outline branches."), cl::init(true), cl::Hidden)
static uint64_t countMBBInstruction(MachineBasicBlock *MBB)
static cl::opt< unsigned > LoopToColdBlockRatio("loop-to-cold-block-ratio", cl::desc("Outline loop blocks from loop chain if (frequency of loop) / " "(frequency of block) is greater than this ratio"), cl::init(5), cl::Hidden)
static cl::opt< bool > RenumberBlocksBeforeView("renumber-blocks-before-view", cl::desc("If true, basic blocks are re-numbered before MBP layout is printed " "into a dot graph. Only used when a function is being printed."), cl::init(false), cl::Hidden)
static cl::opt< unsigned > TailDupPlacementAggressiveThreshold("tail-dup-placement-aggressive-threshold", cl::desc("Instruction cutoff for aggressive tail duplication during " "layout. Used at -O3. Tail merging during layout is forced to " "have a threshold that won't conflict."), cl::init(4), cl::Hidden)
static cl::opt< bool > ForcePreciseRotationCost("force-precise-rotation-cost", cl::desc("Force the use of precise cost " "loop rotation strategy."), cl::init(false), cl::Hidden)
#define P(N)
static bool hasProfileData(const Function &F, const FunctionOutliningInfo &OI)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file contains some templates that are useful if you are working with the STL at all.
static const char * name
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
static BlockFrequency max()
Returns the maximum possible frequency, the saturation value.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
static constexpr BranchProbability getOne()
static constexpr BranchProbability getZero()
uint32_t getNumerator() const
BranchProbability getCompl() const
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:721
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
bool erase(const KeyT &Val)
Definition DenseMap.h:930
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
bool hasProfileData() const
Return true if the function is annotated with profile data.
Definition Function.h:313
Module * getParent()
Get the module that this global value is contained inside of...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1441
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:613
bool isEHPad() const
Returns true if the block is a landing pad.
LLVM_ABI MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor)
Update the terminator instructions in block to account for changes to block layout which may have bee...
LLVM_ABI bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
void setAlignment(Align A)
Set alignment of the basic block.
LLVM_ABI bool isEntryBlock() const
Returns true if this is the entry block of the function.
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
LLVM_ABI DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
iterator_range< succ_iterator > successors()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
iterator_range< pred_iterator > predecessors()
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName) const
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
Analysis pass that exposes the MachineLoopInfo for a machine function.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
LLVM_ABI uint64_t getOrCompHotCountThreshold() const
Returns HotCountThreshold if set.
typename vector_type::const_iterator iterator
Definition SetVector.h:72
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
reference emplace_back(ArgTypes &&... Args)
iterator erase(const_iterator CI)
typename SuperClass::const_iterator const_iterator
typename SuperClass::iterator iterator
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST T * Allocate(size_t num=1)
Allocate space for an array of objects without constructing them.
Definition Allocator.h:458
void DestroyAll()
Call the destructor of each allocated object and deallocate all but the current slab and reset the cu...
Definition Allocator.h:429
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
LLVM_ABI void initMF(MachineFunction &MF, bool PreRegAlloc, const MachineBranchProbabilityInfo *MBPI, MBFIWrapper *MBFI, ProfileSummaryInfo *PSI, bool LayoutMode, unsigned TailDupSize=0)
Prepare to run on a specific machine function.
LLVM_ABI bool tailDuplicateAndUpdate(bool IsSimple, MachineBasicBlock *MBB, MachineBasicBlock *ForcedLayoutPred, SmallVectorImpl< MachineBasicBlock * > *DuplicatedPreds=nullptr, function_ref< void(MachineBasicBlock *)> *RemovalCallback=nullptr, SmallVectorImpl< MachineBasicBlock * > *CandidatePtr=nullptr)
Tail duplicate a single basic block into its predecessors, and then clean up.
static LLVM_ABI bool isSimpleBB(MachineBasicBlock *TailBB)
True if this BB has only one unconditional jump.
LLVM_ABI bool canTailDuplicate(MachineBasicBlock *TailBB, MachineBasicBlock *PredBB)
Returns true if TailBB can successfully be duplicated into PredBB.
LLVM_ABI bool shouldTailDuplicate(bool IsSimple, MachineBasicBlock &TailBB)
Determine if it is profitable to duplicate this block.
virtual Align getPrefLoopAlignment(MachineLoop *ML=nullptr, const MachineBasicBlock *BlockToAlign=nullptr) const
Return the preferred loop alignment.
virtual unsigned getMaxPermittedBytesForAlignment(MachineBasicBlock *MBB) const
Return the maximum amount of bytes allowed to be emitted when padding for alignment.
virtual bool alignLoopsWithOptSize() const
Should loops be aligned even when the function is marked OptSize (but not MinSize).
bool requiresStructuredCFG() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
#define UINT64_MAX
Definition DataTypes.h:77
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
initializer< Ty > init(const Ty &Val)
LLVM_ABI double calcExtTspScore(ArrayRef< uint64_t > Order, ArrayRef< uint64_t > NodeSizes, ArrayRef< EdgeCount > EdgeCounts)
Estimate the "quality" of a given node order in CFG.
LLVM_ABI std::vector< uint64_t > computeExtTspLayout(ArrayRef< uint64_t > NodeSizes, ArrayRef< uint64_t > NodeCounts, ArrayRef< EdgeCount > EdgeCounts)
Find a layout of nodes (basic blocks) of a given CFG optimizing jump locality and thus processor I-ca...
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
void stable_sort(R &&Range)
Definition STLExtras.h:2132
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
InstructionCost Cost
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
cl::opt< GVDAGType > ViewBlockLayoutWithBFI("view-block-layout-with-bfi", cl::Hidden, cl::desc("Pop up a window to show a dag displaying MBP layout and associated " "block frequencies of the CFG."), cl::values(clEnumValN(GVDAGType::None, "none", "do not display graphs."), clEnumValN(GVDAGType::Fraction, "fraction", "display a graph using the " "fractional block frequency representation."), clEnumValN(GVDAGType::Integer, "integer", "display a graph using the raw " "integer fractional block frequency representation."), clEnumValN(GVDAGType::Count, "count", "display a graph using the real " "profile count if available.")))
cl::opt< bool > ApplyExtTspWithoutProfile
constexpr from_range_t from_range
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
cl::opt< unsigned > ProfileLikelyProb
NoopStatistic Statistic
Definition Statistic.h:161
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool isFunctionInPrintList(StringRef FunctionName)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
cl::opt< unsigned > StaticLikelyProb
LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI, BlockFrequency Freq)
Print the block frequency Freq relative to the current functions entry frequency.
LLVM_ABI char & MachineBlockPlacementID
MachineBlockPlacement - This pass places basic blocks based on branch probabilities.
cl::opt< bool > EnableExtTspBlockPlacement
LLVM_ABI StringRef getViewBlockFreqFuncName(const LLVMContext &C)
Return -view-bfi-func-name.
LLVM_ABI char & MachineBlockPlacementStatsID
MachineBlockPlacementStats - This pass collects statistics about the basic block placement using bran...
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
static constexpr Align fromLog2(unsigned Log2Value)
Returns an alignment of 1 << Log2Value bytes.
Definition Alignment.h:73