1044eb2f6SDimitry Andric //===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===//
263faed5bSDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
663faed5bSDimitry Andric //
763faed5bSDimitry Andric //===----------------------------------------------------------------------===//
863faed5bSDimitry Andric //
963faed5bSDimitry Andric // This file implements basic block placement transformations using the CFG
1063faed5bSDimitry Andric // structure and branch probability estimates.
1163faed5bSDimitry Andric //
1263faed5bSDimitry Andric // The pass strives to preserve the structure of the CFG (that is, retain
1358b69754SDimitry Andric // a topological ordering of basic blocks) in the absence of a *strong* signal
1463faed5bSDimitry Andric // to the contrary from probabilities. However, within the CFG structure, it
1563faed5bSDimitry Andric // attempts to choose an ordering which favors placing more likely sequences of
1663faed5bSDimitry Andric // blocks adjacent to each other.
1763faed5bSDimitry Andric //
1863faed5bSDimitry Andric // The algorithm works from the inner-most loop within a function outward, and
1963faed5bSDimitry Andric // at each stage walks through the basic blocks, trying to coalesce them into
2063faed5bSDimitry Andric // sequential chains where allowed by the CFG (or demanded by heavy
2163faed5bSDimitry Andric // probabilities). Finally, it walks the blocks in topological order, and the
2263faed5bSDimitry Andric // first time it reaches a chain of basic blocks, it schedules them in the
2363faed5bSDimitry Andric // function in-order.
2463faed5bSDimitry Andric //
2563faed5bSDimitry Andric //===----------------------------------------------------------------------===//
2663faed5bSDimitry Andric
2701095a5dSDimitry Andric #include "BranchFolding.h"
28044eb2f6SDimitry Andric #include "llvm/ADT/ArrayRef.h"
294a16efa3SDimitry Andric #include "llvm/ADT/DenseMap.h"
30044eb2f6SDimitry Andric #include "llvm/ADT/STLExtras.h"
31044eb2f6SDimitry Andric #include "llvm/ADT/SetVector.h"
324a16efa3SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
334a16efa3SDimitry Andric #include "llvm/ADT/SmallVector.h"
344a16efa3SDimitry Andric #include "llvm/ADT/Statistic.h"
3571d5a254SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
36706b4fc4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
37145449b1SDimitry Andric #include "llvm/CodeGen/MBFIWrapper.h"
3863faed5bSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
3963faed5bSDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
4063faed5bSDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
4163faed5bSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
4263faed5bSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
4363faed5bSDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
4471d5a254SDimitry Andric #include "llvm/CodeGen/MachinePostDominators.h"
45706b4fc4SDimitry Andric #include "llvm/CodeGen/MachineSizeOpts.h"
46b915e9e0SDimitry Andric #include "llvm/CodeGen/TailDuplicator.h"
47044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
48044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
497ab83427SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
50044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
51044eb2f6SDimitry Andric #include "llvm/IR/DebugLoc.h"
52044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
53145449b1SDimitry Andric #include "llvm/IR/PrintPasses.h"
54706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
55044eb2f6SDimitry Andric #include "llvm/Pass.h"
5663faed5bSDimitry Andric #include "llvm/Support/Allocator.h"
57044eb2f6SDimitry Andric #include "llvm/Support/BlockFrequency.h"
58044eb2f6SDimitry Andric #include "llvm/Support/BranchProbability.h"
59044eb2f6SDimitry Andric #include "llvm/Support/CodeGen.h"
6059d6cff9SDimitry Andric #include "llvm/Support/CommandLine.h"
61044eb2f6SDimitry Andric #include "llvm/Support/Compiler.h"
6263faed5bSDimitry Andric #include "llvm/Support/Debug.h"
635a5ac124SDimitry Andric #include "llvm/Support/raw_ostream.h"
64044eb2f6SDimitry Andric #include "llvm/Target/TargetMachine.h"
6577fc4c14SDimitry Andric #include "llvm/Transforms/Utils/CodeLayout.h"
6663faed5bSDimitry Andric #include <algorithm>
67044eb2f6SDimitry Andric #include <cassert>
68044eb2f6SDimitry Andric #include <cstdint>
69044eb2f6SDimitry Andric #include <iterator>
70044eb2f6SDimitry Andric #include <memory>
71044eb2f6SDimitry Andric #include <string>
72044eb2f6SDimitry Andric #include <tuple>
7371d5a254SDimitry Andric #include <utility>
74044eb2f6SDimitry Andric #include <vector>
75044eb2f6SDimitry Andric
7663faed5bSDimitry Andric using namespace llvm;
7763faed5bSDimitry Andric
785a5ac124SDimitry Andric #define DEBUG_TYPE "block-placement"
795ca98fd9SDimitry Andric
8063faed5bSDimitry Andric STATISTIC(NumCondBranches, "Number of conditional branches");
81dd58ef01SDimitry Andric STATISTIC(NumUncondBranches, "Number of unconditional branches");
8263faed5bSDimitry Andric STATISTIC(CondBranchTakenFreq,
8363faed5bSDimitry Andric "Potential frequency of taking conditional branches");
8463faed5bSDimitry Andric STATISTIC(UncondBranchTakenFreq,
8563faed5bSDimitry Andric "Potential frequency of taking unconditional branches");
8663faed5bSDimitry Andric
871d5ae102SDimitry Andric static cl::opt<unsigned> AlignAllBlock(
881d5ae102SDimitry Andric "align-all-blocks",
891d5ae102SDimitry Andric cl::desc("Force the alignment of all blocks in the function in log2 format "
901d5ae102SDimitry Andric "(e.g 4 means align on 16B boundaries)."),
9159d6cff9SDimitry Andric cl::init(0), cl::Hidden);
9259d6cff9SDimitry Andric
9301095a5dSDimitry Andric static cl::opt<unsigned> AlignAllNonFallThruBlocks(
9401095a5dSDimitry Andric "align-all-nofallthru-blocks",
951d5ae102SDimitry Andric cl::desc("Force the alignment of all blocks that have no fall-through "
961d5ae102SDimitry Andric "predecessors (i.e. don't add nops that are executed). In log2 "
971d5ae102SDimitry Andric "format (e.g 4 means align on 16B boundaries)."),
98dd58ef01SDimitry Andric cl::init(0), cl::Hidden);
99dd58ef01SDimitry Andric
1006f8fc217SDimitry Andric static cl::opt<unsigned> MaxBytesForAlignmentOverride(
1016f8fc217SDimitry Andric "max-bytes-for-alignment",
1026f8fc217SDimitry Andric cl::desc("Forces the maximum bytes allowed to be emitted when padding for "
1036f8fc217SDimitry Andric "alignment"),
1046f8fc217SDimitry Andric cl::init(0), cl::Hidden);
1056f8fc217SDimitry Andric
1065ca98fd9SDimitry Andric // FIXME: Find a good default for this flag and remove the flag.
1075a5ac124SDimitry Andric static cl::opt<unsigned> ExitBlockBias(
1085a5ac124SDimitry Andric "block-placement-exit-block-bias",
1095ca98fd9SDimitry Andric cl::desc("Block frequency percentage a loop exit block needs "
1105ca98fd9SDimitry Andric "over the original exit to be considered the new exit."),
1115ca98fd9SDimitry Andric cl::init(0), cl::Hidden);
1125ca98fd9SDimitry Andric
113b915e9e0SDimitry Andric // Definition:
114b915e9e0SDimitry Andric // - Outlining: placement of a basic block outside the chain or hot path.
115b915e9e0SDimitry Andric
116dd58ef01SDimitry Andric static cl::opt<unsigned> LoopToColdBlockRatio(
117dd58ef01SDimitry Andric "loop-to-cold-block-ratio",
118dd58ef01SDimitry Andric cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
119dd58ef01SDimitry Andric "(frequency of block) is greater than this ratio"),
120dd58ef01SDimitry Andric cl::init(5), cl::Hidden);
121dd58ef01SDimitry Andric
122044eb2f6SDimitry Andric static cl::opt<bool> ForceLoopColdBlock(
123044eb2f6SDimitry Andric "force-loop-cold-block",
124044eb2f6SDimitry Andric cl::desc("Force outlining cold blocks from loops."),
125044eb2f6SDimitry Andric cl::init(false), cl::Hidden);
126044eb2f6SDimitry Andric
127dd58ef01SDimitry Andric static cl::opt<bool>
128dd58ef01SDimitry Andric PreciseRotationCost("precise-rotation-cost",
129dd58ef01SDimitry Andric cl::desc("Model the cost of loop rotation more "
130dd58ef01SDimitry Andric "precisely by using profile data."),
131dd58ef01SDimitry Andric cl::init(false), cl::Hidden);
132044eb2f6SDimitry Andric
13301095a5dSDimitry Andric static cl::opt<bool>
13401095a5dSDimitry Andric ForcePreciseRotationCost("force-precise-rotation-cost",
13501095a5dSDimitry Andric cl::desc("Force the use of precise cost "
13601095a5dSDimitry Andric "loop rotation strategy."),
13701095a5dSDimitry Andric cl::init(false), cl::Hidden);
138dd58ef01SDimitry Andric
139dd58ef01SDimitry Andric static cl::opt<unsigned> MisfetchCost(
140dd58ef01SDimitry Andric "misfetch-cost",
14101095a5dSDimitry Andric cl::desc("Cost that models the probabilistic risk of an instruction "
142dd58ef01SDimitry Andric "misfetch due to a jump comparing to falling through, whose cost "
143dd58ef01SDimitry Andric "is zero."),
144dd58ef01SDimitry Andric cl::init(1), cl::Hidden);
145dd58ef01SDimitry Andric
146dd58ef01SDimitry Andric static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
147dd58ef01SDimitry Andric cl::desc("Cost of jump instructions."),
148dd58ef01SDimitry Andric cl::init(1), cl::Hidden);
149b915e9e0SDimitry Andric static cl::opt<bool>
150b915e9e0SDimitry Andric TailDupPlacement("tail-dup-placement",
151b915e9e0SDimitry Andric cl::desc("Perform tail duplication during placement. "
152b915e9e0SDimitry Andric "Creates more fallthrough opportunites in "
153b915e9e0SDimitry Andric "outline branches."),
154b915e9e0SDimitry Andric cl::init(true), cl::Hidden);
155dd58ef01SDimitry Andric
15601095a5dSDimitry Andric static cl::opt<bool>
15701095a5dSDimitry Andric BranchFoldPlacement("branch-fold-placement",
15801095a5dSDimitry Andric cl::desc("Perform branch folding during placement. "
15901095a5dSDimitry Andric "Reduces code size."),
16001095a5dSDimitry Andric cl::init(true), cl::Hidden);
16101095a5dSDimitry Andric
162b915e9e0SDimitry Andric // Heuristic for tail duplication.
16371d5a254SDimitry Andric static cl::opt<unsigned> TailDupPlacementThreshold(
164b915e9e0SDimitry Andric "tail-dup-placement-threshold",
165b915e9e0SDimitry Andric cl::desc("Instruction cutoff for tail duplication during layout. "
166b915e9e0SDimitry Andric "Tail merging during layout is forced to have a threshold "
167b915e9e0SDimitry Andric "that won't conflict."), cl::init(2),
168b915e9e0SDimitry Andric cl::Hidden);
169b915e9e0SDimitry Andric
1706b3f41edSDimitry Andric // Heuristic for aggressive tail duplication.
1716b3f41edSDimitry Andric static cl::opt<unsigned> TailDupPlacementAggressiveThreshold(
1726b3f41edSDimitry Andric "tail-dup-placement-aggressive-threshold",
1736b3f41edSDimitry Andric cl::desc("Instruction cutoff for aggressive tail duplication during "
1746b3f41edSDimitry Andric "layout. Used at -O3. Tail merging during layout is forced to "
175044eb2f6SDimitry Andric "have a threshold that won't conflict."), cl::init(4),
1766b3f41edSDimitry Andric cl::Hidden);
1776b3f41edSDimitry Andric
17871d5a254SDimitry Andric // Heuristic for tail duplication.
17971d5a254SDimitry Andric static cl::opt<unsigned> TailDupPlacementPenalty(
18071d5a254SDimitry Andric "tail-dup-placement-penalty",
18171d5a254SDimitry Andric cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
18271d5a254SDimitry Andric "Copying can increase fallthrough, but it also increases icache "
18371d5a254SDimitry Andric "pressure. This parameter controls the penalty to account for that. "
18471d5a254SDimitry Andric "Percent as integer."),
18571d5a254SDimitry Andric cl::init(2),
18671d5a254SDimitry Andric cl::Hidden);
18771d5a254SDimitry Andric
188b60736ecSDimitry Andric // Heuristic for tail duplication if profile count is used in cost model.
189b60736ecSDimitry Andric static cl::opt<unsigned> TailDupProfilePercentThreshold(
190b60736ecSDimitry Andric "tail-dup-profile-percent-threshold",
191b60736ecSDimitry Andric cl::desc("If profile count information is used in tail duplication cost "
192b60736ecSDimitry Andric "model, the gained fall through number from tail duplication "
193b60736ecSDimitry Andric "should be at least this percent of hot count."),
194b60736ecSDimitry Andric cl::init(50), cl::Hidden);
195b60736ecSDimitry Andric
19671d5a254SDimitry Andric // Heuristic for triangle chains.
19771d5a254SDimitry Andric static cl::opt<unsigned> TriangleChainCount(
19871d5a254SDimitry Andric "triangle-chain-count",
19971d5a254SDimitry Andric cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
20071d5a254SDimitry Andric "triangle tail duplication heuristic to kick in. 0 to disable."),
20171d5a254SDimitry Andric cl::init(2),
20271d5a254SDimitry Andric cl::Hidden);
20371d5a254SDimitry Andric
204e3b55780SDimitry Andric // Use case: When block layout is visualized after MBP pass, the basic blocks
205e3b55780SDimitry Andric // are labeled in layout order; meanwhile blocks could be numbered in a
206e3b55780SDimitry Andric // different order. It's hard to map between the graph and pass output.
207e3b55780SDimitry Andric // With this option on, the basic blocks are renumbered in function layout
208e3b55780SDimitry Andric // order. For debugging only.
209e3b55780SDimitry Andric static cl::opt<bool> RenumberBlocksBeforeView(
210e3b55780SDimitry Andric "renumber-blocks-before-view",
211e3b55780SDimitry Andric cl::desc(
212e3b55780SDimitry Andric "If true, basic blocks are re-numbered before MBP layout is printed "
213e3b55780SDimitry Andric "into a dot graph. Only used when a function is being printed."),
214e3b55780SDimitry Andric cl::init(false), cl::Hidden);
215e3b55780SDimitry Andric
2167fa27ce4SDimitry Andric namespace llvm {
217145449b1SDimitry Andric extern cl::opt<bool> EnableExtTspBlockPlacement;
218145449b1SDimitry Andric extern cl::opt<bool> ApplyExtTspWithoutProfile;
21901095a5dSDimitry Andric extern cl::opt<unsigned> StaticLikelyProb;
22001095a5dSDimitry Andric extern cl::opt<unsigned> ProfileLikelyProb;
22101095a5dSDimitry Andric
22271d5a254SDimitry Andric // Internal option used to control BFI display only after MBP pass.
22371d5a254SDimitry Andric // Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
22471d5a254SDimitry Andric // -view-block-layout-with-bfi=
22571d5a254SDimitry Andric extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
22671d5a254SDimitry Andric
22771d5a254SDimitry Andric // Command line option to specify the name of the function for CFG dump
22871d5a254SDimitry Andric // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
22971d5a254SDimitry Andric extern cl::opt<std::string> ViewBlockFreqFuncName;
230344a3780SDimitry Andric } // namespace llvm
23171d5a254SDimitry Andric
23263faed5bSDimitry Andric namespace {
23363faed5bSDimitry Andric
234044eb2f6SDimitry Andric class BlockChain;
235044eb2f6SDimitry Andric
236eb11fae6SDimitry Andric /// Type for our function-wide basic block -> block chain mapping.
237044eb2f6SDimitry Andric using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>;
238044eb2f6SDimitry Andric
239eb11fae6SDimitry Andric /// A chain of blocks which will be laid out contiguously.
24063faed5bSDimitry Andric ///
24163faed5bSDimitry Andric /// This is the datastructure representing a chain of consecutive blocks that
24263faed5bSDimitry Andric /// are profitable to layout together in order to maximize fallthrough
24358b69754SDimitry Andric /// probabilities and code locality. We also can use a block chain to represent
24458b69754SDimitry Andric /// a sequence of basic blocks which have some external (correctness)
24558b69754SDimitry Andric /// requirement for sequential layout.
24663faed5bSDimitry Andric ///
24758b69754SDimitry Andric /// Chains can be built around a single basic block and can be merged to grow
24858b69754SDimitry Andric /// them. They participate in a block-to-chain mapping, which is updated
24958b69754SDimitry Andric /// automatically as chains are merged together.
25063faed5bSDimitry Andric class BlockChain {
251eb11fae6SDimitry Andric /// The sequence of blocks belonging to this chain.
25263faed5bSDimitry Andric ///
25363faed5bSDimitry Andric /// This is the sequence of blocks for a particular chain. These will be laid
25463faed5bSDimitry Andric /// out in-order within the function.
25563faed5bSDimitry Andric SmallVector<MachineBasicBlock *, 4> Blocks;
25663faed5bSDimitry Andric
257eb11fae6SDimitry Andric /// A handle to the function-wide basic block to block chain mapping.
25863faed5bSDimitry Andric ///
25963faed5bSDimitry Andric /// This is retained in each block chain to simplify the computation of child
26063faed5bSDimitry Andric /// block chains for SCC-formation and iteration. We store the edges to child
26163faed5bSDimitry Andric /// basic blocks, and map them back to their associated chains using this
26263faed5bSDimitry Andric /// structure.
26363faed5bSDimitry Andric BlockToChainMapType &BlockToChain;
26463faed5bSDimitry Andric
26563faed5bSDimitry Andric public:
266eb11fae6SDimitry Andric /// Construct a new BlockChain.
26763faed5bSDimitry Andric ///
26863faed5bSDimitry Andric /// This builds a new block chain representing a single basic block in the
26963faed5bSDimitry Andric /// function. It also registers itself as the chain that block participates
27063faed5bSDimitry Andric /// in with the BlockToChain mapping.
BlockChain(BlockToChainMapType & BlockToChain,MachineBasicBlock * BB)27163faed5bSDimitry Andric BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
272044eb2f6SDimitry Andric : Blocks(1, BB), BlockToChain(BlockToChain) {
27363faed5bSDimitry Andric assert(BB && "Cannot create a chain with a null basic block");
27463faed5bSDimitry Andric BlockToChain[BB] = this;
27563faed5bSDimitry Andric }
27663faed5bSDimitry Andric
277eb11fae6SDimitry Andric /// Iterator over blocks within the chain.
278044eb2f6SDimitry Andric using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
279044eb2f6SDimitry Andric using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator;
28063faed5bSDimitry Andric
281eb11fae6SDimitry Andric /// Beginning of blocks within the chain.
begin()282b61ab53cSDimitry Andric iterator begin() { return Blocks.begin(); }
begin() const28371d5a254SDimitry Andric const_iterator begin() const { return Blocks.begin(); }
28463faed5bSDimitry Andric
285eb11fae6SDimitry Andric /// End of blocks within the chain.
end()286b61ab53cSDimitry Andric iterator end() { return Blocks.end(); }
end() const28771d5a254SDimitry Andric const_iterator end() const { return Blocks.end(); }
28863faed5bSDimitry Andric
remove(MachineBasicBlock * BB)289b915e9e0SDimitry Andric bool remove(MachineBasicBlock* BB) {
290b915e9e0SDimitry Andric for(iterator i = begin(); i != end(); ++i) {
291b915e9e0SDimitry Andric if (*i == BB) {
292b915e9e0SDimitry Andric Blocks.erase(i);
293b915e9e0SDimitry Andric return true;
294b915e9e0SDimitry Andric }
295b915e9e0SDimitry Andric }
296b915e9e0SDimitry Andric return false;
297b915e9e0SDimitry Andric }
298b915e9e0SDimitry Andric
299eb11fae6SDimitry Andric /// Merge a block chain into this one.
30063faed5bSDimitry Andric ///
30163faed5bSDimitry Andric /// This routine merges a block chain into this one. It takes care of forming
30263faed5bSDimitry Andric /// a contiguous sequence of basic blocks, updating the edge list, and
30363faed5bSDimitry Andric /// updating the block -> chain mapping. It does not free or tear down the
30463faed5bSDimitry Andric /// old chain, but the old chain's block list is no longer valid.
merge(MachineBasicBlock * BB,BlockChain * Chain)30563faed5bSDimitry Andric void merge(MachineBasicBlock *BB, BlockChain *Chain) {
306b5630dbaSDimitry Andric assert(BB && "Can't merge a null block.");
307b5630dbaSDimitry Andric assert(!Blocks.empty() && "Can't merge into an empty chain.");
30863faed5bSDimitry Andric
30963faed5bSDimitry Andric // Fast path in case we don't have a chain already.
31063faed5bSDimitry Andric if (!Chain) {
311b5630dbaSDimitry Andric assert(!BlockToChain[BB] &&
312b5630dbaSDimitry Andric "Passed chain is null, but BB has entry in BlockToChain.");
31363faed5bSDimitry Andric Blocks.push_back(BB);
31463faed5bSDimitry Andric BlockToChain[BB] = this;
31563faed5bSDimitry Andric return;
31663faed5bSDimitry Andric }
31763faed5bSDimitry Andric
318b5630dbaSDimitry Andric assert(BB == *Chain->begin() && "Passed BB is not head of Chain.");
31963faed5bSDimitry Andric assert(Chain->begin() != Chain->end());
32063faed5bSDimitry Andric
32163faed5bSDimitry Andric // Update the incoming blocks to point to this chain, and add them to the
32263faed5bSDimitry Andric // chain structure.
3235a5ac124SDimitry Andric for (MachineBasicBlock *ChainBB : *Chain) {
3245a5ac124SDimitry Andric Blocks.push_back(ChainBB);
325b5630dbaSDimitry Andric assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain.");
3265a5ac124SDimitry Andric BlockToChain[ChainBB] = this;
32763faed5bSDimitry Andric }
32863faed5bSDimitry Andric }
32963faed5bSDimitry Andric
33063faed5bSDimitry Andric #ifndef NDEBUG
331eb11fae6SDimitry Andric /// Dump the blocks in this chain.
dump()3325ca98fd9SDimitry Andric LLVM_DUMP_METHOD void dump() {
3335a5ac124SDimitry Andric for (MachineBasicBlock *MBB : *this)
3345a5ac124SDimitry Andric MBB->dump();
33563faed5bSDimitry Andric }
33663faed5bSDimitry Andric #endif // NDEBUG
33763faed5bSDimitry Andric
338eb11fae6SDimitry Andric /// Count of predecessors of any block within the chain which have not
33901095a5dSDimitry Andric /// yet been scheduled. In general, we will delay scheduling this chain
34001095a5dSDimitry Andric /// until those predecessors are scheduled (or we find a sufficiently good
34101095a5dSDimitry Andric /// reason to override this heuristic.) Note that when forming loop chains,
34201095a5dSDimitry Andric /// blocks outside the loop are ignored and treated as if they were already
34301095a5dSDimitry Andric /// scheduled.
34463faed5bSDimitry Andric ///
34501095a5dSDimitry Andric /// Note: This field is reinitialized multiple times - once for each loop,
34601095a5dSDimitry Andric /// and then once for the function as a whole.
347044eb2f6SDimitry Andric unsigned UnscheduledPredecessors = 0;
34863faed5bSDimitry Andric };
34963faed5bSDimitry Andric
35063faed5bSDimitry Andric class MachineBlockPlacement : public MachineFunctionPass {
351eb11fae6SDimitry Andric /// A type for a block filter set.
352044eb2f6SDimitry Andric using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
35371d5a254SDimitry Andric
354d8e91e46SDimitry Andric /// Pair struct containing basic block and taildup profitability
35571d5a254SDimitry Andric struct BlockAndTailDupResult {
3567fa27ce4SDimitry Andric MachineBasicBlock *BB = nullptr;
35771d5a254SDimitry Andric bool ShouldTailDup;
35871d5a254SDimitry Andric };
35971d5a254SDimitry Andric
36071d5a254SDimitry Andric /// Triple struct containing edge weight and the edge.
36171d5a254SDimitry Andric struct WeightedEdge {
36271d5a254SDimitry Andric BlockFrequency Weight;
3637fa27ce4SDimitry Andric MachineBasicBlock *Src = nullptr;
3647fa27ce4SDimitry Andric MachineBasicBlock *Dest = nullptr;
36571d5a254SDimitry Andric };
36663faed5bSDimitry Andric
367eb11fae6SDimitry Andric /// work lists of blocks that are ready to be laid out
36801095a5dSDimitry Andric SmallVector<MachineBasicBlock *, 16> BlockWorkList;
36901095a5dSDimitry Andric SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
37001095a5dSDimitry Andric
37171d5a254SDimitry Andric /// Edges that have already been computed as optimal.
37271d5a254SDimitry Andric DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
37371d5a254SDimitry Andric
374eb11fae6SDimitry Andric /// Machine Function
3757fa27ce4SDimitry Andric MachineFunction *F = nullptr;
37601095a5dSDimitry Andric
377eb11fae6SDimitry Andric /// A handle to the branch probability pass.
3787fa27ce4SDimitry Andric const MachineBranchProbabilityInfo *MBPI = nullptr;
37963faed5bSDimitry Andric
380eb11fae6SDimitry Andric /// A handle to the function-wide block frequency pass.
381cfca06d7SDimitry Andric std::unique_ptr<MBFIWrapper> MBFI;
38263faed5bSDimitry Andric
383eb11fae6SDimitry Andric /// A handle to the loop info.
3847fa27ce4SDimitry Andric MachineLoopInfo *MLI = nullptr;
38563faed5bSDimitry Andric
386eb11fae6SDimitry Andric /// Preferred loop exit.
387b915e9e0SDimitry Andric /// Member variable for convenience. It may be removed by duplication deep
388b915e9e0SDimitry Andric /// in the call stack.
3897fa27ce4SDimitry Andric MachineBasicBlock *PreferredLoopExit = nullptr;
390b915e9e0SDimitry Andric
391eb11fae6SDimitry Andric /// A handle to the target's instruction info.
3927fa27ce4SDimitry Andric const TargetInstrInfo *TII = nullptr;
39363faed5bSDimitry Andric
394eb11fae6SDimitry Andric /// A handle to the target's lowering info.
3957fa27ce4SDimitry Andric const TargetLoweringBase *TLI = nullptr;
39663faed5bSDimitry Andric
397eb11fae6SDimitry Andric /// A handle to the post dominator tree.
3987fa27ce4SDimitry Andric MachinePostDominatorTree *MPDT = nullptr;
3995a5ac124SDimitry Andric
4007fa27ce4SDimitry Andric ProfileSummaryInfo *PSI = nullptr;
401706b4fc4SDimitry Andric
402eb11fae6SDimitry Andric /// Duplicator used to duplicate tails during placement.
403b915e9e0SDimitry Andric ///
404b915e9e0SDimitry Andric /// Placement decisions can open up new tail duplication opportunities, but
405b915e9e0SDimitry Andric /// since tail duplication affects placement decisions of later blocks, it
406b915e9e0SDimitry Andric /// must be done inline.
407b915e9e0SDimitry Andric TailDuplicator TailDup;
408b915e9e0SDimitry Andric
409cfca06d7SDimitry Andric /// Partial tail duplication threshold.
410cfca06d7SDimitry Andric BlockFrequency DupThreshold;
411cfca06d7SDimitry Andric
412b60736ecSDimitry Andric /// True: use block profile count to compute tail duplication cost.
413b60736ecSDimitry Andric /// False: use block frequency to compute tail duplication cost.
4147fa27ce4SDimitry Andric bool UseProfileCount = false;
415b60736ecSDimitry Andric
416eb11fae6SDimitry Andric /// Allocator and owner of BlockChain structures.
41763faed5bSDimitry Andric ///
41858b69754SDimitry Andric /// We build BlockChains lazily while processing the loop structure of
41958b69754SDimitry Andric /// a function. To reduce malloc traffic, we allocate them using this
42058b69754SDimitry Andric /// slab-like allocator, and destroy them after the pass completes. An
42158b69754SDimitry Andric /// important guarantee is that this allocator produces stable pointers to
42258b69754SDimitry Andric /// the chains.
42363faed5bSDimitry Andric SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
42463faed5bSDimitry Andric
425eb11fae6SDimitry Andric /// Function wide BasicBlock to BlockChain mapping.
42663faed5bSDimitry Andric ///
42763faed5bSDimitry Andric /// This mapping allows efficiently moving from any given basic block to the
42863faed5bSDimitry Andric /// BlockChain it participates in, if any. We use it to, among other things,
42963faed5bSDimitry Andric /// allow implicitly defining edges between chains as the existing edges
43063faed5bSDimitry Andric /// between basic blocks.
43171d5a254SDimitry Andric DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
43263faed5bSDimitry Andric
433b915e9e0SDimitry Andric #ifndef NDEBUG
434b915e9e0SDimitry Andric /// The set of basic blocks that have terminators that cannot be fully
435b915e9e0SDimitry Andric /// analyzed. These basic blocks cannot be re-ordered safely by
436b915e9e0SDimitry Andric /// MachineBlockPlacement, and we must preserve physical layout of these
437b915e9e0SDimitry Andric /// blocks and their successors through the pass.
438b915e9e0SDimitry Andric SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
439b915e9e0SDimitry Andric #endif
440b915e9e0SDimitry Andric
441b60736ecSDimitry Andric /// Get block profile count or frequency according to UseProfileCount.
442b60736ecSDimitry Andric /// The return value is used to model tail duplication cost.
getBlockCountOrFrequency(const MachineBasicBlock * BB)443b60736ecSDimitry Andric BlockFrequency getBlockCountOrFrequency(const MachineBasicBlock *BB) {
444b60736ecSDimitry Andric if (UseProfileCount) {
445b60736ecSDimitry Andric auto Count = MBFI->getBlockProfileCount(BB);
446b60736ecSDimitry Andric if (Count)
447b1c73532SDimitry Andric return BlockFrequency(*Count);
448b60736ecSDimitry Andric else
449b1c73532SDimitry Andric return BlockFrequency(0);
450b60736ecSDimitry Andric } else
451b60736ecSDimitry Andric return MBFI->getBlockFreq(BB);
452b60736ecSDimitry Andric }
453b60736ecSDimitry Andric
454cfca06d7SDimitry Andric /// Scale the DupThreshold according to basic block size.
455cfca06d7SDimitry Andric BlockFrequency scaleThreshold(MachineBasicBlock *BB);
456cfca06d7SDimitry Andric void initDupThreshold();
457cfca06d7SDimitry Andric
458b915e9e0SDimitry Andric /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
459b915e9e0SDimitry Andric /// if the count goes to 0, add them to the appropriate work list.
46071d5a254SDimitry Andric void markChainSuccessors(
46171d5a254SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
4625ca98fd9SDimitry Andric const BlockFilterSet *BlockFilter = nullptr);
463b915e9e0SDimitry Andric
464b915e9e0SDimitry Andric /// Decrease the UnscheduledPredecessors count for a single block, and
465b915e9e0SDimitry Andric /// if the count goes to 0, add them to the appropriate work list.
466b915e9e0SDimitry Andric void markBlockSuccessors(
46771d5a254SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *BB,
46871d5a254SDimitry Andric const MachineBasicBlock *LoopHeaderBB,
469b915e9e0SDimitry Andric const BlockFilterSet *BlockFilter = nullptr);
470b915e9e0SDimitry Andric
47101095a5dSDimitry Andric BranchProbability
47271d5a254SDimitry Andric collectViableSuccessors(
47371d5a254SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain,
47401095a5dSDimitry Andric const BlockFilterSet *BlockFilter,
47501095a5dSDimitry Andric SmallVector<MachineBasicBlock *, 4> &Successors);
476cfca06d7SDimitry Andric bool isBestSuccessor(MachineBasicBlock *BB, MachineBasicBlock *Pred,
477cfca06d7SDimitry Andric BlockFilterSet *BlockFilter);
478cfca06d7SDimitry Andric void findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock *> &Candidates,
479cfca06d7SDimitry Andric MachineBasicBlock *BB,
480cfca06d7SDimitry Andric BlockFilterSet *BlockFilter);
481b915e9e0SDimitry Andric bool repeatedlyTailDuplicateBlock(
482b915e9e0SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *&LPred,
483ac9a064cSDimitry Andric const MachineBasicBlock *LoopHeaderBB, BlockChain &Chain,
484ac9a064cSDimitry Andric BlockFilterSet *BlockFilter,
485ac9a064cSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt,
486ac9a064cSDimitry Andric BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt);
487ac9a064cSDimitry Andric bool
488ac9a064cSDimitry Andric maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred,
48971d5a254SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter,
490b915e9e0SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt,
491ac9a064cSDimitry Andric BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
492eb11fae6SDimitry Andric bool &DuplicatedToLPred);
49371d5a254SDimitry Andric bool hasBetterLayoutPredecessor(
49471d5a254SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
49571d5a254SDimitry Andric const BlockChain &SuccChain, BranchProbability SuccProb,
49671d5a254SDimitry Andric BranchProbability RealSuccProb, const BlockChain &Chain,
49701095a5dSDimitry Andric const BlockFilterSet *BlockFilter);
49871d5a254SDimitry Andric BlockAndTailDupResult selectBestSuccessor(
49971d5a254SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain,
50063faed5bSDimitry Andric const BlockFilterSet *BlockFilter);
50171d5a254SDimitry Andric MachineBasicBlock *selectBestCandidateBlock(
50271d5a254SDimitry Andric const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
503ac9a064cSDimitry Andric MachineBasicBlock *
504ac9a064cSDimitry Andric getFirstUnplacedBlock(const BlockChain &PlacedChain,
505ac9a064cSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt);
506ac9a064cSDimitry Andric MachineBasicBlock *
507ac9a064cSDimitry Andric getFirstUnplacedBlock(const BlockChain &PlacedChain,
508ac9a064cSDimitry Andric BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
50963faed5bSDimitry Andric const BlockFilterSet *BlockFilter);
51001095a5dSDimitry Andric
511eb11fae6SDimitry Andric /// Add a basic block to the work list if it is appropriate.
51201095a5dSDimitry Andric ///
51301095a5dSDimitry Andric /// If the optional parameter BlockFilter is provided, only MBB
51401095a5dSDimitry Andric /// present in the set will be added to the worklist. If nullptr
51501095a5dSDimitry Andric /// is provided, no filtering occurs.
51671d5a254SDimitry Andric void fillWorkLists(const MachineBasicBlock *MBB,
51701095a5dSDimitry Andric SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
51801095a5dSDimitry Andric const BlockFilterSet *BlockFilter);
519044eb2f6SDimitry Andric
52071d5a254SDimitry Andric void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
521b915e9e0SDimitry Andric BlockFilterSet *BlockFilter = nullptr);
522e6d15924SDimitry Andric bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock,
523e6d15924SDimitry Andric const MachineBasicBlock *OldTop);
524e6d15924SDimitry Andric bool hasViableTopFallthrough(const MachineBasicBlock *Top,
525e6d15924SDimitry Andric const BlockFilterSet &LoopBlockSet);
526e6d15924SDimitry Andric BlockFrequency TopFallThroughFreq(const MachineBasicBlock *Top,
527e6d15924SDimitry Andric const BlockFilterSet &LoopBlockSet);
528e6d15924SDimitry Andric BlockFrequency FallThroughGains(const MachineBasicBlock *NewTop,
529e6d15924SDimitry Andric const MachineBasicBlock *OldTop,
530e6d15924SDimitry Andric const MachineBasicBlock *ExitBB,
531e6d15924SDimitry Andric const BlockFilterSet &LoopBlockSet);
532e6d15924SDimitry Andric MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop,
533e6d15924SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
53471d5a254SDimitry Andric MachineBasicBlock *findBestLoopTop(
53571d5a254SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
53671d5a254SDimitry Andric MachineBasicBlock *findBestLoopExit(
537e6d15924SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet,
538e6d15924SDimitry Andric BlockFrequency &ExitFreq);
53971d5a254SDimitry Andric BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
54071d5a254SDimitry Andric void buildLoopChains(const MachineLoop &L);
54171d5a254SDimitry Andric void rotateLoop(
54271d5a254SDimitry Andric BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
543e6d15924SDimitry Andric BlockFrequency ExitFreq, const BlockFilterSet &LoopBlockSet);
54471d5a254SDimitry Andric void rotateLoopWithProfile(
54571d5a254SDimitry Andric BlockChain &LoopChain, const MachineLoop &L,
54663faed5bSDimitry Andric const BlockFilterSet &LoopBlockSet);
54701095a5dSDimitry Andric void buildCFGChains();
54801095a5dSDimitry Andric void optimizeBranches();
54901095a5dSDimitry Andric void alignBlocks();
55071d5a254SDimitry Andric /// Returns true if a block should be tail-duplicated to increase fallthrough
55171d5a254SDimitry Andric /// opportunities.
55271d5a254SDimitry Andric bool shouldTailDuplicate(MachineBasicBlock *BB);
55371d5a254SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase
55471d5a254SDimitry Andric /// fallthroughs.
55571d5a254SDimitry Andric bool isProfitableToTailDup(
55671d5a254SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
557eb11fae6SDimitry Andric BranchProbability QProb,
55871d5a254SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter);
559044eb2f6SDimitry Andric
56071d5a254SDimitry Andric /// Check for a trellis layout.
56171d5a254SDimitry Andric bool isTrellis(const MachineBasicBlock *BB,
56271d5a254SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
56371d5a254SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter);
564044eb2f6SDimitry Andric
56571d5a254SDimitry Andric /// Get the best successor given a trellis layout.
56671d5a254SDimitry Andric BlockAndTailDupResult getBestTrellisSuccessor(
56771d5a254SDimitry Andric const MachineBasicBlock *BB,
56871d5a254SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
56971d5a254SDimitry Andric BranchProbability AdjustedSumProb, const BlockChain &Chain,
57071d5a254SDimitry Andric const BlockFilterSet *BlockFilter);
571044eb2f6SDimitry Andric
57271d5a254SDimitry Andric /// Get the best pair of non-conflicting edges.
57371d5a254SDimitry Andric static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
57471d5a254SDimitry Andric const MachineBasicBlock *BB,
57571d5a254SDimitry Andric MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
576044eb2f6SDimitry Andric
57771d5a254SDimitry Andric /// Returns true if a block can tail duplicate into all unplaced
57871d5a254SDimitry Andric /// predecessors. Filters based on loop.
57971d5a254SDimitry Andric bool canTailDuplicateUnplacedPreds(
58071d5a254SDimitry Andric const MachineBasicBlock *BB, MachineBasicBlock *Succ,
58171d5a254SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter);
582044eb2f6SDimitry Andric
58371d5a254SDimitry Andric /// Find chains of triangles to tail-duplicate where a global analysis works,
58471d5a254SDimitry Andric /// but a local analysis would not find them.
58571d5a254SDimitry Andric void precomputeTriangleChains();
58663faed5bSDimitry Andric
58777fc4c14SDimitry Andric /// Apply a post-processing step optimizing block placement.
58877fc4c14SDimitry Andric void applyExtTsp();
58977fc4c14SDimitry Andric
59077fc4c14SDimitry Andric /// Modify the existing block placement in the function and adjust all jumps.
59177fc4c14SDimitry Andric void assignBlockOrder(const std::vector<const MachineBasicBlock *> &NewOrder);
59277fc4c14SDimitry Andric
59377fc4c14SDimitry Andric /// Create a single CFG chain from the current block order.
59477fc4c14SDimitry Andric void createCFGChainExtTsp();
59577fc4c14SDimitry Andric
59663faed5bSDimitry Andric public:
59763faed5bSDimitry Andric static char ID; // Pass identification, replacement for typeid
598044eb2f6SDimitry Andric
MachineBlockPlacement()59963faed5bSDimitry Andric MachineBlockPlacement() : MachineFunctionPass(ID) {
60063faed5bSDimitry Andric initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
60163faed5bSDimitry Andric }
60263faed5bSDimitry Andric
6035ca98fd9SDimitry Andric bool runOnMachineFunction(MachineFunction &F) override;
60463faed5bSDimitry Andric
allowTailDupPlacement() const605eb11fae6SDimitry Andric bool allowTailDupPlacement() const {
606eb11fae6SDimitry Andric assert(F);
607eb11fae6SDimitry Andric return TailDupPlacement && !F->getTarget().requiresStructuredCFG();
608eb11fae6SDimitry Andric }
609eb11fae6SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const6105ca98fd9SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
611ac9a064cSDimitry Andric AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
612ac9a064cSDimitry Andric AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
61371d5a254SDimitry Andric if (TailDupPlacement)
614ac9a064cSDimitry Andric AU.addRequired<MachinePostDominatorTreeWrapperPass>();
615ac9a064cSDimitry Andric AU.addRequired<MachineLoopInfoWrapperPass>();
616706b4fc4SDimitry Andric AU.addRequired<ProfileSummaryInfoWrapperPass>();
61701095a5dSDimitry Andric AU.addRequired<TargetPassConfig>();
61863faed5bSDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
61963faed5bSDimitry Andric }
62063faed5bSDimitry Andric };
621044eb2f6SDimitry Andric
622044eb2f6SDimitry Andric } // end anonymous namespace
62363faed5bSDimitry Andric
62463faed5bSDimitry Andric char MachineBlockPlacement::ID = 0;
625044eb2f6SDimitry Andric
62663faed5bSDimitry Andric char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
627044eb2f6SDimitry Andric
628ab44ce3dSDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE,
62963faed5bSDimitry Andric "Branch Probability Basic Block Placement", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)630ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)
631ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass)
632ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTreeWrapperPass)
633ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
634706b4fc4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
635ab44ce3dSDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE,
63663faed5bSDimitry Andric "Branch Probability Basic Block Placement", false, false)
63763faed5bSDimitry Andric
63863faed5bSDimitry Andric #ifndef NDEBUG
639eb11fae6SDimitry Andric /// Helper to print the name of a MBB.
64063faed5bSDimitry Andric ///
64163faed5bSDimitry Andric /// Only used by debug logging.
64271d5a254SDimitry Andric static std::string getBlockName(const MachineBasicBlock *BB) {
64363faed5bSDimitry Andric std::string Result;
64463faed5bSDimitry Andric raw_string_ostream OS(Result);
645044eb2f6SDimitry Andric OS << printMBBReference(*BB);
64601095a5dSDimitry Andric OS << " ('" << BB->getName() << "')";
64763faed5bSDimitry Andric OS.flush();
64863faed5bSDimitry Andric return Result;
64963faed5bSDimitry Andric }
65063faed5bSDimitry Andric #endif
65163faed5bSDimitry Andric
652eb11fae6SDimitry Andric /// Mark a chain's successors as having one fewer preds.
65363faed5bSDimitry Andric ///
65463faed5bSDimitry Andric /// When a chain is being merged into the "placed" chain, this routine will
65563faed5bSDimitry Andric /// quickly walk the successors of each block in the chain and mark them as
65663faed5bSDimitry Andric /// having one fewer active predecessor. It also adds any successors of this
657b915e9e0SDimitry Andric /// chain which reach the zero-predecessor state to the appropriate worklist.
markChainSuccessors(const BlockChain & Chain,const MachineBasicBlock * LoopHeaderBB,const BlockFilterSet * BlockFilter)65863faed5bSDimitry Andric void MachineBlockPlacement::markChainSuccessors(
65971d5a254SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
66063faed5bSDimitry Andric const BlockFilterSet *BlockFilter) {
66163faed5bSDimitry Andric // Walk all the blocks in this chain, marking their successors as having
66263faed5bSDimitry Andric // a predecessor placed.
6635a5ac124SDimitry Andric for (MachineBasicBlock *MBB : Chain) {
664b915e9e0SDimitry Andric markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
665b915e9e0SDimitry Andric }
666b915e9e0SDimitry Andric }
667b915e9e0SDimitry Andric
668eb11fae6SDimitry Andric /// Mark a single block's successors as having one fewer preds.
669b915e9e0SDimitry Andric ///
670b915e9e0SDimitry Andric /// Under normal circumstances, this is only called by markChainSuccessors,
671b915e9e0SDimitry Andric /// but if a block that was to be placed is completely tail-duplicated away,
672b915e9e0SDimitry Andric /// and was duplicated into the chain end, we need to redo markBlockSuccessors
673b915e9e0SDimitry Andric /// for just that block.
markBlockSuccessors(const BlockChain & Chain,const MachineBasicBlock * MBB,const MachineBasicBlock * LoopHeaderBB,const BlockFilterSet * BlockFilter)674b915e9e0SDimitry Andric void MachineBlockPlacement::markBlockSuccessors(
67571d5a254SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *MBB,
67671d5a254SDimitry Andric const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
67763faed5bSDimitry Andric // Add any successors for which this is the only un-placed in-loop
67863faed5bSDimitry Andric // predecessor to the worklist as a viable candidate for CFG-neutral
67963faed5bSDimitry Andric // placement. No subsequent placement of this block will violate the CFG
68063faed5bSDimitry Andric // shape, so we get to use heuristics to choose a favorable placement.
6815a5ac124SDimitry Andric for (MachineBasicBlock *Succ : MBB->successors()) {
6825a5ac124SDimitry Andric if (BlockFilter && !BlockFilter->count(Succ))
68363faed5bSDimitry Andric continue;
6845a5ac124SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ];
68563faed5bSDimitry Andric // Disregard edges within a fixed chain, or edges to the loop header.
6865a5ac124SDimitry Andric if (&Chain == &SuccChain || Succ == LoopHeaderBB)
68763faed5bSDimitry Andric continue;
68863faed5bSDimitry Andric
68963faed5bSDimitry Andric // This is a cross-chain edge that is within the loop, so decrement the
69063faed5bSDimitry Andric // loop predecessor count of the destination chain.
69101095a5dSDimitry Andric if (SuccChain.UnscheduledPredecessors == 0 ||
69201095a5dSDimitry Andric --SuccChain.UnscheduledPredecessors > 0)
69301095a5dSDimitry Andric continue;
69401095a5dSDimitry Andric
695b915e9e0SDimitry Andric auto *NewBB = *SuccChain.begin();
696b915e9e0SDimitry Andric if (NewBB->isEHPad())
697b915e9e0SDimitry Andric EHPadWorkList.push_back(NewBB);
69801095a5dSDimitry Andric else
699b915e9e0SDimitry Andric BlockWorkList.push_back(NewBB);
70063faed5bSDimitry Andric }
70163faed5bSDimitry Andric }
70263faed5bSDimitry Andric
70301095a5dSDimitry Andric /// This helper function collects the set of successors of block
70401095a5dSDimitry Andric /// \p BB that are allowed to be its layout successors, and return
70501095a5dSDimitry Andric /// the total branch probability of edges from \p BB to those
70601095a5dSDimitry Andric /// blocks.
collectViableSuccessors(const MachineBasicBlock * BB,const BlockChain & Chain,const BlockFilterSet * BlockFilter,SmallVector<MachineBasicBlock *,4> & Successors)70701095a5dSDimitry Andric BranchProbability MachineBlockPlacement::collectViableSuccessors(
70871d5a254SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain,
70971d5a254SDimitry Andric const BlockFilterSet *BlockFilter,
71001095a5dSDimitry Andric SmallVector<MachineBasicBlock *, 4> &Successors) {
71101095a5dSDimitry Andric // Adjust edge probabilities by excluding edges pointing to blocks that is
71201095a5dSDimitry Andric // either not in BlockFilter or is already in the current chain. Consider the
71301095a5dSDimitry Andric // following CFG:
71401095a5dSDimitry Andric //
71501095a5dSDimitry Andric // --->A
71601095a5dSDimitry Andric // | / \
71701095a5dSDimitry Andric // | B C
71801095a5dSDimitry Andric // | \ / \
71901095a5dSDimitry Andric // ----D E
72001095a5dSDimitry Andric //
72101095a5dSDimitry Andric // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
72201095a5dSDimitry Andric // A->C is chosen as a fall-through, D won't be selected as a successor of C
72301095a5dSDimitry Andric // due to CFG constraint (the probability of C->D is not greater than
7247c7aba6eSDimitry Andric // HotProb to break topo-order). If we exclude E that is not in BlockFilter
72501095a5dSDimitry Andric // when calculating the probability of C->D, D will be selected and we
72601095a5dSDimitry Andric // will get A C D B as the layout of this loop.
72701095a5dSDimitry Andric auto AdjustedSumProb = BranchProbability::getOne();
72801095a5dSDimitry Andric for (MachineBasicBlock *Succ : BB->successors()) {
72901095a5dSDimitry Andric bool SkipSucc = false;
73001095a5dSDimitry Andric if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
73101095a5dSDimitry Andric SkipSucc = true;
73201095a5dSDimitry Andric } else {
73301095a5dSDimitry Andric BlockChain *SuccChain = BlockToChain[Succ];
73401095a5dSDimitry Andric if (SuccChain == &Chain) {
73501095a5dSDimitry Andric SkipSucc = true;
73601095a5dSDimitry Andric } else if (Succ != *SuccChain->begin()) {
737eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " " << getBlockName(Succ)
738eb11fae6SDimitry Andric << " -> Mid chain!\n");
73901095a5dSDimitry Andric continue;
74001095a5dSDimitry Andric }
74101095a5dSDimitry Andric }
74201095a5dSDimitry Andric if (SkipSucc)
74301095a5dSDimitry Andric AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
74401095a5dSDimitry Andric else
74501095a5dSDimitry Andric Successors.push_back(Succ);
74601095a5dSDimitry Andric }
74701095a5dSDimitry Andric
74801095a5dSDimitry Andric return AdjustedSumProb;
74901095a5dSDimitry Andric }
75001095a5dSDimitry Andric
75101095a5dSDimitry Andric /// The helper function returns the branch probability that is adjusted
75201095a5dSDimitry Andric /// or normalized over the new total \p AdjustedSumProb.
75301095a5dSDimitry Andric static BranchProbability
getAdjustedProbability(BranchProbability OrigProb,BranchProbability AdjustedSumProb)75401095a5dSDimitry Andric getAdjustedProbability(BranchProbability OrigProb,
75501095a5dSDimitry Andric BranchProbability AdjustedSumProb) {
75601095a5dSDimitry Andric BranchProbability SuccProb;
75701095a5dSDimitry Andric uint32_t SuccProbN = OrigProb.getNumerator();
75801095a5dSDimitry Andric uint32_t SuccProbD = AdjustedSumProb.getNumerator();
75901095a5dSDimitry Andric if (SuccProbN >= SuccProbD)
76001095a5dSDimitry Andric SuccProb = BranchProbability::getOne();
76101095a5dSDimitry Andric else
76201095a5dSDimitry Andric SuccProb = BranchProbability(SuccProbN, SuccProbD);
76301095a5dSDimitry Andric
76401095a5dSDimitry Andric return SuccProb;
76501095a5dSDimitry Andric }
76601095a5dSDimitry Andric
76771d5a254SDimitry Andric /// Check if \p BB has exactly the successors in \p Successors.
76871d5a254SDimitry Andric static bool
hasSameSuccessors(MachineBasicBlock & BB,SmallPtrSetImpl<const MachineBasicBlock * > & Successors)76971d5a254SDimitry Andric hasSameSuccessors(MachineBasicBlock &BB,
77071d5a254SDimitry Andric SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
77171d5a254SDimitry Andric if (BB.succ_size() != Successors.size())
77201095a5dSDimitry Andric return false;
77371d5a254SDimitry Andric // We don't want to count self-loops
77471d5a254SDimitry Andric if (Successors.count(&BB))
77571d5a254SDimitry Andric return false;
77671d5a254SDimitry Andric for (MachineBasicBlock *Succ : BB.successors())
77771d5a254SDimitry Andric if (!Successors.count(Succ))
77871d5a254SDimitry Andric return false;
77971d5a254SDimitry Andric return true;
78071d5a254SDimitry Andric }
78171d5a254SDimitry Andric
78271d5a254SDimitry Andric /// Check if a block should be tail duplicated to increase fallthrough
78371d5a254SDimitry Andric /// opportunities.
78471d5a254SDimitry Andric /// \p BB Block to check.
shouldTailDuplicate(MachineBasicBlock * BB)78571d5a254SDimitry Andric bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
78671d5a254SDimitry Andric // Blocks with single successors don't create additional fallthrough
78771d5a254SDimitry Andric // opportunities. Don't duplicate them. TODO: When conditional exits are
78871d5a254SDimitry Andric // analyzable, allow them to be duplicated.
78971d5a254SDimitry Andric bool IsSimple = TailDup.isSimpleBB(BB);
79071d5a254SDimitry Andric
79171d5a254SDimitry Andric if (BB->succ_size() == 1)
79271d5a254SDimitry Andric return false;
79371d5a254SDimitry Andric return TailDup.shouldTailDuplicate(IsSimple, *BB);
79471d5a254SDimitry Andric }
79571d5a254SDimitry Andric
79671d5a254SDimitry Andric /// Compare 2 BlockFrequency's with a small penalty for \p A.
79771d5a254SDimitry Andric /// In order to be conservative, we apply a X% penalty to account for
79871d5a254SDimitry Andric /// increased icache pressure and static heuristics. For small frequencies
79971d5a254SDimitry Andric /// we use only the numerators to improve accuracy. For simplicity, we assume the
80071d5a254SDimitry Andric /// penalty is less than 100%
80171d5a254SDimitry Andric /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
greaterWithBias(BlockFrequency A,BlockFrequency B,BlockFrequency EntryFreq)80271d5a254SDimitry Andric static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
803b1c73532SDimitry Andric BlockFrequency EntryFreq) {
80471d5a254SDimitry Andric BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
80571d5a254SDimitry Andric BlockFrequency Gain = A - B;
806b1c73532SDimitry Andric return (Gain / ThresholdProb) >= EntryFreq;
80771d5a254SDimitry Andric }
80871d5a254SDimitry Andric
80971d5a254SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase
81071d5a254SDimitry Andric /// fallthroughs. It only makes sense to call this function when
81171d5a254SDimitry Andric /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
81271d5a254SDimitry Andric /// always locally profitable if we would have picked \p Succ without
81371d5a254SDimitry Andric /// considering duplication.
isProfitableToTailDup(const MachineBasicBlock * BB,const MachineBasicBlock * Succ,BranchProbability QProb,const BlockChain & Chain,const BlockFilterSet * BlockFilter)81471d5a254SDimitry Andric bool MachineBlockPlacement::isProfitableToTailDup(
81571d5a254SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
81671d5a254SDimitry Andric BranchProbability QProb,
81771d5a254SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
81871d5a254SDimitry Andric // We need to do a probability calculation to make sure this is profitable.
81971d5a254SDimitry Andric // First: does succ have a successor that post-dominates? This affects the
82071d5a254SDimitry Andric // calculation. The 2 relevant cases are:
82171d5a254SDimitry Andric // BB BB
82271d5a254SDimitry Andric // | \Qout | \Qout
82371d5a254SDimitry Andric // P| C |P C
82471d5a254SDimitry Andric // = C' = C'
82571d5a254SDimitry Andric // | /Qin | /Qin
82671d5a254SDimitry Andric // | / | /
82771d5a254SDimitry Andric // Succ Succ
82871d5a254SDimitry Andric // / \ | \ V
82971d5a254SDimitry Andric // U/ =V |U \
83071d5a254SDimitry Andric // / \ = D
83171d5a254SDimitry Andric // D E | /
83271d5a254SDimitry Andric // | /
83371d5a254SDimitry Andric // |/
83471d5a254SDimitry Andric // PDom
83571d5a254SDimitry Andric // '=' : Branch taken for that CFG edge
83671d5a254SDimitry Andric // In the second case, Placing Succ while duplicating it into C prevents the
83771d5a254SDimitry Andric // fallthrough of Succ into either D or PDom, because they now have C as an
83871d5a254SDimitry Andric // unplaced predecessor
83971d5a254SDimitry Andric
84071d5a254SDimitry Andric // Start by figuring out which case we fall into
84171d5a254SDimitry Andric MachineBasicBlock *PDom = nullptr;
84271d5a254SDimitry Andric SmallVector<MachineBasicBlock *, 4> SuccSuccs;
84371d5a254SDimitry Andric // Only scan the relevant successors
84471d5a254SDimitry Andric auto AdjustedSuccSumProb =
84571d5a254SDimitry Andric collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
84671d5a254SDimitry Andric BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
84771d5a254SDimitry Andric auto BBFreq = MBFI->getBlockFreq(BB);
84871d5a254SDimitry Andric auto SuccFreq = MBFI->getBlockFreq(Succ);
84971d5a254SDimitry Andric BlockFrequency P = BBFreq * PProb;
85071d5a254SDimitry Andric BlockFrequency Qout = BBFreq * QProb;
851b1c73532SDimitry Andric BlockFrequency EntryFreq = MBFI->getEntryFreq();
85271d5a254SDimitry Andric // If there are no more successors, it is profitable to copy, as it strictly
85371d5a254SDimitry Andric // increases fallthrough.
85471d5a254SDimitry Andric if (SuccSuccs.size() == 0)
85571d5a254SDimitry Andric return greaterWithBias(P, Qout, EntryFreq);
85671d5a254SDimitry Andric
85771d5a254SDimitry Andric auto BestSuccSucc = BranchProbability::getZero();
85871d5a254SDimitry Andric // Find the PDom or the best Succ if no PDom exists.
85971d5a254SDimitry Andric for (MachineBasicBlock *SuccSucc : SuccSuccs) {
86071d5a254SDimitry Andric auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
86171d5a254SDimitry Andric if (Prob > BestSuccSucc)
86271d5a254SDimitry Andric BestSuccSucc = Prob;
86371d5a254SDimitry Andric if (PDom == nullptr)
86471d5a254SDimitry Andric if (MPDT->dominates(SuccSucc, Succ)) {
86571d5a254SDimitry Andric PDom = SuccSucc;
86671d5a254SDimitry Andric break;
86771d5a254SDimitry Andric }
86871d5a254SDimitry Andric }
86971d5a254SDimitry Andric // For the comparisons, we need to know Succ's best incoming edge that isn't
87071d5a254SDimitry Andric // from BB.
87171d5a254SDimitry Andric auto SuccBestPred = BlockFrequency(0);
87271d5a254SDimitry Andric for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
87371d5a254SDimitry Andric if (SuccPred == Succ || SuccPred == BB
87471d5a254SDimitry Andric || BlockToChain[SuccPred] == &Chain
87571d5a254SDimitry Andric || (BlockFilter && !BlockFilter->count(SuccPred)))
87601095a5dSDimitry Andric continue;
87771d5a254SDimitry Andric auto Freq = MBFI->getBlockFreq(SuccPred)
87871d5a254SDimitry Andric * MBPI->getEdgeProbability(SuccPred, Succ);
87971d5a254SDimitry Andric if (Freq > SuccBestPred)
88071d5a254SDimitry Andric SuccBestPred = Freq;
88171d5a254SDimitry Andric }
88271d5a254SDimitry Andric // Qin is Succ's best unplaced incoming edge that isn't BB
88371d5a254SDimitry Andric BlockFrequency Qin = SuccBestPred;
88471d5a254SDimitry Andric // If it doesn't have a post-dominating successor, here is the calculation:
88571d5a254SDimitry Andric // BB BB
88671d5a254SDimitry Andric // | \Qout | \
88771d5a254SDimitry Andric // P| C | =
88871d5a254SDimitry Andric // = C' | C
88971d5a254SDimitry Andric // | /Qin | |
89071d5a254SDimitry Andric // | / | C' (+Succ)
89171d5a254SDimitry Andric // Succ Succ /|
89271d5a254SDimitry Andric // / \ | \/ |
89371d5a254SDimitry Andric // U/ =V | == |
89471d5a254SDimitry Andric // / \ | / \|
89571d5a254SDimitry Andric // D E D E
89671d5a254SDimitry Andric // '=' : Branch taken for that CFG edge
89771d5a254SDimitry Andric // Cost in the first case is: P + V
89871d5a254SDimitry Andric // For this calculation, we always assume P > Qout. If Qout > P
89971d5a254SDimitry Andric // The result of this function will be ignored at the caller.
90071d5a254SDimitry Andric // Let F = SuccFreq - Qin
90171d5a254SDimitry Andric // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
90271d5a254SDimitry Andric
90371d5a254SDimitry Andric if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
90471d5a254SDimitry Andric BranchProbability UProb = BestSuccSucc;
90571d5a254SDimitry Andric BranchProbability VProb = AdjustedSuccSumProb - UProb;
90671d5a254SDimitry Andric BlockFrequency F = SuccFreq - Qin;
90771d5a254SDimitry Andric BlockFrequency V = SuccFreq * VProb;
90871d5a254SDimitry Andric BlockFrequency QinU = std::min(Qin, F) * UProb;
90971d5a254SDimitry Andric BlockFrequency BaseCost = P + V;
91071d5a254SDimitry Andric BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
91171d5a254SDimitry Andric return greaterWithBias(BaseCost, DupCost, EntryFreq);
91271d5a254SDimitry Andric }
91371d5a254SDimitry Andric BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
91471d5a254SDimitry Andric BranchProbability VProb = AdjustedSuccSumProb - UProb;
91571d5a254SDimitry Andric BlockFrequency U = SuccFreq * UProb;
91671d5a254SDimitry Andric BlockFrequency V = SuccFreq * VProb;
91771d5a254SDimitry Andric BlockFrequency F = SuccFreq - Qin;
91871d5a254SDimitry Andric // If there is a post-dominating successor, here is the calculation:
91971d5a254SDimitry Andric // BB BB BB BB
92071d5a254SDimitry Andric // | \Qout | \ | \Qout | \
92171d5a254SDimitry Andric // |P C | = |P C | =
92271d5a254SDimitry Andric // = C' |P C = C' |P C
92371d5a254SDimitry Andric // | /Qin | | | /Qin | |
92471d5a254SDimitry Andric // | / | C' (+Succ) | / | C' (+Succ)
92571d5a254SDimitry Andric // Succ Succ /| Succ Succ /|
92671d5a254SDimitry Andric // | \ V | \/ | | \ V | \/ |
92771d5a254SDimitry Andric // |U \ |U /\ =? |U = |U /\ |
92871d5a254SDimitry Andric // = D = = =?| | D | = =|
92971d5a254SDimitry Andric // | / |/ D | / |/ D
93071d5a254SDimitry Andric // | / | / | = | /
93171d5a254SDimitry Andric // |/ | / |/ | =
93271d5a254SDimitry Andric // Dom Dom Dom Dom
93371d5a254SDimitry Andric // '=' : Branch taken for that CFG edge
93471d5a254SDimitry Andric // The cost for taken branches in the first case is P + U
93571d5a254SDimitry Andric // Let F = SuccFreq - Qin
93671d5a254SDimitry Andric // The cost in the second case (assuming independence), given the layout:
93771d5a254SDimitry Andric // BB, Succ, (C+Succ), D, Dom or the layout:
93871d5a254SDimitry Andric // BB, Succ, D, Dom, (C+Succ)
93971d5a254SDimitry Andric // is Qout + max(F, Qin) * U + min(F, Qin)
94071d5a254SDimitry Andric // compare P + U vs Qout + P * U + Qin.
94171d5a254SDimitry Andric //
94271d5a254SDimitry Andric // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
94371d5a254SDimitry Andric //
94471d5a254SDimitry Andric // For the 3rd case, the cost is P + 2 * V
94571d5a254SDimitry Andric // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
94671d5a254SDimitry Andric // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
94771d5a254SDimitry Andric if (UProb > AdjustedSuccSumProb / 2 &&
94871d5a254SDimitry Andric !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
94971d5a254SDimitry Andric Chain, BlockFilter))
95071d5a254SDimitry Andric // Cases 3 & 4
95171d5a254SDimitry Andric return greaterWithBias(
95271d5a254SDimitry Andric (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
95371d5a254SDimitry Andric EntryFreq);
95471d5a254SDimitry Andric // Cases 1 & 2
95571d5a254SDimitry Andric return greaterWithBias((P + U),
95671d5a254SDimitry Andric (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
95771d5a254SDimitry Andric std::max(Qin, F) * UProb),
95871d5a254SDimitry Andric EntryFreq);
95971d5a254SDimitry Andric }
96071d5a254SDimitry Andric
96171d5a254SDimitry Andric /// Check for a trellis layout. \p BB is the upper part of a trellis if its
96271d5a254SDimitry Andric /// successors form the lower part of a trellis. A successor set S forms the
96371d5a254SDimitry Andric /// lower part of a trellis if all of the predecessors of S are either in S or
96471d5a254SDimitry Andric /// have all of S as successors. We ignore trellises where BB doesn't have 2
96571d5a254SDimitry Andric /// successors because for fewer than 2, it's trivial, and for 3 or greater they
96671d5a254SDimitry Andric /// are very uncommon and complex to compute optimally. Allowing edges within S
96771d5a254SDimitry Andric /// is not strictly a trellis, but the same algorithm works, so we allow it.
isTrellis(const MachineBasicBlock * BB,const SmallVectorImpl<MachineBasicBlock * > & ViableSuccs,const BlockChain & Chain,const BlockFilterSet * BlockFilter)96871d5a254SDimitry Andric bool MachineBlockPlacement::isTrellis(
96971d5a254SDimitry Andric const MachineBasicBlock *BB,
97071d5a254SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
97171d5a254SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
97271d5a254SDimitry Andric // Technically BB could form a trellis with branching factor higher than 2.
97371d5a254SDimitry Andric // But that's extremely uncommon.
97471d5a254SDimitry Andric if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
97571d5a254SDimitry Andric return false;
97671d5a254SDimitry Andric
97771d5a254SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
97871d5a254SDimitry Andric BB->succ_end());
97971d5a254SDimitry Andric // To avoid reviewing the same predecessors twice.
98071d5a254SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
98171d5a254SDimitry Andric
98271d5a254SDimitry Andric for (MachineBasicBlock *Succ : ViableSuccs) {
98371d5a254SDimitry Andric int PredCount = 0;
9844b4fe385SDimitry Andric for (auto *SuccPred : Succ->predecessors()) {
98571d5a254SDimitry Andric // Allow triangle successors, but don't count them.
98671d5a254SDimitry Andric if (Successors.count(SuccPred)) {
98771d5a254SDimitry Andric // Make sure that it is actually a triangle.
98871d5a254SDimitry Andric for (MachineBasicBlock *CheckSucc : SuccPred->successors())
98971d5a254SDimitry Andric if (!Successors.count(CheckSucc))
99071d5a254SDimitry Andric return false;
99101095a5dSDimitry Andric continue;
99271d5a254SDimitry Andric }
99371d5a254SDimitry Andric const BlockChain *PredChain = BlockToChain[SuccPred];
99471d5a254SDimitry Andric if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
99571d5a254SDimitry Andric PredChain == &Chain || PredChain == BlockToChain[Succ])
99671d5a254SDimitry Andric continue;
99771d5a254SDimitry Andric ++PredCount;
99871d5a254SDimitry Andric // Perform the successor check only once.
99971d5a254SDimitry Andric if (!SeenPreds.insert(SuccPred).second)
100071d5a254SDimitry Andric continue;
100171d5a254SDimitry Andric if (!hasSameSuccessors(*SuccPred, Successors))
100271d5a254SDimitry Andric return false;
100371d5a254SDimitry Andric }
100471d5a254SDimitry Andric // If one of the successors has only BB as a predecessor, it is not a
100571d5a254SDimitry Andric // trellis.
100671d5a254SDimitry Andric if (PredCount < 1)
100701095a5dSDimitry Andric return false;
100801095a5dSDimitry Andric }
100901095a5dSDimitry Andric return true;
101071d5a254SDimitry Andric }
101171d5a254SDimitry Andric
101271d5a254SDimitry Andric /// Pick the highest total weight pair of edges that can both be laid out.
101371d5a254SDimitry Andric /// The edges in \p Edges[0] are assumed to have a different destination than
101471d5a254SDimitry Andric /// the edges in \p Edges[1]. Simple counting shows that the best pair is either
101571d5a254SDimitry Andric /// the individual highest weight edges to the 2 different destinations, or in
101671d5a254SDimitry Andric /// case of a conflict, one of them should be replaced with a 2nd best edge.
101771d5a254SDimitry Andric std::pair<MachineBlockPlacement::WeightedEdge,
101871d5a254SDimitry Andric MachineBlockPlacement::WeightedEdge>
getBestNonConflictingEdges(const MachineBasicBlock * BB,MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge,8>> Edges)101971d5a254SDimitry Andric MachineBlockPlacement::getBestNonConflictingEdges(
102071d5a254SDimitry Andric const MachineBasicBlock *BB,
102171d5a254SDimitry Andric MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
102271d5a254SDimitry Andric Edges) {
102371d5a254SDimitry Andric // Sort the edges, and then for each successor, find the best incoming
102471d5a254SDimitry Andric // predecessor. If the best incoming predecessors aren't the same,
102571d5a254SDimitry Andric // then that is clearly the best layout. If there is a conflict, one of the
102671d5a254SDimitry Andric // successors will have to fallthrough from the second best predecessor. We
102771d5a254SDimitry Andric // compare which combination is better overall.
102871d5a254SDimitry Andric
102971d5a254SDimitry Andric // Sort for highest frequency.
103071d5a254SDimitry Andric auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
103171d5a254SDimitry Andric
1032e6d15924SDimitry Andric llvm::stable_sort(Edges[0], Cmp);
1033e6d15924SDimitry Andric llvm::stable_sort(Edges[1], Cmp);
103471d5a254SDimitry Andric auto BestA = Edges[0].begin();
103571d5a254SDimitry Andric auto BestB = Edges[1].begin();
103671d5a254SDimitry Andric // Arrange for the correct answer to be in BestA and BestB
103771d5a254SDimitry Andric // If the 2 best edges don't conflict, the answer is already there.
103871d5a254SDimitry Andric if (BestA->Src == BestB->Src) {
103971d5a254SDimitry Andric // Compare the total fallthrough of (Best + Second Best) for both pairs
104071d5a254SDimitry Andric auto SecondBestA = std::next(BestA);
104171d5a254SDimitry Andric auto SecondBestB = std::next(BestB);
104271d5a254SDimitry Andric BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
104371d5a254SDimitry Andric BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
104471d5a254SDimitry Andric if (BestAScore < BestBScore)
104571d5a254SDimitry Andric BestA = SecondBestA;
104671d5a254SDimitry Andric else
104771d5a254SDimitry Andric BestB = SecondBestB;
104871d5a254SDimitry Andric }
104971d5a254SDimitry Andric // Arrange for the BB edge to be in BestA if it exists.
105071d5a254SDimitry Andric if (BestB->Src == BB)
105171d5a254SDimitry Andric std::swap(BestA, BestB);
105271d5a254SDimitry Andric return std::make_pair(*BestA, *BestB);
105371d5a254SDimitry Andric }
105471d5a254SDimitry Andric
105571d5a254SDimitry Andric /// Get the best successor from \p BB based on \p BB being part of a trellis.
105671d5a254SDimitry Andric /// We only handle trellises with 2 successors, so the algorithm is
105771d5a254SDimitry Andric /// straightforward: Find the best pair of edges that don't conflict. We find
105871d5a254SDimitry Andric /// the best incoming edge for each successor in the trellis. If those conflict,
105971d5a254SDimitry Andric /// we consider which of them should be replaced with the second best.
106071d5a254SDimitry Andric /// Upon return the two best edges will be in \p BestEdges. If one of the edges
106171d5a254SDimitry Andric /// comes from \p BB, it will be in \p BestEdges[0]
106271d5a254SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult
getBestTrellisSuccessor(const MachineBasicBlock * BB,const SmallVectorImpl<MachineBasicBlock * > & ViableSuccs,BranchProbability AdjustedSumProb,const BlockChain & Chain,const BlockFilterSet * BlockFilter)106371d5a254SDimitry Andric MachineBlockPlacement::getBestTrellisSuccessor(
106471d5a254SDimitry Andric const MachineBasicBlock *BB,
106571d5a254SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
106671d5a254SDimitry Andric BranchProbability AdjustedSumProb, const BlockChain &Chain,
106771d5a254SDimitry Andric const BlockFilterSet *BlockFilter) {
106871d5a254SDimitry Andric
106971d5a254SDimitry Andric BlockAndTailDupResult Result = {nullptr, false};
107071d5a254SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
107171d5a254SDimitry Andric BB->succ_end());
107271d5a254SDimitry Andric
107371d5a254SDimitry Andric // We assume size 2 because it's common. For general n, we would have to do
107471d5a254SDimitry Andric // the Hungarian algorithm, but it's not worth the complexity because more
107571d5a254SDimitry Andric // than 2 successors is fairly uncommon, and a trellis even more so.
107671d5a254SDimitry Andric if (Successors.size() != 2 || ViableSuccs.size() != 2)
107771d5a254SDimitry Andric return Result;
107871d5a254SDimitry Andric
107971d5a254SDimitry Andric // Collect the edge frequencies of all edges that form the trellis.
108071d5a254SDimitry Andric SmallVector<WeightedEdge, 8> Edges[2];
108171d5a254SDimitry Andric int SuccIndex = 0;
10824b4fe385SDimitry Andric for (auto *Succ : ViableSuccs) {
108371d5a254SDimitry Andric for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
108471d5a254SDimitry Andric // Skip any placed predecessors that are not BB
108571d5a254SDimitry Andric if (SuccPred != BB)
108671d5a254SDimitry Andric if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
108771d5a254SDimitry Andric BlockToChain[SuccPred] == &Chain ||
108871d5a254SDimitry Andric BlockToChain[SuccPred] == BlockToChain[Succ])
108971d5a254SDimitry Andric continue;
109071d5a254SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
109171d5a254SDimitry Andric MBPI->getEdgeProbability(SuccPred, Succ);
109271d5a254SDimitry Andric Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
109371d5a254SDimitry Andric }
109471d5a254SDimitry Andric ++SuccIndex;
109571d5a254SDimitry Andric }
109671d5a254SDimitry Andric
109771d5a254SDimitry Andric // Pick the best combination of 2 edges from all the edges in the trellis.
109871d5a254SDimitry Andric WeightedEdge BestA, BestB;
109971d5a254SDimitry Andric std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
110071d5a254SDimitry Andric
110171d5a254SDimitry Andric if (BestA.Src != BB) {
110271d5a254SDimitry Andric // If we have a trellis, and BB doesn't have the best fallthrough edges,
110371d5a254SDimitry Andric // we shouldn't choose any successor. We've already looked and there's a
110471d5a254SDimitry Andric // better fallthrough edge for all the successors.
1105eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
110671d5a254SDimitry Andric return Result;
110771d5a254SDimitry Andric }
110871d5a254SDimitry Andric
110971d5a254SDimitry Andric // Did we pick the triangle edge? If tail-duplication is profitable, do
111071d5a254SDimitry Andric // that instead. Otherwise merge the triangle edge now while we know it is
111171d5a254SDimitry Andric // optimal.
111271d5a254SDimitry Andric if (BestA.Dest == BestB.Src) {
111371d5a254SDimitry Andric // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
111471d5a254SDimitry Andric // would be better.
111571d5a254SDimitry Andric MachineBasicBlock *Succ1 = BestA.Dest;
111671d5a254SDimitry Andric MachineBasicBlock *Succ2 = BestB.Dest;
111771d5a254SDimitry Andric // Check to see if tail-duplication would be profitable.
1118eb11fae6SDimitry Andric if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) &&
111971d5a254SDimitry Andric canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
112071d5a254SDimitry Andric isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
112171d5a254SDimitry Andric Chain, BlockFilter)) {
1122eb11fae6SDimitry Andric LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
112371d5a254SDimitry Andric MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
112471d5a254SDimitry Andric dbgs() << " Selected: " << getBlockName(Succ2)
1125eb11fae6SDimitry Andric << ", probability: " << Succ2Prob
1126eb11fae6SDimitry Andric << " (Tail Duplicate)\n");
112771d5a254SDimitry Andric Result.BB = Succ2;
112871d5a254SDimitry Andric Result.ShouldTailDup = true;
112971d5a254SDimitry Andric return Result;
113071d5a254SDimitry Andric }
113171d5a254SDimitry Andric }
113271d5a254SDimitry Andric // We have already computed the optimal edge for the other side of the
113371d5a254SDimitry Andric // trellis.
113471d5a254SDimitry Andric ComputedEdges[BestB.Src] = { BestB.Dest, false };
113571d5a254SDimitry Andric
113671d5a254SDimitry Andric auto TrellisSucc = BestA.Dest;
1137eb11fae6SDimitry Andric LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability(
113871d5a254SDimitry Andric MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
113971d5a254SDimitry Andric dbgs() << " Selected: " << getBlockName(TrellisSucc)
114071d5a254SDimitry Andric << ", probability: " << SuccProb << " (Trellis)\n");
114171d5a254SDimitry Andric Result.BB = TrellisSucc;
114271d5a254SDimitry Andric return Result;
114371d5a254SDimitry Andric }
114471d5a254SDimitry Andric
1145eb11fae6SDimitry Andric /// When the option allowTailDupPlacement() is on, this method checks if the
114671d5a254SDimitry Andric /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
114771d5a254SDimitry Andric /// into all of its unplaced, unfiltered predecessors, that are not BB.
canTailDuplicateUnplacedPreds(const MachineBasicBlock * BB,MachineBasicBlock * Succ,const BlockChain & Chain,const BlockFilterSet * BlockFilter)114871d5a254SDimitry Andric bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
114971d5a254SDimitry Andric const MachineBasicBlock *BB, MachineBasicBlock *Succ,
115071d5a254SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
115171d5a254SDimitry Andric if (!shouldTailDuplicate(Succ))
115201095a5dSDimitry Andric return false;
115371d5a254SDimitry Andric
1154706b4fc4SDimitry Andric // The result of canTailDuplicate.
1155706b4fc4SDimitry Andric bool Duplicate = true;
1156706b4fc4SDimitry Andric // Number of possible duplication.
1157706b4fc4SDimitry Andric unsigned int NumDup = 0;
1158706b4fc4SDimitry Andric
115971d5a254SDimitry Andric // For CFG checking.
116071d5a254SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
116171d5a254SDimitry Andric BB->succ_end());
116271d5a254SDimitry Andric for (MachineBasicBlock *Pred : Succ->predecessors()) {
116371d5a254SDimitry Andric // Make sure all unplaced and unfiltered predecessors can be
116471d5a254SDimitry Andric // tail-duplicated into.
116571d5a254SDimitry Andric // Skip any blocks that are already placed or not in this loop.
116671d5a254SDimitry Andric if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
11677fa27ce4SDimitry Andric || (BlockToChain[Pred] == &Chain && !Succ->succ_empty()))
116871d5a254SDimitry Andric continue;
116971d5a254SDimitry Andric if (!TailDup.canTailDuplicate(Succ, Pred)) {
117071d5a254SDimitry Andric if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
117171d5a254SDimitry Andric // This will result in a trellis after tail duplication, so we don't
117271d5a254SDimitry Andric // need to copy Succ into this predecessor. In the presence
117371d5a254SDimitry Andric // of a trellis tail duplication can continue to be profitable.
117471d5a254SDimitry Andric // For example:
117571d5a254SDimitry Andric // A A
117671d5a254SDimitry Andric // |\ |\
117771d5a254SDimitry Andric // | \ | \
117871d5a254SDimitry Andric // | C | C+BB
117971d5a254SDimitry Andric // | / | |
118071d5a254SDimitry Andric // |/ | |
118171d5a254SDimitry Andric // BB => BB |
118271d5a254SDimitry Andric // |\ |\/|
118371d5a254SDimitry Andric // | \ |/\|
118471d5a254SDimitry Andric // | D | D
118571d5a254SDimitry Andric // | / | /
118671d5a254SDimitry Andric // |/ |/
118771d5a254SDimitry Andric // Succ Succ
118871d5a254SDimitry Andric //
118971d5a254SDimitry Andric // After BB was duplicated into C, the layout looks like the one on the
119071d5a254SDimitry Andric // right. BB and C now have the same successors. When considering
119171d5a254SDimitry Andric // whether Succ can be duplicated into all its unplaced predecessors, we
119271d5a254SDimitry Andric // ignore C.
119371d5a254SDimitry Andric // We can do this because C already has a profitable fallthrough, namely
119471d5a254SDimitry Andric // D. TODO(iteratee): ignore sufficiently cold predecessors for
119571d5a254SDimitry Andric // duplication and for this test.
119671d5a254SDimitry Andric //
119771d5a254SDimitry Andric // This allows trellises to be laid out in 2 separate chains
119871d5a254SDimitry Andric // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
119971d5a254SDimitry Andric // because it allows the creation of 2 fallthrough paths with links
120071d5a254SDimitry Andric // between them, and we correctly identify the best layout for these
120171d5a254SDimitry Andric // CFGs. We want to extend trellises that the user created in addition
120271d5a254SDimitry Andric // to trellises created by tail-duplication, so we just look for the
120371d5a254SDimitry Andric // CFG.
120471d5a254SDimitry Andric continue;
1205706b4fc4SDimitry Andric Duplicate = false;
1206706b4fc4SDimitry Andric continue;
1207706b4fc4SDimitry Andric }
1208706b4fc4SDimitry Andric NumDup++;
1209706b4fc4SDimitry Andric }
1210706b4fc4SDimitry Andric
1211706b4fc4SDimitry Andric // No possible duplication in current filter set.
1212706b4fc4SDimitry Andric if (NumDup == 0)
121371d5a254SDimitry Andric return false;
1214706b4fc4SDimitry Andric
1215cfca06d7SDimitry Andric // If profile information is available, findDuplicateCandidates can do more
1216cfca06d7SDimitry Andric // precise benefit analysis.
1217cfca06d7SDimitry Andric if (F->getFunction().hasProfileData())
1218cfca06d7SDimitry Andric return true;
1219cfca06d7SDimitry Andric
1220706b4fc4SDimitry Andric // This is mainly for function exit BB.
1221706b4fc4SDimitry Andric // The integrated tail duplication is really designed for increasing
1222706b4fc4SDimitry Andric // fallthrough from predecessors from Succ to its successors. We may need
1223706b4fc4SDimitry Andric // other machanism to handle different cases.
1224c0981da4SDimitry Andric if (Succ->succ_empty())
1225706b4fc4SDimitry Andric return true;
1226706b4fc4SDimitry Andric
1227706b4fc4SDimitry Andric // Plus the already placed predecessor.
1228706b4fc4SDimitry Andric NumDup++;
1229706b4fc4SDimitry Andric
1230706b4fc4SDimitry Andric // If the duplication candidate has more unplaced predecessors than
1231706b4fc4SDimitry Andric // successors, the extra duplication can't bring more fallthrough.
1232706b4fc4SDimitry Andric //
1233706b4fc4SDimitry Andric // Pred1 Pred2 Pred3
1234706b4fc4SDimitry Andric // \ | /
1235706b4fc4SDimitry Andric // \ | /
1236706b4fc4SDimitry Andric // \ | /
1237706b4fc4SDimitry Andric // Dup
1238706b4fc4SDimitry Andric // / \
1239706b4fc4SDimitry Andric // / \
1240706b4fc4SDimitry Andric // Succ1 Succ2
1241706b4fc4SDimitry Andric //
1242706b4fc4SDimitry Andric // In this example Dup has 2 successors and 3 predecessors, duplication of Dup
1243706b4fc4SDimitry Andric // can increase the fallthrough from Pred1 to Succ1 and from Pred2 to Succ2,
1244706b4fc4SDimitry Andric // but the duplication into Pred3 can't increase fallthrough.
1245706b4fc4SDimitry Andric //
1246706b4fc4SDimitry Andric // A small number of extra duplication may not hurt too much. We need a better
1247706b4fc4SDimitry Andric // heuristic to handle it.
1248706b4fc4SDimitry Andric if ((NumDup > Succ->succ_size()) || !Duplicate)
1249706b4fc4SDimitry Andric return false;
1250706b4fc4SDimitry Andric
125171d5a254SDimitry Andric return true;
125271d5a254SDimitry Andric }
125371d5a254SDimitry Andric
125471d5a254SDimitry Andric /// Find chains of triangles where we believe it would be profitable to
125571d5a254SDimitry Andric /// tail-duplicate them all, but a local analysis would not find them.
125671d5a254SDimitry Andric /// There are 3 ways this can be profitable:
125771d5a254SDimitry Andric /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
125871d5a254SDimitry Andric /// longer chains)
125971d5a254SDimitry Andric /// 2) The chains are statically correlated. Branch probabilities have a very
126071d5a254SDimitry Andric /// U-shaped distribution.
126171d5a254SDimitry Andric /// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
126271d5a254SDimitry Andric /// If the branches in a chain are likely to be from the same side of the
126371d5a254SDimitry Andric /// distribution as their predecessor, but are independent at runtime, this
126471d5a254SDimitry Andric /// transformation is profitable. (Because the cost of being wrong is a small
126571d5a254SDimitry Andric /// fixed cost, unlike the standard triangle layout where the cost of being
126671d5a254SDimitry Andric /// wrong scales with the # of triangles.)
126771d5a254SDimitry Andric /// 3) The chains are dynamically correlated. If the probability that a previous
126871d5a254SDimitry Andric /// branch was taken positively influences whether the next branch will be
126971d5a254SDimitry Andric /// taken
127071d5a254SDimitry Andric /// We believe that 2 and 3 are common enough to justify the small margin in 1.
precomputeTriangleChains()127171d5a254SDimitry Andric void MachineBlockPlacement::precomputeTriangleChains() {
127271d5a254SDimitry Andric struct TriangleChain {
127371d5a254SDimitry Andric std::vector<MachineBasicBlock *> Edges;
1274044eb2f6SDimitry Andric
127571d5a254SDimitry Andric TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
127671d5a254SDimitry Andric : Edges({src, dst}) {}
127771d5a254SDimitry Andric
127871d5a254SDimitry Andric void append(MachineBasicBlock *dst) {
127971d5a254SDimitry Andric assert(getKey()->isSuccessor(dst) &&
128071d5a254SDimitry Andric "Attempting to append a block that is not a successor.");
128171d5a254SDimitry Andric Edges.push_back(dst);
128271d5a254SDimitry Andric }
128371d5a254SDimitry Andric
128471d5a254SDimitry Andric unsigned count() const { return Edges.size() - 1; }
128571d5a254SDimitry Andric
128671d5a254SDimitry Andric MachineBasicBlock *getKey() const {
128771d5a254SDimitry Andric return Edges.back();
128871d5a254SDimitry Andric }
128971d5a254SDimitry Andric };
129071d5a254SDimitry Andric
129171d5a254SDimitry Andric if (TriangleChainCount == 0)
129271d5a254SDimitry Andric return;
129371d5a254SDimitry Andric
1294eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n");
129571d5a254SDimitry Andric // Map from last block to the chain that contains it. This allows us to extend
129671d5a254SDimitry Andric // chains as we find new triangles.
129771d5a254SDimitry Andric DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
129871d5a254SDimitry Andric for (MachineBasicBlock &BB : *F) {
129971d5a254SDimitry Andric // If BB doesn't have 2 successors, it doesn't start a triangle.
130071d5a254SDimitry Andric if (BB.succ_size() != 2)
130171d5a254SDimitry Andric continue;
130271d5a254SDimitry Andric MachineBasicBlock *PDom = nullptr;
130371d5a254SDimitry Andric for (MachineBasicBlock *Succ : BB.successors()) {
130471d5a254SDimitry Andric if (!MPDT->dominates(Succ, &BB))
130571d5a254SDimitry Andric continue;
130671d5a254SDimitry Andric PDom = Succ;
130771d5a254SDimitry Andric break;
130871d5a254SDimitry Andric }
130971d5a254SDimitry Andric // If BB doesn't have a post-dominating successor, it doesn't form a
131071d5a254SDimitry Andric // triangle.
131171d5a254SDimitry Andric if (PDom == nullptr)
131271d5a254SDimitry Andric continue;
131371d5a254SDimitry Andric // If PDom has a hint that it is low probability, skip this triangle.
131471d5a254SDimitry Andric if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
131571d5a254SDimitry Andric continue;
131671d5a254SDimitry Andric // If PDom isn't eligible for duplication, this isn't the kind of triangle
131771d5a254SDimitry Andric // we're looking for.
131871d5a254SDimitry Andric if (!shouldTailDuplicate(PDom))
131971d5a254SDimitry Andric continue;
132071d5a254SDimitry Andric bool CanTailDuplicate = true;
132171d5a254SDimitry Andric // If PDom can't tail-duplicate into it's non-BB predecessors, then this
132271d5a254SDimitry Andric // isn't the kind of triangle we're looking for.
132371d5a254SDimitry Andric for (MachineBasicBlock* Pred : PDom->predecessors()) {
132471d5a254SDimitry Andric if (Pred == &BB)
132571d5a254SDimitry Andric continue;
132671d5a254SDimitry Andric if (!TailDup.canTailDuplicate(PDom, Pred)) {
132771d5a254SDimitry Andric CanTailDuplicate = false;
132871d5a254SDimitry Andric break;
132971d5a254SDimitry Andric }
133071d5a254SDimitry Andric }
133171d5a254SDimitry Andric // If we can't tail-duplicate PDom to its predecessors, then skip this
133271d5a254SDimitry Andric // triangle.
133371d5a254SDimitry Andric if (!CanTailDuplicate)
133471d5a254SDimitry Andric continue;
133571d5a254SDimitry Andric
133671d5a254SDimitry Andric // Now we have an interesting triangle. Insert it if it's not part of an
13377c7aba6eSDimitry Andric // existing chain.
133871d5a254SDimitry Andric // Note: This cannot be replaced with a call insert() or emplace() because
133971d5a254SDimitry Andric // the find key is BB, but the insert/emplace key is PDom.
134071d5a254SDimitry Andric auto Found = TriangleChainMap.find(&BB);
134171d5a254SDimitry Andric // If it is, remove the chain from the map, grow it, and put it back in the
134271d5a254SDimitry Andric // map with the end as the new key.
134371d5a254SDimitry Andric if (Found != TriangleChainMap.end()) {
134471d5a254SDimitry Andric TriangleChain Chain = std::move(Found->second);
134571d5a254SDimitry Andric TriangleChainMap.erase(Found);
134671d5a254SDimitry Andric Chain.append(PDom);
134771d5a254SDimitry Andric TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
134871d5a254SDimitry Andric } else {
134971d5a254SDimitry Andric auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
135071d5a254SDimitry Andric assert(InsertResult.second && "Block seen twice.");
135171d5a254SDimitry Andric (void)InsertResult;
135271d5a254SDimitry Andric }
135371d5a254SDimitry Andric }
135471d5a254SDimitry Andric
135571d5a254SDimitry Andric // Iterating over a DenseMap is safe here, because the only thing in the body
135671d5a254SDimitry Andric // of the loop is inserting into another DenseMap (ComputedEdges).
135771d5a254SDimitry Andric // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
135871d5a254SDimitry Andric for (auto &ChainPair : TriangleChainMap) {
135971d5a254SDimitry Andric TriangleChain &Chain = ChainPair.second;
136071d5a254SDimitry Andric // Benchmarking has shown that due to branch correlation duplicating 2 or
136171d5a254SDimitry Andric // more triangles is profitable, despite the calculations assuming
136271d5a254SDimitry Andric // independence.
136371d5a254SDimitry Andric if (Chain.count() < TriangleChainCount)
136471d5a254SDimitry Andric continue;
136571d5a254SDimitry Andric MachineBasicBlock *dst = Chain.Edges.back();
136671d5a254SDimitry Andric Chain.Edges.pop_back();
136771d5a254SDimitry Andric for (MachineBasicBlock *src : reverse(Chain.Edges)) {
1368eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->"
1369eb11fae6SDimitry Andric << getBlockName(dst)
1370eb11fae6SDimitry Andric << " as pre-computed based on triangles.\n");
137171d5a254SDimitry Andric
137271d5a254SDimitry Andric auto InsertResult = ComputedEdges.insert({src, {dst, true}});
137371d5a254SDimitry Andric assert(InsertResult.second && "Block seen twice.");
137471d5a254SDimitry Andric (void)InsertResult;
137571d5a254SDimitry Andric
137671d5a254SDimitry Andric dst = src;
137771d5a254SDimitry Andric }
137871d5a254SDimitry Andric }
137901095a5dSDimitry Andric }
138001095a5dSDimitry Andric
138101095a5dSDimitry Andric // When profile is not present, return the StaticLikelyProb.
138201095a5dSDimitry Andric // When profile is available, we need to handle the triangle-shape CFG.
getLayoutSuccessorProbThreshold(const MachineBasicBlock * BB)138301095a5dSDimitry Andric static BranchProbability getLayoutSuccessorProbThreshold(
138471d5a254SDimitry Andric const MachineBasicBlock *BB) {
1385c7dac04cSDimitry Andric if (!BB->getParent()->getFunction().hasProfileData())
138601095a5dSDimitry Andric return BranchProbability(StaticLikelyProb, 100);
138701095a5dSDimitry Andric if (BB->succ_size() == 2) {
138801095a5dSDimitry Andric const MachineBasicBlock *Succ1 = *BB->succ_begin();
138901095a5dSDimitry Andric const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
139001095a5dSDimitry Andric if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
139101095a5dSDimitry Andric /* See case 1 below for the cost analysis. For BB->Succ to
139201095a5dSDimitry Andric * be taken with smaller cost, the following needs to hold:
139301095a5dSDimitry Andric * Prob(BB->Succ) > 2 * Prob(BB->Pred)
139471d5a254SDimitry Andric * So the threshold T in the calculation below
139571d5a254SDimitry Andric * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
139671d5a254SDimitry Andric * So T / (1 - T) = 2, Yielding T = 2/3
139771d5a254SDimitry Andric * Also adding user specified branch bias, we have
139801095a5dSDimitry Andric * T = (2/3)*(ProfileLikelyProb/50)
139901095a5dSDimitry Andric * = (2*ProfileLikelyProb)/150)
140001095a5dSDimitry Andric */
140101095a5dSDimitry Andric return BranchProbability(2 * ProfileLikelyProb, 150);
140201095a5dSDimitry Andric }
140301095a5dSDimitry Andric }
140401095a5dSDimitry Andric return BranchProbability(ProfileLikelyProb, 100);
140501095a5dSDimitry Andric }
140601095a5dSDimitry Andric
140701095a5dSDimitry Andric /// Checks to see if the layout candidate block \p Succ has a better layout
140801095a5dSDimitry Andric /// predecessor than \c BB. If yes, returns true.
140971d5a254SDimitry Andric /// \p SuccProb: The probability adjusted for only remaining blocks.
141071d5a254SDimitry Andric /// Only used for logging
141171d5a254SDimitry Andric /// \p RealSuccProb: The un-adjusted probability.
141271d5a254SDimitry Andric /// \p Chain: The chain that BB belongs to and Succ is being considered for.
141371d5a254SDimitry Andric /// \p BlockFilter: if non-null, the set of blocks that make up the loop being
141471d5a254SDimitry Andric /// considered
hasBetterLayoutPredecessor(const MachineBasicBlock * BB,const MachineBasicBlock * Succ,const BlockChain & SuccChain,BranchProbability SuccProb,BranchProbability RealSuccProb,const BlockChain & Chain,const BlockFilterSet * BlockFilter)141501095a5dSDimitry Andric bool MachineBlockPlacement::hasBetterLayoutPredecessor(
141671d5a254SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
141771d5a254SDimitry Andric const BlockChain &SuccChain, BranchProbability SuccProb,
141871d5a254SDimitry Andric BranchProbability RealSuccProb, const BlockChain &Chain,
141971d5a254SDimitry Andric const BlockFilterSet *BlockFilter) {
142001095a5dSDimitry Andric
142101095a5dSDimitry Andric // There isn't a better layout when there are no unscheduled predecessors.
142201095a5dSDimitry Andric if (SuccChain.UnscheduledPredecessors == 0)
142301095a5dSDimitry Andric return false;
142401095a5dSDimitry Andric
142501095a5dSDimitry Andric // There are two basic scenarios here:
142601095a5dSDimitry Andric // -------------------------------------
142701095a5dSDimitry Andric // Case 1: triangular shape CFG (if-then):
142801095a5dSDimitry Andric // BB
142901095a5dSDimitry Andric // | \
143001095a5dSDimitry Andric // | \
143101095a5dSDimitry Andric // | Pred
143201095a5dSDimitry Andric // | /
143301095a5dSDimitry Andric // Succ
143401095a5dSDimitry Andric // In this case, we are evaluating whether to select edge -> Succ, e.g.
143501095a5dSDimitry Andric // set Succ as the layout successor of BB. Picking Succ as BB's
143601095a5dSDimitry Andric // successor breaks the CFG constraints (FIXME: define these constraints).
143701095a5dSDimitry Andric // With this layout, Pred BB
143801095a5dSDimitry Andric // is forced to be outlined, so the overall cost will be cost of the
143901095a5dSDimitry Andric // branch taken from BB to Pred, plus the cost of back taken branch
144001095a5dSDimitry Andric // from Pred to Succ, as well as the additional cost associated
144101095a5dSDimitry Andric // with the needed unconditional jump instruction from Pred To Succ.
144201095a5dSDimitry Andric
144301095a5dSDimitry Andric // The cost of the topological order layout is the taken branch cost
144401095a5dSDimitry Andric // from BB to Succ, so to make BB->Succ a viable candidate, the following
144501095a5dSDimitry Andric // must hold:
144601095a5dSDimitry Andric // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
144701095a5dSDimitry Andric // < freq(BB->Succ) * taken_branch_cost.
144801095a5dSDimitry Andric // Ignoring unconditional jump cost, we get
144901095a5dSDimitry Andric // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
145001095a5dSDimitry Andric // prob(BB->Succ) > 2 * prob(BB->Pred)
145101095a5dSDimitry Andric //
145201095a5dSDimitry Andric // When real profile data is available, we can precisely compute the
145301095a5dSDimitry Andric // probability threshold that is needed for edge BB->Succ to be considered.
145401095a5dSDimitry Andric // Without profile data, the heuristic requires the branch bias to be
145501095a5dSDimitry Andric // a lot larger to make sure the signal is very strong (e.g. 80% default).
145601095a5dSDimitry Andric // -----------------------------------------------------------------
145701095a5dSDimitry Andric // Case 2: diamond like CFG (if-then-else):
145801095a5dSDimitry Andric // S
145901095a5dSDimitry Andric // / \
146001095a5dSDimitry Andric // | \
146101095a5dSDimitry Andric // BB Pred
146201095a5dSDimitry Andric // \ /
146301095a5dSDimitry Andric // Succ
146401095a5dSDimitry Andric // ..
146501095a5dSDimitry Andric //
146601095a5dSDimitry Andric // The current block is BB and edge BB->Succ is now being evaluated.
146701095a5dSDimitry Andric // Note that edge S->BB was previously already selected because
146801095a5dSDimitry Andric // prob(S->BB) > prob(S->Pred).
146901095a5dSDimitry Andric // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
147001095a5dSDimitry Andric // choose Pred, we will have a topological ordering as shown on the left
147101095a5dSDimitry Andric // in the picture below. If we choose Succ, we have the solution as shown
147201095a5dSDimitry Andric // on the right:
147301095a5dSDimitry Andric //
147401095a5dSDimitry Andric // topo-order:
147501095a5dSDimitry Andric //
147601095a5dSDimitry Andric // S----- ---S
147701095a5dSDimitry Andric // | | | |
147801095a5dSDimitry Andric // ---BB | | BB
147901095a5dSDimitry Andric // | | | |
14807c7aba6eSDimitry Andric // | Pred-- | Succ--
148101095a5dSDimitry Andric // | | | |
14827c7aba6eSDimitry Andric // ---Succ ---Pred--
148301095a5dSDimitry Andric //
148401095a5dSDimitry Andric // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
148501095a5dSDimitry Andric // = freq(S->Pred) + freq(S->BB)
148601095a5dSDimitry Andric //
148701095a5dSDimitry Andric // If we have profile data (i.e, branch probabilities can be trusted), the
148801095a5dSDimitry Andric // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
148901095a5dSDimitry Andric // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
149001095a5dSDimitry Andric // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
149101095a5dSDimitry Andric // means the cost of topological order is greater.
149201095a5dSDimitry Andric // When profile data is not available, however, we need to be more
149301095a5dSDimitry Andric // conservative. If the branch prediction is wrong, breaking the topo-order
149401095a5dSDimitry Andric // will actually yield a layout with large cost. For this reason, we need
149501095a5dSDimitry Andric // strong biased branch at block S with Prob(S->BB) in order to select
149601095a5dSDimitry Andric // BB->Succ. This is equivalent to looking the CFG backward with backward
149701095a5dSDimitry Andric // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
149801095a5dSDimitry Andric // profile data).
1499b915e9e0SDimitry Andric // --------------------------------------------------------------------------
1500b915e9e0SDimitry Andric // Case 3: forked diamond
1501b915e9e0SDimitry Andric // S
1502b915e9e0SDimitry Andric // / \
1503b915e9e0SDimitry Andric // / \
1504b915e9e0SDimitry Andric // BB Pred
1505b915e9e0SDimitry Andric // | \ / |
1506b915e9e0SDimitry Andric // | \ / |
1507b915e9e0SDimitry Andric // | X |
1508b915e9e0SDimitry Andric // | / \ |
1509b915e9e0SDimitry Andric // | / \ |
1510b915e9e0SDimitry Andric // S1 S2
1511b915e9e0SDimitry Andric //
1512b915e9e0SDimitry Andric // The current block is BB and edge BB->S1 is now being evaluated.
1513b915e9e0SDimitry Andric // As above S->BB was already selected because
1514b915e9e0SDimitry Andric // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1515b915e9e0SDimitry Andric //
1516b915e9e0SDimitry Andric // topo-order:
1517b915e9e0SDimitry Andric //
1518b915e9e0SDimitry Andric // S-------| ---S
1519b915e9e0SDimitry Andric // | | | |
1520b915e9e0SDimitry Andric // ---BB | | BB
1521b915e9e0SDimitry Andric // | | | |
1522b915e9e0SDimitry Andric // | Pred----| | S1----
1523b915e9e0SDimitry Andric // | | | |
1524b915e9e0SDimitry Andric // --(S1 or S2) ---Pred--
152571d5a254SDimitry Andric // |
152671d5a254SDimitry Andric // S2
1527b915e9e0SDimitry Andric //
1528b915e9e0SDimitry Andric // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1529b915e9e0SDimitry Andric // + min(freq(Pred->S1), freq(Pred->S2))
1530b915e9e0SDimitry Andric // Non-topo-order cost:
1531b915e9e0SDimitry Andric // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1532b915e9e0SDimitry Andric // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1533b915e9e0SDimitry Andric // is 0. Then the non topo layout is better when
1534b915e9e0SDimitry Andric // freq(S->Pred) < freq(BB->S1).
1535b915e9e0SDimitry Andric // This is exactly what is checked below.
1536b915e9e0SDimitry Andric // Note there are other shapes that apply (Pred may not be a single block,
1537b915e9e0SDimitry Andric // but they all fit this general pattern.)
153801095a5dSDimitry Andric BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
153901095a5dSDimitry Andric
154001095a5dSDimitry Andric // Make sure that a hot successor doesn't have a globally more
154101095a5dSDimitry Andric // important predecessor.
154201095a5dSDimitry Andric BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
154301095a5dSDimitry Andric bool BadCFGConflict = false;
154401095a5dSDimitry Andric
154501095a5dSDimitry Andric for (MachineBasicBlock *Pred : Succ->predecessors()) {
1546706b4fc4SDimitry Andric BlockChain *PredChain = BlockToChain[Pred];
1547706b4fc4SDimitry Andric if (Pred == Succ || PredChain == &SuccChain ||
154801095a5dSDimitry Andric (BlockFilter && !BlockFilter->count(Pred)) ||
1549706b4fc4SDimitry Andric PredChain == &Chain || Pred != *std::prev(PredChain->end()) ||
155071d5a254SDimitry Andric // This check is redundant except for look ahead. This function is
155171d5a254SDimitry Andric // called for lookahead by isProfitableToTailDup when BB hasn't been
155271d5a254SDimitry Andric // placed yet.
155371d5a254SDimitry Andric (Pred == BB))
155401095a5dSDimitry Andric continue;
1555b915e9e0SDimitry Andric // Do backward checking.
1556b915e9e0SDimitry Andric // For all cases above, we need a backward checking to filter out edges that
155771d5a254SDimitry Andric // are not 'strongly' biased.
155801095a5dSDimitry Andric // BB Pred
155901095a5dSDimitry Andric // \ /
156001095a5dSDimitry Andric // Succ
156101095a5dSDimitry Andric // We select edge BB->Succ if
156201095a5dSDimitry Andric // freq(BB->Succ) > freq(Succ) * HotProb
156301095a5dSDimitry Andric // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
156401095a5dSDimitry Andric // HotProb
156501095a5dSDimitry Andric // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
1566b915e9e0SDimitry Andric // Case 1 is covered too, because the first equation reduces to:
1567b915e9e0SDimitry Andric // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
156801095a5dSDimitry Andric BlockFrequency PredEdgeFreq =
156901095a5dSDimitry Andric MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
157001095a5dSDimitry Andric if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
157101095a5dSDimitry Andric BadCFGConflict = true;
157201095a5dSDimitry Andric break;
157301095a5dSDimitry Andric }
157401095a5dSDimitry Andric }
157501095a5dSDimitry Andric
157601095a5dSDimitry Andric if (BadCFGConflict) {
1577eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> "
1578eb11fae6SDimitry Andric << SuccProb << " (prob) (non-cold CFG conflict)\n");
157901095a5dSDimitry Andric return true;
158001095a5dSDimitry Andric }
158101095a5dSDimitry Andric
158201095a5dSDimitry Andric return false;
158301095a5dSDimitry Andric }
158401095a5dSDimitry Andric
1585eb11fae6SDimitry Andric /// Select the best successor for a block.
158663faed5bSDimitry Andric ///
158763faed5bSDimitry Andric /// This looks across all successors of a particular block and attempts to
158863faed5bSDimitry Andric /// select the "best" one to be the layout successor. It only considers direct
158963faed5bSDimitry Andric /// successors which also pass the block filter. It will attempt to avoid
159063faed5bSDimitry Andric /// breaking CFG structure, but cave and break such structures in the case of
159163faed5bSDimitry Andric /// very hot successor edges.
159263faed5bSDimitry Andric ///
159371d5a254SDimitry Andric /// \returns The best successor block found, or null if none are viable, along
159471d5a254SDimitry Andric /// with a boolean indicating if tail duplication is necessary.
159571d5a254SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult
selectBestSuccessor(const MachineBasicBlock * BB,const BlockChain & Chain,const BlockFilterSet * BlockFilter)159671d5a254SDimitry Andric MachineBlockPlacement::selectBestSuccessor(
159771d5a254SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain,
159863faed5bSDimitry Andric const BlockFilterSet *BlockFilter) {
159901095a5dSDimitry Andric const BranchProbability HotProb(StaticLikelyProb, 100);
160063faed5bSDimitry Andric
160171d5a254SDimitry Andric BlockAndTailDupResult BestSucc = { nullptr, false };
1602dd58ef01SDimitry Andric auto BestProb = BranchProbability::getZero();
1603dd58ef01SDimitry Andric
1604dd58ef01SDimitry Andric SmallVector<MachineBasicBlock *, 4> Successors;
160501095a5dSDimitry Andric auto AdjustedSumProb =
160601095a5dSDimitry Andric collectViableSuccessors(BB, Chain, BlockFilter, Successors);
160763faed5bSDimitry Andric
1608eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB)
1609eb11fae6SDimitry Andric << "\n");
161071d5a254SDimitry Andric
161171d5a254SDimitry Andric // if we already precomputed the best successor for BB, return that if still
161271d5a254SDimitry Andric // applicable.
161371d5a254SDimitry Andric auto FoundEdge = ComputedEdges.find(BB);
161471d5a254SDimitry Andric if (FoundEdge != ComputedEdges.end()) {
161571d5a254SDimitry Andric MachineBasicBlock *Succ = FoundEdge->second.BB;
161671d5a254SDimitry Andric ComputedEdges.erase(FoundEdge);
161771d5a254SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ];
161871d5a254SDimitry Andric if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
161971d5a254SDimitry Andric SuccChain != &Chain && Succ == *SuccChain->begin())
162071d5a254SDimitry Andric return FoundEdge->second;
162171d5a254SDimitry Andric }
162271d5a254SDimitry Andric
162371d5a254SDimitry Andric // if BB is part of a trellis, Use the trellis to determine the optimal
162471d5a254SDimitry Andric // fallthrough edges
162571d5a254SDimitry Andric if (isTrellis(BB, Successors, Chain, BlockFilter))
162671d5a254SDimitry Andric return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
162771d5a254SDimitry Andric BlockFilter);
162871d5a254SDimitry Andric
162971d5a254SDimitry Andric // For blocks with CFG violations, we may be able to lay them out anyway with
163071d5a254SDimitry Andric // tail-duplication. We keep this vector so we can perform the probability
163171d5a254SDimitry Andric // calculations the minimum number of times.
1632cfca06d7SDimitry Andric SmallVector<std::pair<BranchProbability, MachineBasicBlock *>, 4>
163371d5a254SDimitry Andric DupCandidates;
1634dd58ef01SDimitry Andric for (MachineBasicBlock *Succ : Successors) {
1635dd58ef01SDimitry Andric auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
163601095a5dSDimitry Andric BranchProbability SuccProb =
163701095a5dSDimitry Andric getAdjustedProbability(RealSuccProb, AdjustedSumProb);
163863faed5bSDimitry Andric
163901095a5dSDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ];
164001095a5dSDimitry Andric // Skip the edge \c BB->Succ if block \c Succ has a better layout
164101095a5dSDimitry Andric // predecessor that yields lower global cost.
164201095a5dSDimitry Andric if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
164371d5a254SDimitry Andric Chain, BlockFilter)) {
164471d5a254SDimitry Andric // If tail duplication would make Succ profitable, place it.
1645eb11fae6SDimitry Andric if (allowTailDupPlacement() && shouldTailDuplicate(Succ))
1646cfca06d7SDimitry Andric DupCandidates.emplace_back(SuccProb, Succ);
164701095a5dSDimitry Andric continue;
164871d5a254SDimitry Andric }
164901095a5dSDimitry Andric
1650eb11fae6SDimitry Andric LLVM_DEBUG(
1651eb11fae6SDimitry Andric dbgs() << " Candidate: " << getBlockName(Succ)
1652eb11fae6SDimitry Andric << ", probability: " << SuccProb
165301095a5dSDimitry Andric << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
165463faed5bSDimitry Andric << "\n");
1655b915e9e0SDimitry Andric
165671d5a254SDimitry Andric if (BestSucc.BB && BestProb >= SuccProb) {
1657eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n");
165863faed5bSDimitry Andric continue;
1659b915e9e0SDimitry Andric }
1660b915e9e0SDimitry Andric
1661eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Setting it as best candidate\n");
166271d5a254SDimitry Andric BestSucc.BB = Succ;
1663dd58ef01SDimitry Andric BestProb = SuccProb;
166463faed5bSDimitry Andric }
166571d5a254SDimitry Andric // Handle the tail duplication candidates in order of decreasing probability.
166671d5a254SDimitry Andric // Stop at the first one that is profitable. Also stop if they are less
166771d5a254SDimitry Andric // profitable than BestSucc. Position is important because we preserve it and
166871d5a254SDimitry Andric // prefer first best match. Here we aren't comparing in order, so we capture
166971d5a254SDimitry Andric // the position instead.
1670e6d15924SDimitry Andric llvm::stable_sort(DupCandidates,
1671e6d15924SDimitry Andric [](std::tuple<BranchProbability, MachineBasicBlock *> L,
1672e6d15924SDimitry Andric std::tuple<BranchProbability, MachineBasicBlock *> R) {
1673e6d15924SDimitry Andric return std::get<0>(L) > std::get<0>(R);
1674e6d15924SDimitry Andric });
167571d5a254SDimitry Andric for (auto &Tup : DupCandidates) {
167671d5a254SDimitry Andric BranchProbability DupProb;
167771d5a254SDimitry Andric MachineBasicBlock *Succ;
167871d5a254SDimitry Andric std::tie(DupProb, Succ) = Tup;
167971d5a254SDimitry Andric if (DupProb < BestProb)
168071d5a254SDimitry Andric break;
168171d5a254SDimitry Andric if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
168271d5a254SDimitry Andric && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
1683eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ)
1684eb11fae6SDimitry Andric << ", probability: " << DupProb
168571d5a254SDimitry Andric << " (Tail Duplicate)\n");
168671d5a254SDimitry Andric BestSucc.BB = Succ;
168771d5a254SDimitry Andric BestSucc.ShouldTailDup = true;
168871d5a254SDimitry Andric break;
168971d5a254SDimitry Andric }
169071d5a254SDimitry Andric }
169171d5a254SDimitry Andric
169271d5a254SDimitry Andric if (BestSucc.BB)
1693eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
1694b915e9e0SDimitry Andric
169563faed5bSDimitry Andric return BestSucc;
169663faed5bSDimitry Andric }
169763faed5bSDimitry Andric
1698eb11fae6SDimitry Andric /// Select the best block from a worklist.
169963faed5bSDimitry Andric ///
170063faed5bSDimitry Andric /// This looks through the provided worklist as a list of candidate basic
170163faed5bSDimitry Andric /// blocks and select the most profitable one to place. The definition of
170263faed5bSDimitry Andric /// profitable only really makes sense in the context of a loop. This returns
170363faed5bSDimitry Andric /// the most frequently visited block in the worklist, which in the case of
170463faed5bSDimitry Andric /// a loop, is the one most desirable to be physically close to the rest of the
170501095a5dSDimitry Andric /// loop body in order to improve i-cache behavior.
170663faed5bSDimitry Andric ///
170763faed5bSDimitry Andric /// \returns The best block found, or null if none are viable.
selectBestCandidateBlock(const BlockChain & Chain,SmallVectorImpl<MachineBasicBlock * > & WorkList)170863faed5bSDimitry Andric MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
170971d5a254SDimitry Andric const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
171063faed5bSDimitry Andric // Once we need to walk the worklist looking for a candidate, cleanup the
171163faed5bSDimitry Andric // worklist of already placed entries.
171263faed5bSDimitry Andric // FIXME: If this shows up on profiles, it could be folded (at the cost of
171363faed5bSDimitry Andric // some code complexity) into the loop below.
1714b60736ecSDimitry Andric llvm::erase_if(WorkList, [&](MachineBasicBlock *BB) {
17155ca98fd9SDimitry Andric return BlockToChain.lookup(BB) == &Chain;
1716b60736ecSDimitry Andric });
171763faed5bSDimitry Andric
171801095a5dSDimitry Andric if (WorkList.empty())
171901095a5dSDimitry Andric return nullptr;
172001095a5dSDimitry Andric
172101095a5dSDimitry Andric bool IsEHPad = WorkList[0]->isEHPad();
172201095a5dSDimitry Andric
17235ca98fd9SDimitry Andric MachineBasicBlock *BestBlock = nullptr;
172463faed5bSDimitry Andric BlockFrequency BestFreq;
17255a5ac124SDimitry Andric for (MachineBasicBlock *MBB : WorkList) {
1726b5630dbaSDimitry Andric assert(MBB->isEHPad() == IsEHPad &&
1727b5630dbaSDimitry Andric "EHPad mismatch between block and work list.");
172801095a5dSDimitry Andric
17295a5ac124SDimitry Andric BlockChain &SuccChain = *BlockToChain[MBB];
173001095a5dSDimitry Andric if (&SuccChain == &Chain)
173163faed5bSDimitry Andric continue;
173201095a5dSDimitry Andric
1733b5630dbaSDimitry Andric assert(SuccChain.UnscheduledPredecessors == 0 &&
1734b5630dbaSDimitry Andric "Found CFG-violating block");
173563faed5bSDimitry Andric
17365a5ac124SDimitry Andric BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1737b1c73532SDimitry Andric LLVM_DEBUG(dbgs() << " " << getBlockName(MBB) << " -> "
1738b1c73532SDimitry Andric << printBlockFreq(MBFI->getMBFI(), CandidateFreq)
1739b1c73532SDimitry Andric << " (freq)\n");
174001095a5dSDimitry Andric
174101095a5dSDimitry Andric // For ehpad, we layout the least probable first as to avoid jumping back
174201095a5dSDimitry Andric // from least probable landingpads to more probable ones.
174301095a5dSDimitry Andric //
174401095a5dSDimitry Andric // FIXME: Using probability is probably (!) not the best way to achieve
174501095a5dSDimitry Andric // this. We should probably have a more principled approach to layout
174601095a5dSDimitry Andric // cleanup code.
174701095a5dSDimitry Andric //
174801095a5dSDimitry Andric // The goal is to get:
174901095a5dSDimitry Andric //
175001095a5dSDimitry Andric // +--------------------------+
175101095a5dSDimitry Andric // | V
175201095a5dSDimitry Andric // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
175301095a5dSDimitry Andric //
175401095a5dSDimitry Andric // Rather than:
175501095a5dSDimitry Andric //
175601095a5dSDimitry Andric // +-------------------------------------+
175701095a5dSDimitry Andric // V |
175801095a5dSDimitry Andric // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
175901095a5dSDimitry Andric if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
176063faed5bSDimitry Andric continue;
176101095a5dSDimitry Andric
17625a5ac124SDimitry Andric BestBlock = MBB;
176363faed5bSDimitry Andric BestFreq = CandidateFreq;
176463faed5bSDimitry Andric }
176501095a5dSDimitry Andric
176663faed5bSDimitry Andric return BestBlock;
176763faed5bSDimitry Andric }
176863faed5bSDimitry Andric
1769ac9a064cSDimitry Andric /// Retrieve the first unplaced basic block in the entire function.
177063faed5bSDimitry Andric ///
177163faed5bSDimitry Andric /// This routine is called when we are unable to use the CFG to walk through
177263faed5bSDimitry Andric /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
177363faed5bSDimitry Andric /// We walk through the function's blocks in order, starting from the
177463faed5bSDimitry Andric /// LastUnplacedBlockIt. We update this iterator on each call to avoid
177563faed5bSDimitry Andric /// re-scanning the entire sequence on repeated calls to this routine.
getFirstUnplacedBlock(const BlockChain & PlacedChain,MachineFunction::iterator & PrevUnplacedBlockIt)177663faed5bSDimitry Andric MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
177701095a5dSDimitry Andric const BlockChain &PlacedChain,
1778ac9a064cSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt) {
1779ac9a064cSDimitry Andric
178001095a5dSDimitry Andric for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
178163faed5bSDimitry Andric ++I) {
1782dd58ef01SDimitry Andric if (BlockToChain[&*I] != &PlacedChain) {
178363faed5bSDimitry Andric PrevUnplacedBlockIt = I;
178463faed5bSDimitry Andric // Now select the head of the chain to which the unplaced block belongs
178563faed5bSDimitry Andric // as the block to place. This will force the entire chain to be placed,
178663faed5bSDimitry Andric // and satisfies the requirements of merging chains.
1787dd58ef01SDimitry Andric return *BlockToChain[&*I]->begin();
178863faed5bSDimitry Andric }
178963faed5bSDimitry Andric }
17905ca98fd9SDimitry Andric return nullptr;
179163faed5bSDimitry Andric }
179263faed5bSDimitry Andric
1793ac9a064cSDimitry Andric /// Retrieve the first unplaced basic block among the blocks in BlockFilter.
1794ac9a064cSDimitry Andric ///
1795ac9a064cSDimitry Andric /// This is similar to getFirstUnplacedBlock for the entire function, but since
1796ac9a064cSDimitry Andric /// the size of BlockFilter is typically far less than the number of blocks in
1797ac9a064cSDimitry Andric /// the entire function, iterating through the BlockFilter is more efficient.
1798ac9a064cSDimitry Andric /// When processing the entire funciton, using the version without BlockFilter
1799ac9a064cSDimitry Andric /// has a complexity of #(loops in function) * #(blocks in function), while this
1800ac9a064cSDimitry Andric /// version has a complexity of sum(#(loops in block) foreach block in function)
1801ac9a064cSDimitry Andric /// which is always smaller. For long function mostly sequential in structure,
1802ac9a064cSDimitry Andric /// the complexity is amortized to 1 * #(blocks in function).
getFirstUnplacedBlock(const BlockChain & PlacedChain,BlockFilterSet::iterator & PrevUnplacedBlockInFilterIt,const BlockFilterSet * BlockFilter)1803ac9a064cSDimitry Andric MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1804ac9a064cSDimitry Andric const BlockChain &PlacedChain,
1805ac9a064cSDimitry Andric BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
1806ac9a064cSDimitry Andric const BlockFilterSet *BlockFilter) {
1807ac9a064cSDimitry Andric assert(BlockFilter);
1808ac9a064cSDimitry Andric for (; PrevUnplacedBlockInFilterIt != BlockFilter->end();
1809ac9a064cSDimitry Andric ++PrevUnplacedBlockInFilterIt) {
1810ac9a064cSDimitry Andric BlockChain *C = BlockToChain[*PrevUnplacedBlockInFilterIt];
1811ac9a064cSDimitry Andric if (C != &PlacedChain) {
1812ac9a064cSDimitry Andric return *C->begin();
1813ac9a064cSDimitry Andric }
1814ac9a064cSDimitry Andric }
1815ac9a064cSDimitry Andric return nullptr;
1816ac9a064cSDimitry Andric }
1817ac9a064cSDimitry Andric
fillWorkLists(const MachineBasicBlock * MBB,SmallPtrSetImpl<BlockChain * > & UpdatedPreds,const BlockFilterSet * BlockFilter=nullptr)181801095a5dSDimitry Andric void MachineBlockPlacement::fillWorkLists(
181971d5a254SDimitry Andric const MachineBasicBlock *MBB,
182001095a5dSDimitry Andric SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
182101095a5dSDimitry Andric const BlockFilterSet *BlockFilter = nullptr) {
182201095a5dSDimitry Andric BlockChain &Chain = *BlockToChain[MBB];
182301095a5dSDimitry Andric if (!UpdatedPreds.insert(&Chain).second)
182401095a5dSDimitry Andric return;
182501095a5dSDimitry Andric
1826b5630dbaSDimitry Andric assert(
1827b5630dbaSDimitry Andric Chain.UnscheduledPredecessors == 0 &&
1828b5630dbaSDimitry Andric "Attempting to place block with unscheduled predecessors in worklist.");
182901095a5dSDimitry Andric for (MachineBasicBlock *ChainBB : Chain) {
1830b5630dbaSDimitry Andric assert(BlockToChain[ChainBB] == &Chain &&
1831b5630dbaSDimitry Andric "Block in chain doesn't match BlockToChain map.");
183201095a5dSDimitry Andric for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
183301095a5dSDimitry Andric if (BlockFilter && !BlockFilter->count(Pred))
183401095a5dSDimitry Andric continue;
183501095a5dSDimitry Andric if (BlockToChain[Pred] == &Chain)
183601095a5dSDimitry Andric continue;
183701095a5dSDimitry Andric ++Chain.UnscheduledPredecessors;
183801095a5dSDimitry Andric }
183901095a5dSDimitry Andric }
184001095a5dSDimitry Andric
184101095a5dSDimitry Andric if (Chain.UnscheduledPredecessors != 0)
184201095a5dSDimitry Andric return;
184301095a5dSDimitry Andric
184471d5a254SDimitry Andric MachineBasicBlock *BB = *Chain.begin();
184571d5a254SDimitry Andric if (BB->isEHPad())
184671d5a254SDimitry Andric EHPadWorkList.push_back(BB);
184701095a5dSDimitry Andric else
184871d5a254SDimitry Andric BlockWorkList.push_back(BB);
184901095a5dSDimitry Andric }
185001095a5dSDimitry Andric
buildChain(const MachineBasicBlock * HeadBB,BlockChain & Chain,BlockFilterSet * BlockFilter)185163faed5bSDimitry Andric void MachineBlockPlacement::buildChain(
185271d5a254SDimitry Andric const MachineBasicBlock *HeadBB, BlockChain &Chain,
1853b915e9e0SDimitry Andric BlockFilterSet *BlockFilter) {
185471d5a254SDimitry Andric assert(HeadBB && "BB must not be null.\n");
185571d5a254SDimitry Andric assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
185601095a5dSDimitry Andric MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
1857ac9a064cSDimitry Andric BlockFilterSet::iterator PrevUnplacedBlockInFilterIt;
1858ac9a064cSDimitry Andric if (BlockFilter)
1859ac9a064cSDimitry Andric PrevUnplacedBlockInFilterIt = BlockFilter->begin();
186063faed5bSDimitry Andric
186171d5a254SDimitry Andric const MachineBasicBlock *LoopHeaderBB = HeadBB;
186201095a5dSDimitry Andric markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
186371d5a254SDimitry Andric MachineBasicBlock *BB = *std::prev(Chain.end());
1864044eb2f6SDimitry Andric while (true) {
186501095a5dSDimitry Andric assert(BB && "null block found at end of chain in loop.");
186601095a5dSDimitry Andric assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
186701095a5dSDimitry Andric assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
186801095a5dSDimitry Andric
186963faed5bSDimitry Andric
187063faed5bSDimitry Andric // Look for the best viable successor if there is one to place immediately
187163faed5bSDimitry Andric // after this block.
187271d5a254SDimitry Andric auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
187371d5a254SDimitry Andric MachineBasicBlock* BestSucc = Result.BB;
187471d5a254SDimitry Andric bool ShouldTailDup = Result.ShouldTailDup;
1875eb11fae6SDimitry Andric if (allowTailDupPlacement())
1876706b4fc4SDimitry Andric ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(BB, BestSucc,
1877706b4fc4SDimitry Andric Chain,
1878706b4fc4SDimitry Andric BlockFilter));
187963faed5bSDimitry Andric
188063faed5bSDimitry Andric // If an immediate successor isn't available, look for the best viable
188163faed5bSDimitry Andric // block among those we've identified as not violating the loop's CFG at
188263faed5bSDimitry Andric // this point. This won't be a fallthrough, but it will increase locality.
188363faed5bSDimitry Andric if (!BestSucc)
188401095a5dSDimitry Andric BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
188501095a5dSDimitry Andric if (!BestSucc)
188601095a5dSDimitry Andric BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
188763faed5bSDimitry Andric
188863faed5bSDimitry Andric if (!BestSucc) {
1889ac9a064cSDimitry Andric if (BlockFilter)
1890ac9a064cSDimitry Andric BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockInFilterIt,
1891ac9a064cSDimitry Andric BlockFilter);
1892ac9a064cSDimitry Andric else
1893ac9a064cSDimitry Andric BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt);
189463faed5bSDimitry Andric if (!BestSucc)
189563faed5bSDimitry Andric break;
189663faed5bSDimitry Andric
1897eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
189863faed5bSDimitry Andric "layout successor until the CFG reduces\n");
189963faed5bSDimitry Andric }
190063faed5bSDimitry Andric
1901b915e9e0SDimitry Andric // Placement may have changed tail duplication opportunities.
1902b915e9e0SDimitry Andric // Check for that now.
1903eb11fae6SDimitry Andric if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
1904cfca06d7SDimitry Andric repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1905ac9a064cSDimitry Andric BlockFilter, PrevUnplacedBlockIt,
1906ac9a064cSDimitry Andric PrevUnplacedBlockInFilterIt);
1907cfca06d7SDimitry Andric // If the chosen successor was duplicated into BB, don't bother laying
1908cfca06d7SDimitry Andric // it out, just go round the loop again with BB as the chain end.
1909cfca06d7SDimitry Andric if (!BB->isSuccessor(BestSucc))
1910b915e9e0SDimitry Andric continue;
1911b915e9e0SDimitry Andric }
1912b915e9e0SDimitry Andric
191363faed5bSDimitry Andric // Place this block, updating the datastructures to reflect its placement.
191463faed5bSDimitry Andric BlockChain &SuccChain = *BlockToChain[BestSucc];
191501095a5dSDimitry Andric // Zero out UnscheduledPredecessors for the successor we're about to merge in case
191663faed5bSDimitry Andric // we selected a successor that didn't fit naturally into the CFG.
191701095a5dSDimitry Andric SuccChain.UnscheduledPredecessors = 0;
1918eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
191901095a5dSDimitry Andric << getBlockName(BestSucc) << "\n");
192001095a5dSDimitry Andric markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
192163faed5bSDimitry Andric Chain.merge(BestSucc, &SuccChain);
19225ca98fd9SDimitry Andric BB = *std::prev(Chain.end());
192363faed5bSDimitry Andric }
192463faed5bSDimitry Andric
1925eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Finished forming chain for header block "
192601095a5dSDimitry Andric << getBlockName(*Chain.begin()) << "\n");
192763faed5bSDimitry Andric }
192863faed5bSDimitry Andric
1929e6d15924SDimitry Andric // If bottom of block BB has only one successor OldTop, in most cases it is
1930e6d15924SDimitry Andric // profitable to move it before OldTop, except the following case:
1931e6d15924SDimitry Andric //
1932e6d15924SDimitry Andric // -->OldTop<-
1933e6d15924SDimitry Andric // | . |
1934e6d15924SDimitry Andric // | . |
1935e6d15924SDimitry Andric // | . |
1936e6d15924SDimitry Andric // ---Pred |
1937e6d15924SDimitry Andric // | |
1938e6d15924SDimitry Andric // BB-----
1939e6d15924SDimitry Andric //
1940e6d15924SDimitry Andric // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't
1941e6d15924SDimitry Andric // layout the other successor below it, so it can't reduce taken branch.
1942e6d15924SDimitry Andric // In this case we keep its original layout.
1943e6d15924SDimitry Andric bool
canMoveBottomBlockToTop(const MachineBasicBlock * BottomBlock,const MachineBasicBlock * OldTop)1944e6d15924SDimitry Andric MachineBlockPlacement::canMoveBottomBlockToTop(
1945e6d15924SDimitry Andric const MachineBasicBlock *BottomBlock,
1946e6d15924SDimitry Andric const MachineBasicBlock *OldTop) {
1947e6d15924SDimitry Andric if (BottomBlock->pred_size() != 1)
1948e6d15924SDimitry Andric return true;
1949e6d15924SDimitry Andric MachineBasicBlock *Pred = *BottomBlock->pred_begin();
1950e6d15924SDimitry Andric if (Pred->succ_size() != 2)
1951e6d15924SDimitry Andric return true;
1952b915e9e0SDimitry Andric
1953e6d15924SDimitry Andric MachineBasicBlock *OtherBB = *Pred->succ_begin();
1954e6d15924SDimitry Andric if (OtherBB == BottomBlock)
1955e6d15924SDimitry Andric OtherBB = *Pred->succ_rbegin();
1956e6d15924SDimitry Andric if (OtherBB == OldTop)
1957e6d15924SDimitry Andric return false;
1958e6d15924SDimitry Andric
1959e6d15924SDimitry Andric return true;
1960e6d15924SDimitry Andric }
1961e6d15924SDimitry Andric
1962e6d15924SDimitry Andric // Find out the possible fall through frequence to the top of a loop.
1963e6d15924SDimitry Andric BlockFrequency
TopFallThroughFreq(const MachineBasicBlock * Top,const BlockFilterSet & LoopBlockSet)1964e6d15924SDimitry Andric MachineBlockPlacement::TopFallThroughFreq(
1965e6d15924SDimitry Andric const MachineBasicBlock *Top,
1966e6d15924SDimitry Andric const BlockFilterSet &LoopBlockSet) {
1967b1c73532SDimitry Andric BlockFrequency MaxFreq = BlockFrequency(0);
1968e6d15924SDimitry Andric for (MachineBasicBlock *Pred : Top->predecessors()) {
1969e6d15924SDimitry Andric BlockChain *PredChain = BlockToChain[Pred];
1970e6d15924SDimitry Andric if (!LoopBlockSet.count(Pred) &&
1971e6d15924SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) {
1972e6d15924SDimitry Andric // Found a Pred block can be placed before Top.
1973e6d15924SDimitry Andric // Check if Top is the best successor of Pred.
1974e6d15924SDimitry Andric auto TopProb = MBPI->getEdgeProbability(Pred, Top);
1975e6d15924SDimitry Andric bool TopOK = true;
1976e6d15924SDimitry Andric for (MachineBasicBlock *Succ : Pred->successors()) {
1977e6d15924SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
1978e6d15924SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ];
1979e6d15924SDimitry Andric // Check if Succ can be placed after Pred.
1980e6d15924SDimitry Andric // Succ should not be in any chain, or it is the head of some chain.
1981e6d15924SDimitry Andric if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) &&
1982e6d15924SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) {
1983e6d15924SDimitry Andric TopOK = false;
1984e6d15924SDimitry Andric break;
1985e6d15924SDimitry Andric }
1986e6d15924SDimitry Andric }
1987e6d15924SDimitry Andric if (TopOK) {
1988e6d15924SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) *
1989e6d15924SDimitry Andric MBPI->getEdgeProbability(Pred, Top);
1990e6d15924SDimitry Andric if (EdgeFreq > MaxFreq)
1991e6d15924SDimitry Andric MaxFreq = EdgeFreq;
1992e6d15924SDimitry Andric }
1993e6d15924SDimitry Andric }
1994e6d15924SDimitry Andric }
1995e6d15924SDimitry Andric return MaxFreq;
1996e6d15924SDimitry Andric }
1997e6d15924SDimitry Andric
1998e6d15924SDimitry Andric // Compute the fall through gains when move NewTop before OldTop.
1999e6d15924SDimitry Andric //
2000e6d15924SDimitry Andric // In following diagram, edges marked as "-" are reduced fallthrough, edges
2001e6d15924SDimitry Andric // marked as "+" are increased fallthrough, this function computes
2002e6d15924SDimitry Andric //
2003e6d15924SDimitry Andric // SUM(increased fallthrough) - SUM(decreased fallthrough)
2004e6d15924SDimitry Andric //
2005e6d15924SDimitry Andric // |
2006e6d15924SDimitry Andric // | -
2007e6d15924SDimitry Andric // V
2008e6d15924SDimitry Andric // --->OldTop
2009e6d15924SDimitry Andric // | .
2010e6d15924SDimitry Andric // | .
2011e6d15924SDimitry Andric // +| . +
2012e6d15924SDimitry Andric // | Pred --->
2013e6d15924SDimitry Andric // | |-
2014e6d15924SDimitry Andric // | V
2015e6d15924SDimitry Andric // --- NewTop <---
2016e6d15924SDimitry Andric // |-
2017e6d15924SDimitry Andric // V
2018e6d15924SDimitry Andric //
2019e6d15924SDimitry Andric BlockFrequency
FallThroughGains(const MachineBasicBlock * NewTop,const MachineBasicBlock * OldTop,const MachineBasicBlock * ExitBB,const BlockFilterSet & LoopBlockSet)2020e6d15924SDimitry Andric MachineBlockPlacement::FallThroughGains(
2021e6d15924SDimitry Andric const MachineBasicBlock *NewTop,
2022e6d15924SDimitry Andric const MachineBasicBlock *OldTop,
2023e6d15924SDimitry Andric const MachineBasicBlock *ExitBB,
2024e6d15924SDimitry Andric const BlockFilterSet &LoopBlockSet) {
2025e6d15924SDimitry Andric BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet);
2026b1c73532SDimitry Andric BlockFrequency FallThrough2Exit = BlockFrequency(0);
2027e6d15924SDimitry Andric if (ExitBB)
2028e6d15924SDimitry Andric FallThrough2Exit = MBFI->getBlockFreq(NewTop) *
2029e6d15924SDimitry Andric MBPI->getEdgeProbability(NewTop, ExitBB);
2030e6d15924SDimitry Andric BlockFrequency BackEdgeFreq = MBFI->getBlockFreq(NewTop) *
2031e6d15924SDimitry Andric MBPI->getEdgeProbability(NewTop, OldTop);
2032e6d15924SDimitry Andric
2033e6d15924SDimitry Andric // Find the best Pred of NewTop.
2034e6d15924SDimitry Andric MachineBasicBlock *BestPred = nullptr;
2035b1c73532SDimitry Andric BlockFrequency FallThroughFromPred = BlockFrequency(0);
2036e6d15924SDimitry Andric for (MachineBasicBlock *Pred : NewTop->predecessors()) {
2037e6d15924SDimitry Andric if (!LoopBlockSet.count(Pred))
2038e6d15924SDimitry Andric continue;
2039e6d15924SDimitry Andric BlockChain *PredChain = BlockToChain[Pred];
2040e6d15924SDimitry Andric if (!PredChain || Pred == *std::prev(PredChain->end())) {
2041b1c73532SDimitry Andric BlockFrequency EdgeFreq =
2042b1c73532SDimitry Andric MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, NewTop);
2043e6d15924SDimitry Andric if (EdgeFreq > FallThroughFromPred) {
2044e6d15924SDimitry Andric FallThroughFromPred = EdgeFreq;
2045e6d15924SDimitry Andric BestPred = Pred;
2046e6d15924SDimitry Andric }
2047e6d15924SDimitry Andric }
2048e6d15924SDimitry Andric }
2049e6d15924SDimitry Andric
2050e6d15924SDimitry Andric // If NewTop is not placed after Pred, another successor can be placed
2051e6d15924SDimitry Andric // after Pred.
2052b1c73532SDimitry Andric BlockFrequency NewFreq = BlockFrequency(0);
2053e6d15924SDimitry Andric if (BestPred) {
2054e6d15924SDimitry Andric for (MachineBasicBlock *Succ : BestPred->successors()) {
2055e6d15924SDimitry Andric if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ))
2056e6d15924SDimitry Andric continue;
20577fa27ce4SDimitry Andric if (ComputedEdges.contains(Succ))
2058e6d15924SDimitry Andric continue;
2059e6d15924SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ];
2060e6d15924SDimitry Andric if ((SuccChain && (Succ != *SuccChain->begin())) ||
2061e6d15924SDimitry Andric (SuccChain == BlockToChain[BestPred]))
2062e6d15924SDimitry Andric continue;
2063e6d15924SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) *
2064e6d15924SDimitry Andric MBPI->getEdgeProbability(BestPred, Succ);
2065e6d15924SDimitry Andric if (EdgeFreq > NewFreq)
2066e6d15924SDimitry Andric NewFreq = EdgeFreq;
2067e6d15924SDimitry Andric }
2068e6d15924SDimitry Andric BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) *
2069e6d15924SDimitry Andric MBPI->getEdgeProbability(BestPred, NewTop);
2070e6d15924SDimitry Andric if (NewFreq > OrigEdgeFreq) {
2071e6d15924SDimitry Andric // If NewTop is not the best successor of Pred, then Pred doesn't
2072e6d15924SDimitry Andric // fallthrough to NewTop. So there is no FallThroughFromPred and
2073e6d15924SDimitry Andric // NewFreq.
2074b1c73532SDimitry Andric NewFreq = BlockFrequency(0);
2075b1c73532SDimitry Andric FallThroughFromPred = BlockFrequency(0);
2076e6d15924SDimitry Andric }
2077e6d15924SDimitry Andric }
2078e6d15924SDimitry Andric
2079b1c73532SDimitry Andric BlockFrequency Result = BlockFrequency(0);
2080e6d15924SDimitry Andric BlockFrequency Gains = BackEdgeFreq + NewFreq;
2081b1c73532SDimitry Andric BlockFrequency Lost =
2082b1c73532SDimitry Andric FallThrough2Top + FallThrough2Exit + FallThroughFromPred;
2083e6d15924SDimitry Andric if (Gains > Lost)
2084e6d15924SDimitry Andric Result = Gains - Lost;
2085e6d15924SDimitry Andric return Result;
2086e6d15924SDimitry Andric }
2087e6d15924SDimitry Andric
2088e6d15924SDimitry Andric /// Helper function of findBestLoopTop. Find the best loop top block
2089e6d15924SDimitry Andric /// from predecessors of old top.
2090e6d15924SDimitry Andric ///
2091e6d15924SDimitry Andric /// Look for a block which is strictly better than the old top for laying
2092e6d15924SDimitry Andric /// out before the old top of the loop. This looks for only two patterns:
2093e6d15924SDimitry Andric ///
2094e6d15924SDimitry Andric /// 1. a block has only one successor, the old loop top
2095e6d15924SDimitry Andric ///
2096e6d15924SDimitry Andric /// Because such a block will always result in an unconditional jump,
2097e6d15924SDimitry Andric /// rotating it in front of the old top is always profitable.
2098e6d15924SDimitry Andric ///
2099e6d15924SDimitry Andric /// 2. a block has two successors, one is old top, another is exit
2100e6d15924SDimitry Andric /// and it has more than one predecessors
2101e6d15924SDimitry Andric ///
2102e6d15924SDimitry Andric /// If it is below one of its predecessors P, only P can fall through to
2103e6d15924SDimitry Andric /// it, all other predecessors need a jump to it, and another conditional
2104e6d15924SDimitry Andric /// jump to loop header. If it is moved before loop header, all its
2105e6d15924SDimitry Andric /// predecessors jump to it, then fall through to loop header. So all its
2106e6d15924SDimitry Andric /// predecessors except P can reduce one taken branch.
2107e6d15924SDimitry Andric /// At the same time, move it before old top increases the taken branch
2108e6d15924SDimitry Andric /// to loop exit block, so the reduced taken branch will be compared with
2109e6d15924SDimitry Andric /// the increased taken branch to the loop exit block.
2110e6d15924SDimitry Andric MachineBasicBlock *
findBestLoopTopHelper(MachineBasicBlock * OldTop,const MachineLoop & L,const BlockFilterSet & LoopBlockSet)2111e6d15924SDimitry Andric MachineBlockPlacement::findBestLoopTopHelper(
2112e6d15924SDimitry Andric MachineBasicBlock *OldTop,
2113e6d15924SDimitry Andric const MachineLoop &L,
2114e6d15924SDimitry Andric const BlockFilterSet &LoopBlockSet) {
2115b61ab53cSDimitry Andric // Check that the header hasn't been fused with a preheader block due to
2116b61ab53cSDimitry Andric // crazy branches. If it has, we need to start with the header at the top to
2117b61ab53cSDimitry Andric // prevent pulling the preheader into the loop body.
2118e6d15924SDimitry Andric BlockChain &HeaderChain = *BlockToChain[OldTop];
2119b61ab53cSDimitry Andric if (!LoopBlockSet.count(*HeaderChain.begin()))
2120e6d15924SDimitry Andric return OldTop;
2121c0981da4SDimitry Andric if (OldTop != *HeaderChain.begin())
2122c0981da4SDimitry Andric return OldTop;
2123b61ab53cSDimitry Andric
2124e6d15924SDimitry Andric LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop)
2125e6d15924SDimitry Andric << "\n");
2126b61ab53cSDimitry Andric
2127b1c73532SDimitry Andric BlockFrequency BestGains = BlockFrequency(0);
21285ca98fd9SDimitry Andric MachineBasicBlock *BestPred = nullptr;
2129e6d15924SDimitry Andric for (MachineBasicBlock *Pred : OldTop->predecessors()) {
2130b61ab53cSDimitry Andric if (!LoopBlockSet.count(Pred))
2131b61ab53cSDimitry Andric continue;
2132e6d15924SDimitry Andric if (Pred == L.getHeader())
2133e6d15924SDimitry Andric continue;
2134e6d15924SDimitry Andric LLVM_DEBUG(dbgs() << " old top pred: " << getBlockName(Pred) << ", has "
2135b1c73532SDimitry Andric << Pred->succ_size() << " successors, "
2136b1c73532SDimitry Andric << printBlockFreq(MBFI->getMBFI(), *Pred) << " freq\n");
2137e6d15924SDimitry Andric if (Pred->succ_size() > 2)
2138b61ab53cSDimitry Andric continue;
2139b61ab53cSDimitry Andric
2140e6d15924SDimitry Andric MachineBasicBlock *OtherBB = nullptr;
2141e6d15924SDimitry Andric if (Pred->succ_size() == 2) {
2142e6d15924SDimitry Andric OtherBB = *Pred->succ_begin();
2143e6d15924SDimitry Andric if (OtherBB == OldTop)
2144e6d15924SDimitry Andric OtherBB = *Pred->succ_rbegin();
2145e6d15924SDimitry Andric }
2146e6d15924SDimitry Andric
2147e6d15924SDimitry Andric if (!canMoveBottomBlockToTop(Pred, OldTop))
2148e6d15924SDimitry Andric continue;
2149e6d15924SDimitry Andric
2150e6d15924SDimitry Andric BlockFrequency Gains = FallThroughGains(Pred, OldTop, OtherBB,
2151e6d15924SDimitry Andric LoopBlockSet);
2152b1c73532SDimitry Andric if ((Gains > BlockFrequency(0)) &&
2153b1c73532SDimitry Andric (Gains > BestGains ||
2154e6d15924SDimitry Andric ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) {
2155b61ab53cSDimitry Andric BestPred = Pred;
2156e6d15924SDimitry Andric BestGains = Gains;
2157b61ab53cSDimitry Andric }
2158b61ab53cSDimitry Andric }
2159b61ab53cSDimitry Andric
2160b61ab53cSDimitry Andric // If no direct predecessor is fine, just use the loop header.
216101095a5dSDimitry Andric if (!BestPred) {
2162eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " final top unchanged\n");
2163e6d15924SDimitry Andric return OldTop;
216401095a5dSDimitry Andric }
2165b61ab53cSDimitry Andric
2166b61ab53cSDimitry Andric // Walk backwards through any straight line of predecessors.
2167b61ab53cSDimitry Andric while (BestPred->pred_size() == 1 &&
2168b61ab53cSDimitry Andric (*BestPred->pred_begin())->succ_size() == 1 &&
2169b61ab53cSDimitry Andric *BestPred->pred_begin() != L.getHeader())
2170b61ab53cSDimitry Andric BestPred = *BestPred->pred_begin();
2171b61ab53cSDimitry Andric
2172eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
2173b61ab53cSDimitry Andric return BestPred;
2174b61ab53cSDimitry Andric }
2175b61ab53cSDimitry Andric
2176e6d15924SDimitry Andric /// Find the best loop top block for layout.
2177e6d15924SDimitry Andric ///
2178e6d15924SDimitry Andric /// This function iteratively calls findBestLoopTopHelper, until no new better
2179e6d15924SDimitry Andric /// BB can be found.
2180e6d15924SDimitry Andric MachineBasicBlock *
findBestLoopTop(const MachineLoop & L,const BlockFilterSet & LoopBlockSet)2181e6d15924SDimitry Andric MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
2182e6d15924SDimitry Andric const BlockFilterSet &LoopBlockSet) {
2183e6d15924SDimitry Andric // Placing the latch block before the header may introduce an extra branch
2184e6d15924SDimitry Andric // that skips this block the first time the loop is executed, which we want
2185e6d15924SDimitry Andric // to avoid when optimising for size.
2186e6d15924SDimitry Andric // FIXME: in theory there is a case that does not introduce a new branch,
2187e6d15924SDimitry Andric // i.e. when the layout predecessor does not fallthrough to the loop header.
2188e6d15924SDimitry Andric // In practice this never happens though: there always seems to be a preheader
2189e6d15924SDimitry Andric // that can fallthrough and that is also placed before the header.
2190706b4fc4SDimitry Andric bool OptForSize = F->getFunction().hasOptSize() ||
2191cfca06d7SDimitry Andric llvm::shouldOptimizeForSize(L.getHeader(), PSI, MBFI.get());
2192706b4fc4SDimitry Andric if (OptForSize)
2193e6d15924SDimitry Andric return L.getHeader();
2194e6d15924SDimitry Andric
2195e6d15924SDimitry Andric MachineBasicBlock *OldTop = nullptr;
2196e6d15924SDimitry Andric MachineBasicBlock *NewTop = L.getHeader();
2197e6d15924SDimitry Andric while (NewTop != OldTop) {
2198e6d15924SDimitry Andric OldTop = NewTop;
2199e6d15924SDimitry Andric NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet);
2200e6d15924SDimitry Andric if (NewTop != OldTop)
2201e6d15924SDimitry Andric ComputedEdges[NewTop] = { OldTop, false };
2202e6d15924SDimitry Andric }
2203e6d15924SDimitry Andric return NewTop;
2204e6d15924SDimitry Andric }
2205e6d15924SDimitry Andric
2206eb11fae6SDimitry Andric /// Find the best loop exiting block for layout.
2207b61ab53cSDimitry Andric ///
220863faed5bSDimitry Andric /// This routine implements the logic to analyze the loop looking for the best
220963faed5bSDimitry Andric /// block to layout at the top of the loop. Typically this is done to maximize
221063faed5bSDimitry Andric /// fallthrough opportunities.
221163faed5bSDimitry Andric MachineBasicBlock *
findBestLoopExit(const MachineLoop & L,const BlockFilterSet & LoopBlockSet,BlockFrequency & ExitFreq)221271d5a254SDimitry Andric MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
2213e6d15924SDimitry Andric const BlockFilterSet &LoopBlockSet,
2214e6d15924SDimitry Andric BlockFrequency &ExitFreq) {
221563faed5bSDimitry Andric // We don't want to layout the loop linearly in all cases. If the loop header
221663faed5bSDimitry Andric // is just a normal basic block in the loop, we want to look for what block
221763faed5bSDimitry Andric // within the loop is the best one to layout at the top. However, if the loop
221863faed5bSDimitry Andric // header has be pre-merged into a chain due to predecessors not having
221963faed5bSDimitry Andric // analyzable branches, *and* the predecessor it is merged with is *not* part
222063faed5bSDimitry Andric // of the loop, rotating the header into the middle of the loop will create
222163faed5bSDimitry Andric // a non-contiguous range of blocks which is Very Bad. So start with the
222263faed5bSDimitry Andric // header and only rotate if safe.
222363faed5bSDimitry Andric BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
222463faed5bSDimitry Andric if (!LoopBlockSet.count(*HeaderChain.begin()))
22255ca98fd9SDimitry Andric return nullptr;
222663faed5bSDimitry Andric
222763faed5bSDimitry Andric BlockFrequency BestExitEdgeFreq;
2228b61ab53cSDimitry Andric unsigned BestExitLoopDepth = 0;
22295ca98fd9SDimitry Andric MachineBasicBlock *ExitingBB = nullptr;
223063faed5bSDimitry Andric // If there are exits to outer loops, loop rotation can severely limit
223101095a5dSDimitry Andric // fallthrough opportunities unless it selects such an exit. Keep a set of
223263faed5bSDimitry Andric // blocks where rotating to exit with that block will reach an outer loop.
223363faed5bSDimitry Andric SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
223463faed5bSDimitry Andric
2235eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Finding best loop exit for: "
2236eb11fae6SDimitry Andric << getBlockName(L.getHeader()) << "\n");
22375a5ac124SDimitry Andric for (MachineBasicBlock *MBB : L.getBlocks()) {
22385a5ac124SDimitry Andric BlockChain &Chain = *BlockToChain[MBB];
223963faed5bSDimitry Andric // Ensure that this block is at the end of a chain; otherwise it could be
22405a5ac124SDimitry Andric // mid-way through an inner loop or a successor of an unanalyzable branch.
22415a5ac124SDimitry Andric if (MBB != *std::prev(Chain.end()))
224263faed5bSDimitry Andric continue;
224363faed5bSDimitry Andric
224463faed5bSDimitry Andric // Now walk the successors. We need to establish whether this has a viable
224563faed5bSDimitry Andric // exiting successor and whether it has a viable non-exiting successor.
224663faed5bSDimitry Andric // We store the old exiting state and restore it if a viable looping
224763faed5bSDimitry Andric // successor isn't found.
224863faed5bSDimitry Andric MachineBasicBlock *OldExitingBB = ExitingBB;
224963faed5bSDimitry Andric BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
2250b61ab53cSDimitry Andric bool HasLoopingSucc = false;
22515a5ac124SDimitry Andric for (MachineBasicBlock *Succ : MBB->successors()) {
2252dd58ef01SDimitry Andric if (Succ->isEHPad())
225363faed5bSDimitry Andric continue;
22545a5ac124SDimitry Andric if (Succ == MBB)
225563faed5bSDimitry Andric continue;
22565a5ac124SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ];
225763faed5bSDimitry Andric // Don't split chains, either this chain or the successor's chain.
2258b61ab53cSDimitry Andric if (&Chain == &SuccChain) {
2259eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
22605a5ac124SDimitry Andric << getBlockName(Succ) << " (chain conflict)\n");
226163faed5bSDimitry Andric continue;
226263faed5bSDimitry Andric }
226363faed5bSDimitry Andric
2264dd58ef01SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
22655a5ac124SDimitry Andric if (LoopBlockSet.count(Succ)) {
2266eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
2267dd58ef01SDimitry Andric << getBlockName(Succ) << " (" << SuccProb << ")\n");
2268b61ab53cSDimitry Andric HasLoopingSucc = true;
226963faed5bSDimitry Andric continue;
2270b61ab53cSDimitry Andric }
227163faed5bSDimitry Andric
2272b61ab53cSDimitry Andric unsigned SuccLoopDepth = 0;
22735a5ac124SDimitry Andric if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
2274b61ab53cSDimitry Andric SuccLoopDepth = ExitLoop->getLoopDepth();
2275b61ab53cSDimitry Andric if (ExitLoop->contains(&L))
22765a5ac124SDimitry Andric BlocksExitingToOuterLoop.insert(MBB);
227763faed5bSDimitry Andric }
227863faed5bSDimitry Andric
22795a5ac124SDimitry Andric BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
2280b1c73532SDimitry Andric LLVM_DEBUG(
2281b1c73532SDimitry Andric dbgs() << " exiting: " << getBlockName(MBB) << " -> "
2282b1c73532SDimitry Andric << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] ("
2283b1c73532SDimitry Andric << printBlockFreq(MBFI->getMBFI(), ExitEdgeFreq) << ")\n");
22845ca98fd9SDimitry Andric // Note that we bias this toward an existing layout successor to retain
22855ca98fd9SDimitry Andric // incoming order in the absence of better information. The exit must have
22865ca98fd9SDimitry Andric // a frequency higher than the current exit before we consider breaking
22875ca98fd9SDimitry Andric // the layout.
22885ca98fd9SDimitry Andric BranchProbability Bias(100 - ExitBlockBias, 100);
22895a5ac124SDimitry Andric if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
2290b61ab53cSDimitry Andric ExitEdgeFreq > BestExitEdgeFreq ||
22915a5ac124SDimitry Andric (MBB->isLayoutSuccessor(Succ) &&
22925ca98fd9SDimitry Andric !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
229363faed5bSDimitry Andric BestExitEdgeFreq = ExitEdgeFreq;
22945a5ac124SDimitry Andric ExitingBB = MBB;
229563faed5bSDimitry Andric }
229663faed5bSDimitry Andric }
229763faed5bSDimitry Andric
2298b61ab53cSDimitry Andric if (!HasLoopingSucc) {
22995a5ac124SDimitry Andric // Restore the old exiting state, no viable looping successor was found.
230063faed5bSDimitry Andric ExitingBB = OldExitingBB;
230163faed5bSDimitry Andric BestExitEdgeFreq = OldBestExitEdgeFreq;
230263faed5bSDimitry Andric }
230363faed5bSDimitry Andric }
2304b61ab53cSDimitry Andric // Without a candidate exiting block or with only a single block in the
230563faed5bSDimitry Andric // loop, just use the loop header to layout the loop.
2306b915e9e0SDimitry Andric if (!ExitingBB) {
2307eb11fae6SDimitry Andric LLVM_DEBUG(
2308eb11fae6SDimitry Andric dbgs() << " No other candidate exit blocks, using loop header\n");
23095ca98fd9SDimitry Andric return nullptr;
2310b915e9e0SDimitry Andric }
2311b915e9e0SDimitry Andric if (L.getNumBlocks() == 1) {
2312eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
2313b915e9e0SDimitry Andric return nullptr;
2314b915e9e0SDimitry Andric }
231563faed5bSDimitry Andric
231663faed5bSDimitry Andric // Also, if we have exit blocks which lead to outer loops but didn't select
231763faed5bSDimitry Andric // one of them as the exiting block we are rotating toward, disable loop
231863faed5bSDimitry Andric // rotation altogether.
231963faed5bSDimitry Andric if (!BlocksExitingToOuterLoop.empty() &&
232063faed5bSDimitry Andric !BlocksExitingToOuterLoop.count(ExitingBB))
23215ca98fd9SDimitry Andric return nullptr;
232263faed5bSDimitry Andric
2323eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB)
2324eb11fae6SDimitry Andric << "\n");
2325e6d15924SDimitry Andric ExitFreq = BestExitEdgeFreq;
2326b61ab53cSDimitry Andric return ExitingBB;
2327b61ab53cSDimitry Andric }
2328b61ab53cSDimitry Andric
2329e6d15924SDimitry Andric /// Check if there is a fallthrough to loop header Top.
2330e6d15924SDimitry Andric ///
2331e6d15924SDimitry Andric /// 1. Look for a Pred that can be layout before Top.
2332e6d15924SDimitry Andric /// 2. Check if Top is the most possible successor of Pred.
2333e6d15924SDimitry Andric bool
hasViableTopFallthrough(const MachineBasicBlock * Top,const BlockFilterSet & LoopBlockSet)2334e6d15924SDimitry Andric MachineBlockPlacement::hasViableTopFallthrough(
2335e6d15924SDimitry Andric const MachineBasicBlock *Top,
2336e6d15924SDimitry Andric const BlockFilterSet &LoopBlockSet) {
2337e6d15924SDimitry Andric for (MachineBasicBlock *Pred : Top->predecessors()) {
2338e6d15924SDimitry Andric BlockChain *PredChain = BlockToChain[Pred];
2339e6d15924SDimitry Andric if (!LoopBlockSet.count(Pred) &&
2340e6d15924SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) {
2341e6d15924SDimitry Andric // Found a Pred block can be placed before Top.
2342e6d15924SDimitry Andric // Check if Top is the best successor of Pred.
2343e6d15924SDimitry Andric auto TopProb = MBPI->getEdgeProbability(Pred, Top);
2344e6d15924SDimitry Andric bool TopOK = true;
2345e6d15924SDimitry Andric for (MachineBasicBlock *Succ : Pred->successors()) {
2346e6d15924SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
2347e6d15924SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ];
2348e6d15924SDimitry Andric // Check if Succ can be placed after Pred.
2349e6d15924SDimitry Andric // Succ should not be in any chain, or it is the head of some chain.
2350e6d15924SDimitry Andric if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
2351e6d15924SDimitry Andric TopOK = false;
2352e6d15924SDimitry Andric break;
2353e6d15924SDimitry Andric }
2354e6d15924SDimitry Andric }
2355e6d15924SDimitry Andric if (TopOK)
2356e6d15924SDimitry Andric return true;
2357e6d15924SDimitry Andric }
2358e6d15924SDimitry Andric }
2359e6d15924SDimitry Andric return false;
2360e6d15924SDimitry Andric }
2361e6d15924SDimitry Andric
2362eb11fae6SDimitry Andric /// Attempt to rotate an exiting block to the bottom of the loop.
2363b61ab53cSDimitry Andric ///
2364b61ab53cSDimitry Andric /// Once we have built a chain, try to rotate it to line up the hot exit block
2365b61ab53cSDimitry Andric /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
2366b61ab53cSDimitry Andric /// branches. For example, if the loop has fallthrough into its header and out
2367b61ab53cSDimitry Andric /// of its bottom already, don't rotate it.
rotateLoop(BlockChain & LoopChain,const MachineBasicBlock * ExitingBB,BlockFrequency ExitFreq,const BlockFilterSet & LoopBlockSet)2368b61ab53cSDimitry Andric void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
236971d5a254SDimitry Andric const MachineBasicBlock *ExitingBB,
2370e6d15924SDimitry Andric BlockFrequency ExitFreq,
2371b61ab53cSDimitry Andric const BlockFilterSet &LoopBlockSet) {
2372b61ab53cSDimitry Andric if (!ExitingBB)
2373b61ab53cSDimitry Andric return;
2374b61ab53cSDimitry Andric
2375b61ab53cSDimitry Andric MachineBasicBlock *Top = *LoopChain.begin();
2376ca089b24SDimitry Andric MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
2377ca089b24SDimitry Andric
2378ca089b24SDimitry Andric // If ExitingBB is already the last one in a chain then nothing to do.
2379ca089b24SDimitry Andric if (Bottom == ExitingBB)
2380ca089b24SDimitry Andric return;
2381ca089b24SDimitry Andric
2382b60736ecSDimitry Andric // The entry block should always be the first BB in a function.
2383b60736ecSDimitry Andric if (Top->isEntryBlock())
2384b60736ecSDimitry Andric return;
2385b60736ecSDimitry Andric
2386e6d15924SDimitry Andric bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
2387b61ab53cSDimitry Andric
2388b61ab53cSDimitry Andric // If the header has viable fallthrough, check whether the current loop
2389b61ab53cSDimitry Andric // bottom is a viable exiting block. If so, bail out as rotating will
2390b61ab53cSDimitry Andric // introduce an unnecessary branch.
2391b61ab53cSDimitry Andric if (ViableTopFallthrough) {
23925a5ac124SDimitry Andric for (MachineBasicBlock *Succ : Bottom->successors()) {
23935a5ac124SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ];
23945a5ac124SDimitry Andric if (!LoopBlockSet.count(Succ) &&
23955a5ac124SDimitry Andric (!SuccChain || Succ == *SuccChain->begin()))
2396b61ab53cSDimitry Andric return;
2397b61ab53cSDimitry Andric }
2398e6d15924SDimitry Andric
2399e6d15924SDimitry Andric // Rotate will destroy the top fallthrough, we need to ensure the new exit
2400e6d15924SDimitry Andric // frequency is larger than top fallthrough.
2401e6d15924SDimitry Andric BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet);
2402e6d15924SDimitry Andric if (FallThrough2Top >= ExitFreq)
2403e6d15924SDimitry Andric return;
2404b61ab53cSDimitry Andric }
2405b61ab53cSDimitry Andric
2406044eb2f6SDimitry Andric BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
2407b61ab53cSDimitry Andric if (ExitIt == LoopChain.end())
2408b61ab53cSDimitry Andric return;
2409b61ab53cSDimitry Andric
2410ca089b24SDimitry Andric // Rotating a loop exit to the bottom when there is a fallthrough to top
2411ca089b24SDimitry Andric // trades the entry fallthrough for an exit fallthrough.
2412ca089b24SDimitry Andric // If there is no bottom->top edge, but the chosen exit block does have
2413ca089b24SDimitry Andric // a fallthrough, we break that fallthrough for nothing in return.
2414ca089b24SDimitry Andric
2415ca089b24SDimitry Andric // Let's consider an example. We have a built chain of basic blocks
2416ca089b24SDimitry Andric // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
2417ca089b24SDimitry Andric // By doing a rotation we get
2418ca089b24SDimitry Andric // Bk+1, ..., Bn, B1, ..., Bk
2419ca089b24SDimitry Andric // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
2420ca089b24SDimitry Andric // If we had a fallthrough Bk -> Bk+1 it is broken now.
2421ca089b24SDimitry Andric // It might be compensated by fallthrough Bn -> B1.
2422ca089b24SDimitry Andric // So we have a condition to avoid creation of extra branch by loop rotation.
2423ca089b24SDimitry Andric // All below must be true to avoid loop rotation:
2424ca089b24SDimitry Andric // If there is a fallthrough to top (B1)
2425ca089b24SDimitry Andric // There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
2426ca089b24SDimitry Andric // There is no fallthrough from bottom (Bn) to top (B1).
2427ca089b24SDimitry Andric // Please note that there is no exit fallthrough from Bn because we checked it
2428ca089b24SDimitry Andric // above.
2429ca089b24SDimitry Andric if (ViableTopFallthrough) {
2430ca089b24SDimitry Andric assert(std::next(ExitIt) != LoopChain.end() &&
2431ca089b24SDimitry Andric "Exit should not be last BB");
2432ca089b24SDimitry Andric MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
2433ca089b24SDimitry Andric if (ExitingBB->isSuccessor(NextBlockInChain))
2434ca089b24SDimitry Andric if (!Bottom->isSuccessor(Top))
2435ca089b24SDimitry Andric return;
2436ca089b24SDimitry Andric }
2437ca089b24SDimitry Andric
2438eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
2439ca089b24SDimitry Andric << " at bottom\n");
24405ca98fd9SDimitry Andric std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
244163faed5bSDimitry Andric }
244263faed5bSDimitry Andric
2443eb11fae6SDimitry Andric /// Attempt to rotate a loop based on profile data to reduce branch cost.
2444dd58ef01SDimitry Andric ///
2445dd58ef01SDimitry Andric /// With profile data, we can determine the cost in terms of missed fall through
2446dd58ef01SDimitry Andric /// opportunities when rotating a loop chain and select the best rotation.
2447dd58ef01SDimitry Andric /// Basically, there are three kinds of cost to consider for each rotation:
2448dd58ef01SDimitry Andric /// 1. The possibly missed fall through edge (if it exists) from BB out of
2449dd58ef01SDimitry Andric /// the loop to the loop header.
2450dd58ef01SDimitry Andric /// 2. The possibly missed fall through edges (if they exist) from the loop
2451dd58ef01SDimitry Andric /// exits to BB out of the loop.
2452dd58ef01SDimitry Andric /// 3. The missed fall through edge (if it exists) from the last BB to the
2453dd58ef01SDimitry Andric /// first BB in the loop chain.
2454dd58ef01SDimitry Andric /// Therefore, the cost for a given rotation is the sum of costs listed above.
2455dd58ef01SDimitry Andric /// We select the best rotation with the smallest cost.
rotateLoopWithProfile(BlockChain & LoopChain,const MachineLoop & L,const BlockFilterSet & LoopBlockSet)2456dd58ef01SDimitry Andric void MachineBlockPlacement::rotateLoopWithProfile(
245771d5a254SDimitry Andric BlockChain &LoopChain, const MachineLoop &L,
245871d5a254SDimitry Andric const BlockFilterSet &LoopBlockSet) {
2459dd58ef01SDimitry Andric auto RotationPos = LoopChain.end();
2460b60736ecSDimitry Andric MachineBasicBlock *ChainHeaderBB = *LoopChain.begin();
2461b60736ecSDimitry Andric
2462b60736ecSDimitry Andric // The entry block should always be the first BB in a function.
2463b60736ecSDimitry Andric if (ChainHeaderBB->isEntryBlock())
2464b60736ecSDimitry Andric return;
2465dd58ef01SDimitry Andric
2466b1c73532SDimitry Andric BlockFrequency SmallestRotationCost = BlockFrequency::max();
2467dd58ef01SDimitry Andric
2468dd58ef01SDimitry Andric // A utility lambda that scales up a block frequency by dividing it by a
2469dd58ef01SDimitry Andric // branch probability which is the reciprocal of the scale.
2470dd58ef01SDimitry Andric auto ScaleBlockFrequency = [](BlockFrequency Freq,
2471dd58ef01SDimitry Andric unsigned Scale) -> BlockFrequency {
2472dd58ef01SDimitry Andric if (Scale == 0)
2473b1c73532SDimitry Andric return BlockFrequency(0);
2474dd58ef01SDimitry Andric // Use operator / between BlockFrequency and BranchProbability to implement
2475dd58ef01SDimitry Andric // saturating multiplication.
2476dd58ef01SDimitry Andric return Freq / BranchProbability(1, Scale);
2477dd58ef01SDimitry Andric };
2478dd58ef01SDimitry Andric
2479dd58ef01SDimitry Andric // Compute the cost of the missed fall-through edge to the loop header if the
2480dd58ef01SDimitry Andric // chain head is not the loop header. As we only consider natural loops with
2481dd58ef01SDimitry Andric // single header, this computation can be done only once.
2482dd58ef01SDimitry Andric BlockFrequency HeaderFallThroughCost(0);
2483e6d15924SDimitry Andric for (auto *Pred : ChainHeaderBB->predecessors()) {
2484dd58ef01SDimitry Andric BlockChain *PredChain = BlockToChain[Pred];
2485dd58ef01SDimitry Andric if (!LoopBlockSet.count(Pred) &&
2486dd58ef01SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) {
2487e6d15924SDimitry Andric auto EdgeFreq = MBFI->getBlockFreq(Pred) *
2488e6d15924SDimitry Andric MBPI->getEdgeProbability(Pred, ChainHeaderBB);
2489dd58ef01SDimitry Andric auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
2490dd58ef01SDimitry Andric // If the predecessor has only an unconditional jump to the header, we
2491dd58ef01SDimitry Andric // need to consider the cost of this jump.
2492dd58ef01SDimitry Andric if (Pred->succ_size() == 1)
2493dd58ef01SDimitry Andric FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
2494dd58ef01SDimitry Andric HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
2495dd58ef01SDimitry Andric }
2496dd58ef01SDimitry Andric }
2497dd58ef01SDimitry Andric
2498dd58ef01SDimitry Andric // Here we collect all exit blocks in the loop, and for each exit we find out
2499dd58ef01SDimitry Andric // its hottest exit edge. For each loop rotation, we define the loop exit cost
2500dd58ef01SDimitry Andric // as the sum of frequencies of exit edges we collect here, excluding the exit
2501dd58ef01SDimitry Andric // edge from the tail of the loop chain.
2502dd58ef01SDimitry Andric SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
25034b4fe385SDimitry Andric for (auto *BB : LoopChain) {
2504dd58ef01SDimitry Andric auto LargestExitEdgeProb = BranchProbability::getZero();
2505dd58ef01SDimitry Andric for (auto *Succ : BB->successors()) {
2506dd58ef01SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ];
2507dd58ef01SDimitry Andric if (!LoopBlockSet.count(Succ) &&
2508dd58ef01SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) {
2509dd58ef01SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2510dd58ef01SDimitry Andric LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
2511dd58ef01SDimitry Andric }
2512dd58ef01SDimitry Andric }
2513dd58ef01SDimitry Andric if (LargestExitEdgeProb > BranchProbability::getZero()) {
2514dd58ef01SDimitry Andric auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
2515dd58ef01SDimitry Andric ExitsWithFreq.emplace_back(BB, ExitFreq);
2516dd58ef01SDimitry Andric }
2517dd58ef01SDimitry Andric }
2518dd58ef01SDimitry Andric
2519dd58ef01SDimitry Andric // In this loop we iterate every block in the loop chain and calculate the
2520dd58ef01SDimitry Andric // cost assuming the block is the head of the loop chain. When the loop ends,
2521dd58ef01SDimitry Andric // we should have found the best candidate as the loop chain's head.
2522dd58ef01SDimitry Andric for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2523dd58ef01SDimitry Andric EndIter = LoopChain.end();
2524dd58ef01SDimitry Andric Iter != EndIter; Iter++, TailIter++) {
2525dd58ef01SDimitry Andric // TailIter is used to track the tail of the loop chain if the block we are
2526dd58ef01SDimitry Andric // checking (pointed by Iter) is the head of the chain.
2527dd58ef01SDimitry Andric if (TailIter == LoopChain.end())
2528dd58ef01SDimitry Andric TailIter = LoopChain.begin();
2529dd58ef01SDimitry Andric
2530dd58ef01SDimitry Andric auto TailBB = *TailIter;
2531dd58ef01SDimitry Andric
2532dd58ef01SDimitry Andric // Calculate the cost by putting this BB to the top.
2533b1c73532SDimitry Andric BlockFrequency Cost = BlockFrequency(0);
2534dd58ef01SDimitry Andric
2535dd58ef01SDimitry Andric // If the current BB is the loop header, we need to take into account the
2536dd58ef01SDimitry Andric // cost of the missed fall through edge from outside of the loop to the
2537dd58ef01SDimitry Andric // header.
2538e6d15924SDimitry Andric if (Iter != LoopChain.begin())
2539dd58ef01SDimitry Andric Cost += HeaderFallThroughCost;
2540dd58ef01SDimitry Andric
2541dd58ef01SDimitry Andric // Collect the loop exit cost by summing up frequencies of all exit edges
2542dd58ef01SDimitry Andric // except the one from the chain tail.
2543dd58ef01SDimitry Andric for (auto &ExitWithFreq : ExitsWithFreq)
2544dd58ef01SDimitry Andric if (TailBB != ExitWithFreq.first)
2545dd58ef01SDimitry Andric Cost += ExitWithFreq.second;
2546dd58ef01SDimitry Andric
2547dd58ef01SDimitry Andric // The cost of breaking the once fall-through edge from the tail to the top
2548dd58ef01SDimitry Andric // of the loop chain. Here we need to consider three cases:
2549dd58ef01SDimitry Andric // 1. If the tail node has only one successor, then we will get an
2550dd58ef01SDimitry Andric // additional jmp instruction. So the cost here is (MisfetchCost +
2551dd58ef01SDimitry Andric // JumpInstCost) * tail node frequency.
2552dd58ef01SDimitry Andric // 2. If the tail node has two successors, then we may still get an
2553dd58ef01SDimitry Andric // additional jmp instruction if the layout successor after the loop
2554dd58ef01SDimitry Andric // chain is not its CFG successor. Note that the more frequently executed
2555dd58ef01SDimitry Andric // jmp instruction will be put ahead of the other one. Assume the
2556dd58ef01SDimitry Andric // frequency of those two branches are x and y, where x is the frequency
2557dd58ef01SDimitry Andric // of the edge to the chain head, then the cost will be
2558dd58ef01SDimitry Andric // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
2559dd58ef01SDimitry Andric // 3. If the tail node has more than two successors (this rarely happens),
2560dd58ef01SDimitry Andric // we won't consider any additional cost.
2561dd58ef01SDimitry Andric if (TailBB->isSuccessor(*Iter)) {
2562dd58ef01SDimitry Andric auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2563dd58ef01SDimitry Andric if (TailBB->succ_size() == 1)
2564b1c73532SDimitry Andric Cost += ScaleBlockFrequency(TailBBFreq, MisfetchCost + JumpInstCost);
2565dd58ef01SDimitry Andric else if (TailBB->succ_size() == 2) {
2566dd58ef01SDimitry Andric auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2567dd58ef01SDimitry Andric auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2568dd58ef01SDimitry Andric auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2569dd58ef01SDimitry Andric ? TailBBFreq * TailToHeadProb.getCompl()
2570dd58ef01SDimitry Andric : TailToHeadFreq;
2571dd58ef01SDimitry Andric Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
2572dd58ef01SDimitry Andric ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
2573dd58ef01SDimitry Andric }
2574dd58ef01SDimitry Andric }
2575dd58ef01SDimitry Andric
2576eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "The cost of loop rotation by making "
2577b1c73532SDimitry Andric << getBlockName(*Iter) << " to the top: "
2578b1c73532SDimitry Andric << printBlockFreq(MBFI->getMBFI(), Cost) << "\n");
2579dd58ef01SDimitry Andric
2580dd58ef01SDimitry Andric if (Cost < SmallestRotationCost) {
2581dd58ef01SDimitry Andric SmallestRotationCost = Cost;
2582dd58ef01SDimitry Andric RotationPos = Iter;
2583dd58ef01SDimitry Andric }
2584dd58ef01SDimitry Andric }
2585dd58ef01SDimitry Andric
2586dd58ef01SDimitry Andric if (RotationPos != LoopChain.end()) {
2587eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
2588dd58ef01SDimitry Andric << " to the top\n");
2589dd58ef01SDimitry Andric std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2590dd58ef01SDimitry Andric }
2591dd58ef01SDimitry Andric }
2592dd58ef01SDimitry Andric
2593eb11fae6SDimitry Andric /// Collect blocks in the given loop that are to be placed.
2594dd58ef01SDimitry Andric ///
2595dd58ef01SDimitry Andric /// When profile data is available, exclude cold blocks from the returned set;
2596dd58ef01SDimitry Andric /// otherwise, collect all blocks in the loop.
2597dd58ef01SDimitry Andric MachineBlockPlacement::BlockFilterSet
collectLoopBlockSet(const MachineLoop & L)259871d5a254SDimitry Andric MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
2599dd58ef01SDimitry Andric BlockFilterSet LoopBlockSet;
2600dd58ef01SDimitry Andric
2601dd58ef01SDimitry Andric // Filter cold blocks off from LoopBlockSet when profile data is available.
2602dd58ef01SDimitry Andric // Collect the sum of frequencies of incoming edges to the loop header from
2603dd58ef01SDimitry Andric // outside. If we treat the loop as a super block, this is the frequency of
2604dd58ef01SDimitry Andric // the loop. Then for each block in the loop, we calculate the ratio between
2605dd58ef01SDimitry Andric // its frequency and the frequency of the loop block. When it is too small,
2606dd58ef01SDimitry Andric // don't add it to the loop chain. If there are outer loops, then this block
2607dd58ef01SDimitry Andric // will be merged into the first outer loop chain for which this block is not
2608dd58ef01SDimitry Andric // cold anymore. This needs precise profile data and we only do this when
2609dd58ef01SDimitry Andric // profile data is available.
2610c7dac04cSDimitry Andric if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
2611dd58ef01SDimitry Andric BlockFrequency LoopFreq(0);
26124b4fe385SDimitry Andric for (auto *LoopPred : L.getHeader()->predecessors())
2613dd58ef01SDimitry Andric if (!L.contains(LoopPred))
2614dd58ef01SDimitry Andric LoopFreq += MBFI->getBlockFreq(LoopPred) *
2615dd58ef01SDimitry Andric MBPI->getEdgeProbability(LoopPred, L.getHeader());
2616dd58ef01SDimitry Andric
2617dd58ef01SDimitry Andric for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2618b60736ecSDimitry Andric if (LoopBlockSet.count(LoopBB))
2619b60736ecSDimitry Andric continue;
2620dd58ef01SDimitry Andric auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2621dd58ef01SDimitry Andric if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2622dd58ef01SDimitry Andric continue;
2623b60736ecSDimitry Andric BlockChain *Chain = BlockToChain[LoopBB];
2624b60736ecSDimitry Andric for (MachineBasicBlock *ChainBB : *Chain)
2625b60736ecSDimitry Andric LoopBlockSet.insert(ChainBB);
2626dd58ef01SDimitry Andric }
2627dd58ef01SDimitry Andric } else
2628dd58ef01SDimitry Andric LoopBlockSet.insert(L.block_begin(), L.block_end());
2629dd58ef01SDimitry Andric
2630dd58ef01SDimitry Andric return LoopBlockSet;
2631dd58ef01SDimitry Andric }
2632dd58ef01SDimitry Andric
2633eb11fae6SDimitry Andric /// Forms basic block chains from the natural loop structures.
263463faed5bSDimitry Andric ///
263563faed5bSDimitry Andric /// These chains are designed to preserve the existing *structure* of the code
263663faed5bSDimitry Andric /// as much as possible. We can then stitch the chains together in a way which
263763faed5bSDimitry Andric /// both preserves the topological structure and minimizes taken conditional
263863faed5bSDimitry Andric /// branches.
buildLoopChains(const MachineLoop & L)263971d5a254SDimitry Andric void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
264063faed5bSDimitry Andric // First recurse through any nested loops, building chains for those inner
264163faed5bSDimitry Andric // loops.
264271d5a254SDimitry Andric for (const MachineLoop *InnerLoop : L)
264301095a5dSDimitry Andric buildLoopChains(*InnerLoop);
264463faed5bSDimitry Andric
2645b5630dbaSDimitry Andric assert(BlockWorkList.empty() &&
2646b5630dbaSDimitry Andric "BlockWorkList not empty when starting to build loop chains.");
2647b5630dbaSDimitry Andric assert(EHPadWorkList.empty() &&
2648b5630dbaSDimitry Andric "EHPadWorkList not empty when starting to build loop chains.");
264901095a5dSDimitry Andric BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
2650dd58ef01SDimitry Andric
2651dd58ef01SDimitry Andric // Check if we have profile data for this function. If yes, we will rotate
2652dd58ef01SDimitry Andric // this loop by modeling costs more precisely which requires the profile data
2653dd58ef01SDimitry Andric // for better layout.
2654dd58ef01SDimitry Andric bool RotateLoopWithProfile =
265501095a5dSDimitry Andric ForcePreciseRotationCost ||
2656c7dac04cSDimitry Andric (PreciseRotationCost && F->getFunction().hasProfileData());
265763faed5bSDimitry Andric
2658b61ab53cSDimitry Andric // First check to see if there is an obviously preferable top block for the
2659b61ab53cSDimitry Andric // loop. This will default to the header, but may end up as one of the
2660b61ab53cSDimitry Andric // predecessors to the header if there is one which will result in strictly
2661b61ab53cSDimitry Andric // fewer branches in the loop body.
2662e6d15924SDimitry Andric MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
2663b61ab53cSDimitry Andric
2664b61ab53cSDimitry Andric // If we selected just the header for the loop top, look for a potentially
2665b61ab53cSDimitry Andric // profitable exit block in the event that rotating the loop can eliminate
2666b61ab53cSDimitry Andric // branches by placing an exit edge at the bottom.
2667044eb2f6SDimitry Andric //
2668044eb2f6SDimitry Andric // Loops are processed innermost to uttermost, make sure we clear
2669044eb2f6SDimitry Andric // PreferredLoopExit before processing a new loop.
2670044eb2f6SDimitry Andric PreferredLoopExit = nullptr;
2671e6d15924SDimitry Andric BlockFrequency ExitFreq;
2672dd58ef01SDimitry Andric if (!RotateLoopWithProfile && LoopTop == L.getHeader())
2673e6d15924SDimitry Andric PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq);
2674b61ab53cSDimitry Andric
2675b61ab53cSDimitry Andric BlockChain &LoopChain = *BlockToChain[LoopTop];
267663faed5bSDimitry Andric
267763faed5bSDimitry Andric // FIXME: This is a really lame way of walking the chains in the loop: we
267863faed5bSDimitry Andric // walk the blocks, and use a set to prevent visiting a particular chain
267963faed5bSDimitry Andric // twice.
268063faed5bSDimitry Andric SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2681b5630dbaSDimitry Andric assert(LoopChain.UnscheduledPredecessors == 0 &&
2682b5630dbaSDimitry Andric "LoopChain should not have unscheduled predecessors.");
268363faed5bSDimitry Andric UpdatedPreds.insert(&LoopChain);
2684dd58ef01SDimitry Andric
268571d5a254SDimitry Andric for (const MachineBasicBlock *LoopBB : LoopBlockSet)
268601095a5dSDimitry Andric fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
268763faed5bSDimitry Andric
268801095a5dSDimitry Andric buildChain(LoopTop, LoopChain, &LoopBlockSet);
2689dd58ef01SDimitry Andric
2690dd58ef01SDimitry Andric if (RotateLoopWithProfile)
2691dd58ef01SDimitry Andric rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2692dd58ef01SDimitry Andric else
2693e6d15924SDimitry Andric rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet);
269463faed5bSDimitry Andric
2695eb11fae6SDimitry Andric LLVM_DEBUG({
269663faed5bSDimitry Andric // Crash at the end so we get all of the debugging output first.
269763faed5bSDimitry Andric bool BadLoop = false;
269801095a5dSDimitry Andric if (LoopChain.UnscheduledPredecessors) {
269963faed5bSDimitry Andric BadLoop = true;
270063faed5bSDimitry Andric dbgs() << "Loop chain contains a block without its preds placed!\n"
270163faed5bSDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
270263faed5bSDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
270363faed5bSDimitry Andric }
27045a5ac124SDimitry Andric for (MachineBasicBlock *ChainBB : LoopChain) {
27055a5ac124SDimitry Andric dbgs() << " ... " << getBlockName(ChainBB) << "\n";
2706b915e9e0SDimitry Andric if (!LoopBlockSet.remove(ChainBB)) {
270763faed5bSDimitry Andric // We don't mark the loop as bad here because there are real situations
270863faed5bSDimitry Andric // where this can occur. For example, with an unanalyzable fallthrough
270963faed5bSDimitry Andric // from a loop block to a non-loop block or vice versa.
271063faed5bSDimitry Andric dbgs() << "Loop chain contains a block not contained by the loop!\n"
271163faed5bSDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
271263faed5bSDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
27135a5ac124SDimitry Andric << " Bad block: " << getBlockName(ChainBB) << "\n";
271463faed5bSDimitry Andric }
2715b61ab53cSDimitry Andric }
271663faed5bSDimitry Andric
271763faed5bSDimitry Andric if (!LoopBlockSet.empty()) {
271863faed5bSDimitry Andric BadLoop = true;
271971d5a254SDimitry Andric for (const MachineBasicBlock *LoopBB : LoopBlockSet)
272063faed5bSDimitry Andric dbgs() << "Loop contains blocks never placed into a chain!\n"
272163faed5bSDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
272263faed5bSDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
27235a5ac124SDimitry Andric << " Bad block: " << getBlockName(LoopBB) << "\n";
272463faed5bSDimitry Andric }
272563faed5bSDimitry Andric assert(!BadLoop && "Detected problems with the placement of this loop.");
272663faed5bSDimitry Andric });
272701095a5dSDimitry Andric
272801095a5dSDimitry Andric BlockWorkList.clear();
272901095a5dSDimitry Andric EHPadWorkList.clear();
273063faed5bSDimitry Andric }
273163faed5bSDimitry Andric
buildCFGChains()273201095a5dSDimitry Andric void MachineBlockPlacement::buildCFGChains() {
273363faed5bSDimitry Andric // Ensure that every BB in the function has an associated chain to simplify
273463faed5bSDimitry Andric // the assumptions of the remaining algorithm.
2735cfca06d7SDimitry Andric SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
273601095a5dSDimitry Andric for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
273701095a5dSDimitry Andric ++FI) {
2738dd58ef01SDimitry Andric MachineBasicBlock *BB = &*FI;
27395a5ac124SDimitry Andric BlockChain *Chain =
27405a5ac124SDimitry Andric new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
274163faed5bSDimitry Andric // Also, merge any blocks which we cannot reason about and must preserve
274263faed5bSDimitry Andric // the exact fallthrough behavior for.
2743044eb2f6SDimitry Andric while (true) {
274463faed5bSDimitry Andric Cond.clear();
2745cfca06d7SDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
274601095a5dSDimitry Andric if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
274763faed5bSDimitry Andric break;
274863faed5bSDimitry Andric
2749dd58ef01SDimitry Andric MachineFunction::iterator NextFI = std::next(FI);
2750dd58ef01SDimitry Andric MachineBasicBlock *NextBB = &*NextFI;
275163faed5bSDimitry Andric // Ensure that the layout successor is a viable block, as we know that
275263faed5bSDimitry Andric // fallthrough is a possibility.
275363faed5bSDimitry Andric assert(NextFI != FE && "Can't fallthrough past the last block.");
2754eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
275563faed5bSDimitry Andric << getBlockName(BB) << " -> " << getBlockName(NextBB)
275663faed5bSDimitry Andric << "\n");
27575ca98fd9SDimitry Andric Chain->merge(NextBB, nullptr);
2758b915e9e0SDimitry Andric #ifndef NDEBUG
2759b915e9e0SDimitry Andric BlocksWithUnanalyzableExits.insert(&*BB);
2760b915e9e0SDimitry Andric #endif
276163faed5bSDimitry Andric FI = NextFI;
276263faed5bSDimitry Andric BB = NextBB;
276363faed5bSDimitry Andric }
276463faed5bSDimitry Andric }
276563faed5bSDimitry Andric
276663faed5bSDimitry Andric // Build any loop-based chains.
2767b915e9e0SDimitry Andric PreferredLoopExit = nullptr;
27685a5ac124SDimitry Andric for (MachineLoop *L : *MLI)
276901095a5dSDimitry Andric buildLoopChains(*L);
277063faed5bSDimitry Andric
2771b5630dbaSDimitry Andric assert(BlockWorkList.empty() &&
2772b5630dbaSDimitry Andric "BlockWorkList should be empty before building final chain.");
2773b5630dbaSDimitry Andric assert(EHPadWorkList.empty() &&
2774b5630dbaSDimitry Andric "EHPadWorkList should be empty before building final chain.");
277563faed5bSDimitry Andric
277663faed5bSDimitry Andric SmallPtrSet<BlockChain *, 4> UpdatedPreds;
277701095a5dSDimitry Andric for (MachineBasicBlock &MBB : *F)
277801095a5dSDimitry Andric fillWorkLists(&MBB, UpdatedPreds);
277963faed5bSDimitry Andric
278001095a5dSDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()];
278101095a5dSDimitry Andric buildChain(&F->front(), FunctionChain);
278263faed5bSDimitry Andric
27835ca98fd9SDimitry Andric #ifndef NDEBUG
2784044eb2f6SDimitry Andric using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
27855ca98fd9SDimitry Andric #endif
2786eb11fae6SDimitry Andric LLVM_DEBUG({
278763faed5bSDimitry Andric // Crash at the end so we get all of the debugging output first.
278863faed5bSDimitry Andric bool BadFunc = false;
278963faed5bSDimitry Andric FunctionBlockSetType FunctionBlockSet;
279001095a5dSDimitry Andric for (MachineBasicBlock &MBB : *F)
27915a5ac124SDimitry Andric FunctionBlockSet.insert(&MBB);
279263faed5bSDimitry Andric
27935a5ac124SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain)
27945a5ac124SDimitry Andric if (!FunctionBlockSet.erase(ChainBB)) {
279563faed5bSDimitry Andric BadFunc = true;
279663faed5bSDimitry Andric dbgs() << "Function chain contains a block not in the function!\n"
27975a5ac124SDimitry Andric << " Bad block: " << getBlockName(ChainBB) << "\n";
279863faed5bSDimitry Andric }
279963faed5bSDimitry Andric
280063faed5bSDimitry Andric if (!FunctionBlockSet.empty()) {
280163faed5bSDimitry Andric BadFunc = true;
28025a5ac124SDimitry Andric for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
280363faed5bSDimitry Andric dbgs() << "Function contains blocks never placed into a chain!\n"
28045a5ac124SDimitry Andric << " Bad block: " << getBlockName(RemainingBB) << "\n";
280563faed5bSDimitry Andric }
280663faed5bSDimitry Andric assert(!BadFunc && "Detected problems with the block placement.");
280763faed5bSDimitry Andric });
280863faed5bSDimitry Andric
2809cfca06d7SDimitry Andric // Remember original layout ordering, so we can update terminators after
2810cfca06d7SDimitry Andric // reordering to point to the original layout successor.
2811cfca06d7SDimitry Andric SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors(
2812cfca06d7SDimitry Andric F->getNumBlockIDs());
2813cfca06d7SDimitry Andric {
2814cfca06d7SDimitry Andric MachineBasicBlock *LastMBB = nullptr;
2815cfca06d7SDimitry Andric for (auto &MBB : *F) {
2816cfca06d7SDimitry Andric if (LastMBB != nullptr)
2817cfca06d7SDimitry Andric OriginalLayoutSuccessors[LastMBB->getNumber()] = &MBB;
2818cfca06d7SDimitry Andric LastMBB = &MBB;
2819cfca06d7SDimitry Andric }
2820cfca06d7SDimitry Andric OriginalLayoutSuccessors[F->back().getNumber()] = nullptr;
2821cfca06d7SDimitry Andric }
2822cfca06d7SDimitry Andric
282363faed5bSDimitry Andric // Splice the blocks into place.
282401095a5dSDimitry Andric MachineFunction::iterator InsertPos = F->begin();
2825eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n");
28265a5ac124SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) {
2827eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
282863faed5bSDimitry Andric : " ... ")
28295a5ac124SDimitry Andric << getBlockName(ChainBB) << "\n");
28305a5ac124SDimitry Andric if (InsertPos != MachineFunction::iterator(ChainBB))
283101095a5dSDimitry Andric F->splice(InsertPos, ChainBB);
283263faed5bSDimitry Andric else
283363faed5bSDimitry Andric ++InsertPos;
283463faed5bSDimitry Andric
283563faed5bSDimitry Andric // Update the terminator of the previous block.
28365a5ac124SDimitry Andric if (ChainBB == *FunctionChain.begin())
283763faed5bSDimitry Andric continue;
2838dd58ef01SDimitry Andric MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
283963faed5bSDimitry Andric
284063faed5bSDimitry Andric // FIXME: It would be awesome of updateTerminator would just return rather
284163faed5bSDimitry Andric // than assert when the branch cannot be analyzed in order to remove this
284263faed5bSDimitry Andric // boiler plate.
284363faed5bSDimitry Andric Cond.clear();
2844cfca06d7SDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
284501095a5dSDimitry Andric
2846b915e9e0SDimitry Andric #ifndef NDEBUG
2847b915e9e0SDimitry Andric if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2848b915e9e0SDimitry Andric // Given the exact block placement we chose, we may actually not _need_ to
2849b915e9e0SDimitry Andric // be able to edit PrevBB's terminator sequence, but not being _able_ to
2850b915e9e0SDimitry Andric // do that at this point is a bug.
2851b915e9e0SDimitry Andric assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2852b915e9e0SDimitry Andric !PrevBB->canFallThrough()) &&
2853b915e9e0SDimitry Andric "Unexpected block with un-analyzable fallthrough!");
2854b915e9e0SDimitry Andric Cond.clear();
2855b915e9e0SDimitry Andric TBB = FBB = nullptr;
2856b915e9e0SDimitry Andric }
2857b915e9e0SDimitry Andric #endif
2858b915e9e0SDimitry Andric
2859f8af5cf6SDimitry Andric // The "PrevBB" is not yet updated to reflect current code layout, so,
286001095a5dSDimitry Andric // o. it may fall-through to a block without explicit "goto" instruction
2861f8af5cf6SDimitry Andric // before layout, and no longer fall-through it after layout; or
2862f8af5cf6SDimitry Andric // o. just opposite.
2863f8af5cf6SDimitry Andric //
286401095a5dSDimitry Andric // analyzeBranch() may return erroneous value for FBB when these two
286501095a5dSDimitry Andric // situations take place. For the first scenario FBB is mistakenly set NULL;
286601095a5dSDimitry Andric // for the 2nd scenario, the FBB, which is expected to be NULL, is
286701095a5dSDimitry Andric // mistakenly pointing to "*BI".
286801095a5dSDimitry Andric // Thus, if the future change needs to use FBB before the layout is set, it
286901095a5dSDimitry Andric // has to correct FBB first by using the code similar to the following:
2870f8af5cf6SDimitry Andric //
287101095a5dSDimitry Andric // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
287201095a5dSDimitry Andric // PrevBB->updateTerminator();
287301095a5dSDimitry Andric // Cond.clear();
287401095a5dSDimitry Andric // TBB = FBB = nullptr;
287501095a5dSDimitry Andric // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
287601095a5dSDimitry Andric // // FIXME: This should never take place.
287701095a5dSDimitry Andric // TBB = FBB = nullptr;
287801095a5dSDimitry Andric // }
287901095a5dSDimitry Andric // }
2880cfca06d7SDimitry Andric if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
2881cfca06d7SDimitry Andric PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]);
2882cfca06d7SDimitry Andric }
288358b69754SDimitry Andric }
288463faed5bSDimitry Andric
288563faed5bSDimitry Andric // Fixup the last block.
288663faed5bSDimitry Andric Cond.clear();
2887cfca06d7SDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2888cfca06d7SDimitry Andric if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) {
2889cfca06d7SDimitry Andric MachineBasicBlock *PrevBB = &F->back();
2890cfca06d7SDimitry Andric PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]);
2891cfca06d7SDimitry Andric }
289263faed5bSDimitry Andric
289301095a5dSDimitry Andric BlockWorkList.clear();
289401095a5dSDimitry Andric EHPadWorkList.clear();
289501095a5dSDimitry Andric }
289601095a5dSDimitry Andric
optimizeBranches()289701095a5dSDimitry Andric void MachineBlockPlacement::optimizeBranches() {
289801095a5dSDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()];
2899cfca06d7SDimitry Andric SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
290001095a5dSDimitry Andric
290101095a5dSDimitry Andric // Now that all the basic blocks in the chain have the proper layout,
2902cfca06d7SDimitry Andric // make a final call to analyzeBranch with AllowModify set.
290301095a5dSDimitry Andric // Indeed, the target may be able to optimize the branches in a way we
290401095a5dSDimitry Andric // cannot because all branches may not be analyzable.
290501095a5dSDimitry Andric // E.g., the target may be able to remove an unconditional branch to
290601095a5dSDimitry Andric // a fallthrough when it occurs after predicated terminators.
290701095a5dSDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) {
290801095a5dSDimitry Andric Cond.clear();
2909cfca06d7SDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
291001095a5dSDimitry Andric if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
291101095a5dSDimitry Andric // If PrevBB has a two-way branch, try to re-order the branches
291201095a5dSDimitry Andric // such that we branch to the successor with higher probability first.
291301095a5dSDimitry Andric if (TBB && !Cond.empty() && FBB &&
291401095a5dSDimitry Andric MBPI->getEdgeProbability(ChainBB, FBB) >
291501095a5dSDimitry Andric MBPI->getEdgeProbability(ChainBB, TBB) &&
2916b915e9e0SDimitry Andric !TII->reverseBranchCondition(Cond)) {
2917eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Reverse order of the two branches: "
291801095a5dSDimitry Andric << getBlockName(ChainBB) << "\n");
2919eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Edge probability: "
292001095a5dSDimitry Andric << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
292101095a5dSDimitry Andric << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
292201095a5dSDimitry Andric DebugLoc dl; // FIXME: this is nowhere
2923b915e9e0SDimitry Andric TII->removeBranch(*ChainBB);
2924b915e9e0SDimitry Andric TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
292501095a5dSDimitry Andric }
292601095a5dSDimitry Andric }
292701095a5dSDimitry Andric }
292801095a5dSDimitry Andric }
292901095a5dSDimitry Andric
alignBlocks()293001095a5dSDimitry Andric void MachineBlockPlacement::alignBlocks() {
2931b61ab53cSDimitry Andric // Walk through the backedges of the function now that we have fully laid out
2932b61ab53cSDimitry Andric // the basic blocks and align the destination of each backedge. We don't rely
293358b69754SDimitry Andric // exclusively on the loop info here so that we can align backedges in
293458b69754SDimitry Andric // unnatural CFGs and backedges that were introduced purely because of the
293558b69754SDimitry Andric // loop rotations done during this layout pass.
2936e6d15924SDimitry Andric if (F->getFunction().hasMinSize() ||
2937e6d15924SDimitry Andric (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize()))
293863faed5bSDimitry Andric return;
293901095a5dSDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()];
294058b69754SDimitry Andric if (FunctionChain.begin() == FunctionChain.end())
294158b69754SDimitry Andric return; // Empty chain.
294263faed5bSDimitry Andric
294358b69754SDimitry Andric const BranchProbability ColdProb(1, 5); // 20%
294401095a5dSDimitry Andric BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
294558b69754SDimitry Andric BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
29465a5ac124SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) {
29475a5ac124SDimitry Andric if (ChainBB == *FunctionChain.begin())
29485a5ac124SDimitry Andric continue;
29495a5ac124SDimitry Andric
295058b69754SDimitry Andric // Don't align non-looping basic blocks. These are unlikely to execute
295158b69754SDimitry Andric // enough times to matter in practice. Note that we'll still handle
295258b69754SDimitry Andric // unnatural CFGs inside of a natural outer loop (the common case) and
295358b69754SDimitry Andric // rotated loops.
29545a5ac124SDimitry Andric MachineLoop *L = MLI->getLoopFor(ChainBB);
295558b69754SDimitry Andric if (!L)
295658b69754SDimitry Andric continue;
295758b69754SDimitry Andric
2958b1c73532SDimitry Andric const Align TLIAlign = TLI->getPrefLoopAlignment(L);
2959b1c73532SDimitry Andric unsigned MDAlign = 1;
2960b1c73532SDimitry Andric MDNode *LoopID = L->getLoopID();
2961b1c73532SDimitry Andric if (LoopID) {
2962ac9a064cSDimitry Andric for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
2963ac9a064cSDimitry Andric MDNode *MD = dyn_cast<MDNode>(MDO);
2964b1c73532SDimitry Andric if (MD == nullptr)
2965b1c73532SDimitry Andric continue;
2966b1c73532SDimitry Andric MDString *S = dyn_cast<MDString>(MD->getOperand(0));
2967b1c73532SDimitry Andric if (S == nullptr)
2968b1c73532SDimitry Andric continue;
2969b1c73532SDimitry Andric if (S->getString() == "llvm.loop.align") {
2970b1c73532SDimitry Andric assert(MD->getNumOperands() == 2 &&
2971b1c73532SDimitry Andric "per-loop align metadata should have two operands.");
2972b1c73532SDimitry Andric MDAlign =
2973b1c73532SDimitry Andric mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
2974b1c73532SDimitry Andric assert(MDAlign >= 1 && "per-loop align value must be positive.");
2975b1c73532SDimitry Andric }
2976b1c73532SDimitry Andric }
2977b1c73532SDimitry Andric }
2978b1c73532SDimitry Andric
2979b1c73532SDimitry Andric // Use max of the TLIAlign and MDAlign
2980b1c73532SDimitry Andric const Align LoopAlign = std::max(TLIAlign, Align(MDAlign));
2981b1c73532SDimitry Andric if (LoopAlign == 1)
298267c32a98SDimitry Andric continue; // Don't care about loop alignment.
298367c32a98SDimitry Andric
298458b69754SDimitry Andric // If the block is cold relative to the function entry don't waste space
298558b69754SDimitry Andric // aligning it.
29865a5ac124SDimitry Andric BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
298758b69754SDimitry Andric if (Freq < WeightedEntryFreq)
298858b69754SDimitry Andric continue;
298958b69754SDimitry Andric
299058b69754SDimitry Andric // If the block is cold relative to its loop header, don't align it
299158b69754SDimitry Andric // regardless of what edges into the block exist.
299258b69754SDimitry Andric MachineBasicBlock *LoopHeader = L->getHeader();
299358b69754SDimitry Andric BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
299458b69754SDimitry Andric if (Freq < (LoopHeaderFreq * ColdProb))
299558b69754SDimitry Andric continue;
299658b69754SDimitry Andric
2997706b4fc4SDimitry Andric // If the global profiles indicates so, don't align it.
2998cfca06d7SDimitry Andric if (llvm::shouldOptimizeForSize(ChainBB, PSI, MBFI.get()) &&
2999706b4fc4SDimitry Andric !TLI->alignLoopsWithOptSize())
3000706b4fc4SDimitry Andric continue;
3001706b4fc4SDimitry Andric
300258b69754SDimitry Andric // Check for the existence of a non-layout predecessor which would benefit
300358b69754SDimitry Andric // from aligning this block.
30045a5ac124SDimitry Andric MachineBasicBlock *LayoutPred =
30055a5ac124SDimitry Andric &*std::prev(MachineFunction::iterator(ChainBB));
300658b69754SDimitry Andric
30076f8fc217SDimitry Andric auto DetermineMaxAlignmentPadding = [&]() {
30086f8fc217SDimitry Andric // Set the maximum bytes allowed to be emitted for alignment.
30096f8fc217SDimitry Andric unsigned MaxBytes;
30106f8fc217SDimitry Andric if (MaxBytesForAlignmentOverride.getNumOccurrences() > 0)
30116f8fc217SDimitry Andric MaxBytes = MaxBytesForAlignmentOverride;
30126f8fc217SDimitry Andric else
30136f8fc217SDimitry Andric MaxBytes = TLI->getMaxPermittedBytesForAlignment(ChainBB);
30146f8fc217SDimitry Andric ChainBB->setMaxBytesForAlignment(MaxBytes);
30156f8fc217SDimitry Andric };
30166f8fc217SDimitry Andric
301758b69754SDimitry Andric // Force alignment if all the predecessors are jumps. We already checked
301858b69754SDimitry Andric // that the block isn't cold above.
30195a5ac124SDimitry Andric if (!LayoutPred->isSuccessor(ChainBB)) {
3020b1c73532SDimitry Andric ChainBB->setAlignment(LoopAlign);
30216f8fc217SDimitry Andric DetermineMaxAlignmentPadding();
302258b69754SDimitry Andric continue;
302358b69754SDimitry Andric }
302458b69754SDimitry Andric
302558b69754SDimitry Andric // Align this block if the layout predecessor's edge into this block is
30264a16efa3SDimitry Andric // cold relative to the block. When this is true, other predecessors make up
302758b69754SDimitry Andric // all of the hot entries into the block and thus alignment is likely to be
302858b69754SDimitry Andric // important.
30295a5ac124SDimitry Andric BranchProbability LayoutProb =
30305a5ac124SDimitry Andric MBPI->getEdgeProbability(LayoutPred, ChainBB);
303158b69754SDimitry Andric BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
30326f8fc217SDimitry Andric if (LayoutEdgeFreq <= (Freq * ColdProb)) {
3033b1c73532SDimitry Andric ChainBB->setAlignment(LoopAlign);
30346f8fc217SDimitry Andric DetermineMaxAlignmentPadding();
30356f8fc217SDimitry Andric }
3036b61ab53cSDimitry Andric }
303763faed5bSDimitry Andric }
303863faed5bSDimitry Andric
3039b915e9e0SDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
3040b915e9e0SDimitry Andric /// it was duplicated into its chain predecessor and removed.
3041b915e9e0SDimitry Andric /// \p BB - Basic block that may be duplicated.
3042b915e9e0SDimitry Andric ///
3043b915e9e0SDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB.
3044b915e9e0SDimitry Andric /// Updated to be the chain end if LPred is removed.
3045b915e9e0SDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
3046b915e9e0SDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
3047b915e9e0SDimitry Andric /// Used to identify which blocks to update predecessor
3048b915e9e0SDimitry Andric /// counts.
3049b915e9e0SDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
3050b915e9e0SDimitry Andric /// chosen in the given order due to unnatural CFG
3051b915e9e0SDimitry Andric /// only needed if \p BB is removed and
3052b915e9e0SDimitry Andric /// \p PrevUnplacedBlockIt pointed to \p BB.
3053b915e9e0SDimitry Andric /// @return true if \p BB was removed.
repeatedlyTailDuplicateBlock(MachineBasicBlock * BB,MachineBasicBlock * & LPred,const MachineBasicBlock * LoopHeaderBB,BlockChain & Chain,BlockFilterSet * BlockFilter,MachineFunction::iterator & PrevUnplacedBlockIt,BlockFilterSet::iterator & PrevUnplacedBlockInFilterIt)3054b915e9e0SDimitry Andric bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
3055b915e9e0SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *&LPred,
3056ac9a064cSDimitry Andric const MachineBasicBlock *LoopHeaderBB, BlockChain &Chain,
3057ac9a064cSDimitry Andric BlockFilterSet *BlockFilter, MachineFunction::iterator &PrevUnplacedBlockIt,
3058ac9a064cSDimitry Andric BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt) {
3059b915e9e0SDimitry Andric bool Removed, DuplicatedToLPred;
3060b915e9e0SDimitry Andric bool DuplicatedToOriginalLPred;
3061ac9a064cSDimitry Andric Removed = maybeTailDuplicateBlock(
3062ac9a064cSDimitry Andric BB, LPred, Chain, BlockFilter, PrevUnplacedBlockIt,
3063ac9a064cSDimitry Andric PrevUnplacedBlockInFilterIt, DuplicatedToLPred);
3064b915e9e0SDimitry Andric if (!Removed)
3065b915e9e0SDimitry Andric return false;
3066b915e9e0SDimitry Andric DuplicatedToOriginalLPred = DuplicatedToLPred;
3067b915e9e0SDimitry Andric // Iteratively try to duplicate again. It can happen that a block that is
3068b915e9e0SDimitry Andric // duplicated into is still small enough to be duplicated again.
3069b915e9e0SDimitry Andric // No need to call markBlockSuccessors in this case, as the blocks being
3070b915e9e0SDimitry Andric // duplicated from here on are already scheduled.
3071cfca06d7SDimitry Andric while (DuplicatedToLPred && Removed) {
3072b915e9e0SDimitry Andric MachineBasicBlock *DupBB, *DupPred;
3073b915e9e0SDimitry Andric // The removal callback causes Chain.end() to be updated when a block is
3074b915e9e0SDimitry Andric // removed. On the first pass through the loop, the chain end should be the
3075b915e9e0SDimitry Andric // same as it was on function entry. On subsequent passes, because we are
3076b915e9e0SDimitry Andric // duplicating the block at the end of the chain, if it is removed the
3077b915e9e0SDimitry Andric // chain will have shrunk by one block.
3078b915e9e0SDimitry Andric BlockChain::iterator ChainEnd = Chain.end();
3079b915e9e0SDimitry Andric DupBB = *(--ChainEnd);
3080b915e9e0SDimitry Andric // Now try to duplicate again.
3081b915e9e0SDimitry Andric if (ChainEnd == Chain.begin())
3082b915e9e0SDimitry Andric break;
3083b915e9e0SDimitry Andric DupPred = *std::prev(ChainEnd);
3084ac9a064cSDimitry Andric Removed = maybeTailDuplicateBlock(
3085ac9a064cSDimitry Andric DupBB, DupPred, Chain, BlockFilter, PrevUnplacedBlockIt,
3086ac9a064cSDimitry Andric PrevUnplacedBlockInFilterIt, DuplicatedToLPred);
3087b915e9e0SDimitry Andric }
3088b915e9e0SDimitry Andric // If BB was duplicated into LPred, it is now scheduled. But because it was
3089b915e9e0SDimitry Andric // removed, markChainSuccessors won't be called for its chain. Instead we
3090b915e9e0SDimitry Andric // call markBlockSuccessors for LPred to achieve the same effect. This must go
3091b915e9e0SDimitry Andric // at the end because repeating the tail duplication can increase the number
3092b915e9e0SDimitry Andric // of unscheduled predecessors.
3093b915e9e0SDimitry Andric LPred = *std::prev(Chain.end());
3094b915e9e0SDimitry Andric if (DuplicatedToOriginalLPred)
3095b915e9e0SDimitry Andric markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
3096b915e9e0SDimitry Andric return true;
3097b915e9e0SDimitry Andric }
3098b915e9e0SDimitry Andric
3099b915e9e0SDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable.
3100b915e9e0SDimitry Andric /// \p BB - Basic block that may be duplicated
3101b915e9e0SDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB
3102b915e9e0SDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
3103b915e9e0SDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
3104b915e9e0SDimitry Andric /// Used to identify which blocks to update predecessor
3105b915e9e0SDimitry Andric /// counts.
3106b915e9e0SDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
3107b915e9e0SDimitry Andric /// chosen in the given order due to unnatural CFG
3108b915e9e0SDimitry Andric /// only needed if \p BB is removed and
3109b915e9e0SDimitry Andric /// \p PrevUnplacedBlockIt pointed to \p BB.
3110cfca06d7SDimitry Andric /// \p DuplicatedToLPred - True if the block was duplicated into LPred.
3111b915e9e0SDimitry Andric /// \return - True if the block was duplicated into all preds and removed.
maybeTailDuplicateBlock(MachineBasicBlock * BB,MachineBasicBlock * LPred,BlockChain & Chain,BlockFilterSet * BlockFilter,MachineFunction::iterator & PrevUnplacedBlockIt,BlockFilterSet::iterator & PrevUnplacedBlockInFilterIt,bool & DuplicatedToLPred)3112b915e9e0SDimitry Andric bool MachineBlockPlacement::maybeTailDuplicateBlock(
3113ac9a064cSDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *LPred, BlockChain &Chain,
3114ac9a064cSDimitry Andric BlockFilterSet *BlockFilter, MachineFunction::iterator &PrevUnplacedBlockIt,
3115ac9a064cSDimitry Andric BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
3116b915e9e0SDimitry Andric bool &DuplicatedToLPred) {
3117b915e9e0SDimitry Andric DuplicatedToLPred = false;
311871d5a254SDimitry Andric if (!shouldTailDuplicate(BB))
311971d5a254SDimitry Andric return false;
312071d5a254SDimitry Andric
3121eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber()
3122eb11fae6SDimitry Andric << "\n");
312371d5a254SDimitry Andric
3124b915e9e0SDimitry Andric // This has to be a callback because none of it can be done after
3125b915e9e0SDimitry Andric // BB is deleted.
3126b915e9e0SDimitry Andric bool Removed = false;
3127b915e9e0SDimitry Andric auto RemovalCallback =
3128b915e9e0SDimitry Andric [&](MachineBasicBlock *RemBB) {
3129b915e9e0SDimitry Andric // Signal to outer function
3130b915e9e0SDimitry Andric Removed = true;
3131b915e9e0SDimitry Andric
3132b915e9e0SDimitry Andric // Conservative default.
3133b915e9e0SDimitry Andric bool InWorkList = true;
3134b915e9e0SDimitry Andric // Remove from the Chain and Chain Map
3135b915e9e0SDimitry Andric if (BlockToChain.count(RemBB)) {
3136b915e9e0SDimitry Andric BlockChain *Chain = BlockToChain[RemBB];
3137b915e9e0SDimitry Andric InWorkList = Chain->UnscheduledPredecessors == 0;
3138b915e9e0SDimitry Andric Chain->remove(RemBB);
3139b915e9e0SDimitry Andric BlockToChain.erase(RemBB);
3140b915e9e0SDimitry Andric }
3141b915e9e0SDimitry Andric
3142b915e9e0SDimitry Andric // Handle the unplaced block iterator
3143b915e9e0SDimitry Andric if (&(*PrevUnplacedBlockIt) == RemBB) {
3144b915e9e0SDimitry Andric PrevUnplacedBlockIt++;
3145b915e9e0SDimitry Andric }
3146b915e9e0SDimitry Andric
3147b915e9e0SDimitry Andric // Handle the Work Lists
3148b915e9e0SDimitry Andric if (InWorkList) {
3149b915e9e0SDimitry Andric SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
3150b915e9e0SDimitry Andric if (RemBB->isEHPad())
3151b915e9e0SDimitry Andric RemoveList = EHPadWorkList;
3152b1c73532SDimitry Andric llvm::erase(RemoveList, RemBB);
3153b915e9e0SDimitry Andric }
3154b915e9e0SDimitry Andric
3155b915e9e0SDimitry Andric // Handle the filter set
3156b915e9e0SDimitry Andric if (BlockFilter) {
3157ac9a064cSDimitry Andric auto It = llvm::find(*BlockFilter, RemBB);
3158ac9a064cSDimitry Andric // Erase RemBB from BlockFilter, and keep PrevUnplacedBlockInFilterIt
3159ac9a064cSDimitry Andric // pointing to the same element as before.
3160ac9a064cSDimitry Andric if (It != BlockFilter->end()) {
3161ac9a064cSDimitry Andric if (It < PrevUnplacedBlockInFilterIt) {
3162ac9a064cSDimitry Andric const MachineBasicBlock *PrevBB = *PrevUnplacedBlockInFilterIt;
3163ac9a064cSDimitry Andric // BlockFilter is a SmallVector so all elements after RemBB are
3164ac9a064cSDimitry Andric // shifted to the front by 1 after its deletion.
3165ac9a064cSDimitry Andric auto Distance = PrevUnplacedBlockInFilterIt - It - 1;
3166ac9a064cSDimitry Andric PrevUnplacedBlockInFilterIt = BlockFilter->erase(It) + Distance;
3167ac9a064cSDimitry Andric assert(*PrevUnplacedBlockInFilterIt == PrevBB);
3168ac9a064cSDimitry Andric (void)PrevBB;
3169ac9a064cSDimitry Andric } else if (It == PrevUnplacedBlockInFilterIt)
3170ac9a064cSDimitry Andric // The block pointed by PrevUnplacedBlockInFilterIt is erased, we
3171ac9a064cSDimitry Andric // have to set it to the next element.
3172ac9a064cSDimitry Andric PrevUnplacedBlockInFilterIt = BlockFilter->erase(It);
3173ac9a064cSDimitry Andric else
3174ac9a064cSDimitry Andric BlockFilter->erase(It);
3175ac9a064cSDimitry Andric }
3176b915e9e0SDimitry Andric }
3177b915e9e0SDimitry Andric
3178b915e9e0SDimitry Andric // Remove the block from loop info.
3179b915e9e0SDimitry Andric MLI->removeBlock(RemBB);
3180b915e9e0SDimitry Andric if (RemBB == PreferredLoopExit)
3181b915e9e0SDimitry Andric PreferredLoopExit = nullptr;
3182b915e9e0SDimitry Andric
3183eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: "
3184b915e9e0SDimitry Andric << getBlockName(RemBB) << "\n");
3185b915e9e0SDimitry Andric };
3186b915e9e0SDimitry Andric auto RemovalCallbackRef =
3187044eb2f6SDimitry Andric function_ref<void(MachineBasicBlock*)>(RemovalCallback);
3188b915e9e0SDimitry Andric
3189b915e9e0SDimitry Andric SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
319071d5a254SDimitry Andric bool IsSimple = TailDup.isSimpleBB(BB);
3191cfca06d7SDimitry Andric SmallVector<MachineBasicBlock *, 8> CandidatePreds;
3192cfca06d7SDimitry Andric SmallVectorImpl<MachineBasicBlock *> *CandidatePtr = nullptr;
3193cfca06d7SDimitry Andric if (F->getFunction().hasProfileData()) {
3194cfca06d7SDimitry Andric // We can do partial duplication with precise profile information.
3195cfca06d7SDimitry Andric findDuplicateCandidates(CandidatePreds, BB, BlockFilter);
3196cfca06d7SDimitry Andric if (CandidatePreds.size() == 0)
3197cfca06d7SDimitry Andric return false;
3198cfca06d7SDimitry Andric if (CandidatePreds.size() < BB->pred_size())
3199cfca06d7SDimitry Andric CandidatePtr = &CandidatePreds;
3200cfca06d7SDimitry Andric }
3201cfca06d7SDimitry Andric TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, &DuplicatedPreds,
3202cfca06d7SDimitry Andric &RemovalCallbackRef, CandidatePtr);
3203b915e9e0SDimitry Andric
3204b915e9e0SDimitry Andric // Update UnscheduledPredecessors to reflect tail-duplication.
3205b915e9e0SDimitry Andric DuplicatedToLPred = false;
3206b915e9e0SDimitry Andric for (MachineBasicBlock *Pred : DuplicatedPreds) {
3207b915e9e0SDimitry Andric // We're only looking for unscheduled predecessors that match the filter.
3208b915e9e0SDimitry Andric BlockChain* PredChain = BlockToChain[Pred];
3209b915e9e0SDimitry Andric if (Pred == LPred)
3210b915e9e0SDimitry Andric DuplicatedToLPred = true;
3211b915e9e0SDimitry Andric if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
3212b915e9e0SDimitry Andric || PredChain == &Chain)
3213b915e9e0SDimitry Andric continue;
3214b915e9e0SDimitry Andric for (MachineBasicBlock *NewSucc : Pred->successors()) {
3215b915e9e0SDimitry Andric if (BlockFilter && !BlockFilter->count(NewSucc))
3216b915e9e0SDimitry Andric continue;
3217b915e9e0SDimitry Andric BlockChain *NewChain = BlockToChain[NewSucc];
3218b915e9e0SDimitry Andric if (NewChain != &Chain && NewChain != PredChain)
3219b915e9e0SDimitry Andric NewChain->UnscheduledPredecessors++;
3220b915e9e0SDimitry Andric }
3221b915e9e0SDimitry Andric }
3222b915e9e0SDimitry Andric return Removed;
3223b915e9e0SDimitry Andric }
3224b915e9e0SDimitry Andric
3225cfca06d7SDimitry Andric // Count the number of actual machine instructions.
countMBBInstruction(MachineBasicBlock * MBB)3226cfca06d7SDimitry Andric static uint64_t countMBBInstruction(MachineBasicBlock *MBB) {
3227cfca06d7SDimitry Andric uint64_t InstrCount = 0;
3228cfca06d7SDimitry Andric for (MachineInstr &MI : *MBB) {
3229cfca06d7SDimitry Andric if (!MI.isPHI() && !MI.isMetaInstruction())
3230cfca06d7SDimitry Andric InstrCount += 1;
3231cfca06d7SDimitry Andric }
3232cfca06d7SDimitry Andric return InstrCount;
3233cfca06d7SDimitry Andric }
3234cfca06d7SDimitry Andric
3235cfca06d7SDimitry Andric // The size cost of duplication is the instruction size of the duplicated block.
3236cfca06d7SDimitry Andric // So we should scale the threshold accordingly. But the instruction size is not
3237cfca06d7SDimitry Andric // available on all targets, so we use the number of instructions instead.
scaleThreshold(MachineBasicBlock * BB)3238cfca06d7SDimitry Andric BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) {
3239b1c73532SDimitry Andric return BlockFrequency(DupThreshold.getFrequency() * countMBBInstruction(BB));
3240cfca06d7SDimitry Andric }
3241cfca06d7SDimitry Andric
3242cfca06d7SDimitry Andric // Returns true if BB is Pred's best successor.
isBestSuccessor(MachineBasicBlock * BB,MachineBasicBlock * Pred,BlockFilterSet * BlockFilter)3243cfca06d7SDimitry Andric bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB,
3244cfca06d7SDimitry Andric MachineBasicBlock *Pred,
3245cfca06d7SDimitry Andric BlockFilterSet *BlockFilter) {
3246cfca06d7SDimitry Andric if (BB == Pred)
3247cfca06d7SDimitry Andric return false;
3248cfca06d7SDimitry Andric if (BlockFilter && !BlockFilter->count(Pred))
3249cfca06d7SDimitry Andric return false;
3250cfca06d7SDimitry Andric BlockChain *PredChain = BlockToChain[Pred];
3251cfca06d7SDimitry Andric if (PredChain && (Pred != *std::prev(PredChain->end())))
3252cfca06d7SDimitry Andric return false;
3253cfca06d7SDimitry Andric
3254cfca06d7SDimitry Andric // Find the successor with largest probability excluding BB.
3255cfca06d7SDimitry Andric BranchProbability BestProb = BranchProbability::getZero();
3256cfca06d7SDimitry Andric for (MachineBasicBlock *Succ : Pred->successors())
3257cfca06d7SDimitry Andric if (Succ != BB) {
3258cfca06d7SDimitry Andric if (BlockFilter && !BlockFilter->count(Succ))
3259cfca06d7SDimitry Andric continue;
3260cfca06d7SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ];
3261cfca06d7SDimitry Andric if (SuccChain && (Succ != *SuccChain->begin()))
3262cfca06d7SDimitry Andric continue;
3263cfca06d7SDimitry Andric BranchProbability SuccProb = MBPI->getEdgeProbability(Pred, Succ);
3264cfca06d7SDimitry Andric if (SuccProb > BestProb)
3265cfca06d7SDimitry Andric BestProb = SuccProb;
3266cfca06d7SDimitry Andric }
3267cfca06d7SDimitry Andric
3268cfca06d7SDimitry Andric BranchProbability BBProb = MBPI->getEdgeProbability(Pred, BB);
3269cfca06d7SDimitry Andric if (BBProb <= BestProb)
3270cfca06d7SDimitry Andric return false;
3271cfca06d7SDimitry Andric
3272cfca06d7SDimitry Andric // Compute the number of reduced taken branches if Pred falls through to BB
3273cfca06d7SDimitry Andric // instead of another successor. Then compare it with threshold.
3274b60736ecSDimitry Andric BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
3275cfca06d7SDimitry Andric BlockFrequency Gain = PredFreq * (BBProb - BestProb);
3276cfca06d7SDimitry Andric return Gain > scaleThreshold(BB);
3277cfca06d7SDimitry Andric }
3278cfca06d7SDimitry Andric
3279cfca06d7SDimitry Andric // Find out the predecessors of BB and BB can be beneficially duplicated into
3280cfca06d7SDimitry Andric // them.
findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock * > & Candidates,MachineBasicBlock * BB,BlockFilterSet * BlockFilter)3281cfca06d7SDimitry Andric void MachineBlockPlacement::findDuplicateCandidates(
3282cfca06d7SDimitry Andric SmallVectorImpl<MachineBasicBlock *> &Candidates,
3283cfca06d7SDimitry Andric MachineBasicBlock *BB,
3284cfca06d7SDimitry Andric BlockFilterSet *BlockFilter) {
3285cfca06d7SDimitry Andric MachineBasicBlock *Fallthrough = nullptr;
3286cfca06d7SDimitry Andric BranchProbability DefaultBranchProb = BranchProbability::getZero();
3287cfca06d7SDimitry Andric BlockFrequency BBDupThreshold(scaleThreshold(BB));
3288b60736ecSDimitry Andric SmallVector<MachineBasicBlock *, 8> Preds(BB->predecessors());
3289b60736ecSDimitry Andric SmallVector<MachineBasicBlock *, 8> Succs(BB->successors());
3290cfca06d7SDimitry Andric
3291cfca06d7SDimitry Andric // Sort for highest frequency.
3292cfca06d7SDimitry Andric auto CmpSucc = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3293cfca06d7SDimitry Andric return MBPI->getEdgeProbability(BB, A) > MBPI->getEdgeProbability(BB, B);
3294cfca06d7SDimitry Andric };
3295cfca06d7SDimitry Andric auto CmpPred = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3296cfca06d7SDimitry Andric return MBFI->getBlockFreq(A) > MBFI->getBlockFreq(B);
3297cfca06d7SDimitry Andric };
3298cfca06d7SDimitry Andric llvm::stable_sort(Succs, CmpSucc);
3299cfca06d7SDimitry Andric llvm::stable_sort(Preds, CmpPred);
3300cfca06d7SDimitry Andric
3301cfca06d7SDimitry Andric auto SuccIt = Succs.begin();
3302cfca06d7SDimitry Andric if (SuccIt != Succs.end()) {
3303cfca06d7SDimitry Andric DefaultBranchProb = MBPI->getEdgeProbability(BB, *SuccIt).getCompl();
3304cfca06d7SDimitry Andric }
3305cfca06d7SDimitry Andric
3306cfca06d7SDimitry Andric // For each predecessors of BB, compute the benefit of duplicating BB,
3307cfca06d7SDimitry Andric // if it is larger than the threshold, add it into Candidates.
3308cfca06d7SDimitry Andric //
3309cfca06d7SDimitry Andric // If we have following control flow.
3310cfca06d7SDimitry Andric //
3311cfca06d7SDimitry Andric // PB1 PB2 PB3 PB4
3312cfca06d7SDimitry Andric // \ | / /\
3313cfca06d7SDimitry Andric // \ | / / \
3314cfca06d7SDimitry Andric // \ |/ / \
3315cfca06d7SDimitry Andric // BB----/ OB
3316cfca06d7SDimitry Andric // /\
3317cfca06d7SDimitry Andric // / \
3318cfca06d7SDimitry Andric // SB1 SB2
3319cfca06d7SDimitry Andric //
3320cfca06d7SDimitry Andric // And it can be partially duplicated as
3321cfca06d7SDimitry Andric //
3322cfca06d7SDimitry Andric // PB2+BB
3323cfca06d7SDimitry Andric // | PB1 PB3 PB4
3324cfca06d7SDimitry Andric // | | / /\
3325cfca06d7SDimitry Andric // | | / / \
3326cfca06d7SDimitry Andric // | |/ / \
3327cfca06d7SDimitry Andric // | BB----/ OB
3328cfca06d7SDimitry Andric // |\ /|
3329cfca06d7SDimitry Andric // | X |
3330cfca06d7SDimitry Andric // |/ \|
3331cfca06d7SDimitry Andric // SB2 SB1
3332cfca06d7SDimitry Andric //
3333cfca06d7SDimitry Andric // The benefit of duplicating into a predecessor is defined as
3334cfca06d7SDimitry Andric // Orig_taken_branch - Duplicated_taken_branch
3335cfca06d7SDimitry Andric //
3336cfca06d7SDimitry Andric // The Orig_taken_branch is computed with the assumption that predecessor
3337cfca06d7SDimitry Andric // jumps to BB and the most possible successor is laid out after BB.
3338cfca06d7SDimitry Andric //
3339cfca06d7SDimitry Andric // The Duplicated_taken_branch is computed with the assumption that BB is
3340cfca06d7SDimitry Andric // duplicated into PB, and one successor is layout after it (SB1 for PB1 and
3341cfca06d7SDimitry Andric // SB2 for PB2 in our case). If there is no available successor, the combined
3342cfca06d7SDimitry Andric // block jumps to all BB's successor, like PB3 in this example.
3343cfca06d7SDimitry Andric //
3344cfca06d7SDimitry Andric // If a predecessor has multiple successors, so BB can't be duplicated into
3345cfca06d7SDimitry Andric // it. But it can beneficially fall through to BB, and duplicate BB into other
3346cfca06d7SDimitry Andric // predecessors.
3347cfca06d7SDimitry Andric for (MachineBasicBlock *Pred : Preds) {
3348b60736ecSDimitry Andric BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
3349cfca06d7SDimitry Andric
3350cfca06d7SDimitry Andric if (!TailDup.canTailDuplicate(BB, Pred)) {
3351cfca06d7SDimitry Andric // BB can't be duplicated into Pred, but it is possible to be layout
3352cfca06d7SDimitry Andric // below Pred.
3353cfca06d7SDimitry Andric if (!Fallthrough && isBestSuccessor(BB, Pred, BlockFilter)) {
3354cfca06d7SDimitry Andric Fallthrough = Pred;
3355cfca06d7SDimitry Andric if (SuccIt != Succs.end())
3356cfca06d7SDimitry Andric SuccIt++;
3357cfca06d7SDimitry Andric }
3358cfca06d7SDimitry Andric continue;
3359cfca06d7SDimitry Andric }
3360cfca06d7SDimitry Andric
3361cfca06d7SDimitry Andric BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb;
3362cfca06d7SDimitry Andric BlockFrequency DupCost;
3363cfca06d7SDimitry Andric if (SuccIt == Succs.end()) {
3364cfca06d7SDimitry Andric // Jump to all successors;
3365cfca06d7SDimitry Andric if (Succs.size() > 0)
3366cfca06d7SDimitry Andric DupCost += PredFreq;
3367cfca06d7SDimitry Andric } else {
3368cfca06d7SDimitry Andric // Fallthrough to *SuccIt, jump to all other successors;
3369cfca06d7SDimitry Andric DupCost += PredFreq;
3370cfca06d7SDimitry Andric DupCost -= PredFreq * MBPI->getEdgeProbability(BB, *SuccIt);
3371cfca06d7SDimitry Andric }
3372cfca06d7SDimitry Andric
3373cfca06d7SDimitry Andric assert(OrigCost >= DupCost);
3374cfca06d7SDimitry Andric OrigCost -= DupCost;
3375cfca06d7SDimitry Andric if (OrigCost > BBDupThreshold) {
3376cfca06d7SDimitry Andric Candidates.push_back(Pred);
3377cfca06d7SDimitry Andric if (SuccIt != Succs.end())
3378cfca06d7SDimitry Andric SuccIt++;
3379cfca06d7SDimitry Andric }
3380cfca06d7SDimitry Andric }
3381cfca06d7SDimitry Andric
3382cfca06d7SDimitry Andric // No predecessors can optimally fallthrough to BB.
3383cfca06d7SDimitry Andric // So we can change one duplication into fallthrough.
3384cfca06d7SDimitry Andric if (!Fallthrough) {
3385cfca06d7SDimitry Andric if ((Candidates.size() < Preds.size()) && (Candidates.size() > 0)) {
3386cfca06d7SDimitry Andric Candidates[0] = Candidates.back();
3387cfca06d7SDimitry Andric Candidates.pop_back();
3388cfca06d7SDimitry Andric }
3389cfca06d7SDimitry Andric }
3390cfca06d7SDimitry Andric }
3391cfca06d7SDimitry Andric
initDupThreshold()3392cfca06d7SDimitry Andric void MachineBlockPlacement::initDupThreshold() {
3393b1c73532SDimitry Andric DupThreshold = BlockFrequency(0);
3394cfca06d7SDimitry Andric if (!F->getFunction().hasProfileData())
3395cfca06d7SDimitry Andric return;
3396cfca06d7SDimitry Andric
3397b60736ecSDimitry Andric // We prefer to use prifile count.
3398b60736ecSDimitry Andric uint64_t HotThreshold = PSI->getOrCompHotCountThreshold();
3399b60736ecSDimitry Andric if (HotThreshold != UINT64_MAX) {
3400b60736ecSDimitry Andric UseProfileCount = true;
3401b1c73532SDimitry Andric DupThreshold =
3402b1c73532SDimitry Andric BlockFrequency(HotThreshold * TailDupProfilePercentThreshold / 100);
3403b60736ecSDimitry Andric return;
3404b60736ecSDimitry Andric }
3405b60736ecSDimitry Andric
3406b60736ecSDimitry Andric // Profile count is not available, we can use block frequency instead.
3407b1c73532SDimitry Andric BlockFrequency MaxFreq = BlockFrequency(0);
3408cfca06d7SDimitry Andric for (MachineBasicBlock &MBB : *F) {
3409cfca06d7SDimitry Andric BlockFrequency Freq = MBFI->getBlockFreq(&MBB);
3410cfca06d7SDimitry Andric if (Freq > MaxFreq)
3411cfca06d7SDimitry Andric MaxFreq = Freq;
3412cfca06d7SDimitry Andric }
3413cfca06d7SDimitry Andric
3414cfca06d7SDimitry Andric BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
3415b1c73532SDimitry Andric DupThreshold = BlockFrequency(MaxFreq * ThresholdProb);
3416b60736ecSDimitry Andric UseProfileCount = false;
3417cfca06d7SDimitry Andric }
3418cfca06d7SDimitry Andric
runOnMachineFunction(MachineFunction & MF)341901095a5dSDimitry Andric bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
3420044eb2f6SDimitry Andric if (skipFunction(MF.getFunction()))
342101095a5dSDimitry Andric return false;
342201095a5dSDimitry Andric
342363faed5bSDimitry Andric // Check for single-block functions and skip them.
342401095a5dSDimitry Andric if (std::next(MF.begin()) == MF.end())
34255ca98fd9SDimitry Andric return false;
34265ca98fd9SDimitry Andric
342701095a5dSDimitry Andric F = &MF;
3428ac9a064cSDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
3429cfca06d7SDimitry Andric MBFI = std::make_unique<MBFIWrapper>(
3430ac9a064cSDimitry Andric getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI());
3431ac9a064cSDimitry Andric MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
343201095a5dSDimitry Andric TII = MF.getSubtarget().getInstrInfo();
343301095a5dSDimitry Andric TLI = MF.getSubtarget().getTargetLowering();
343471d5a254SDimitry Andric MPDT = nullptr;
3435706b4fc4SDimitry Andric PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
3436b915e9e0SDimitry Andric
3437cfca06d7SDimitry Andric initDupThreshold();
3438cfca06d7SDimitry Andric
3439b915e9e0SDimitry Andric // Initialize PreferredLoopExit to nullptr here since it may never be set if
3440b915e9e0SDimitry Andric // there are no MachineLoops.
3441b915e9e0SDimitry Andric PreferredLoopExit = nullptr;
3442b915e9e0SDimitry Andric
3443b5630dbaSDimitry Andric assert(BlockToChain.empty() &&
3444b5630dbaSDimitry Andric "BlockToChain map should be empty before starting placement.");
3445b5630dbaSDimitry Andric assert(ComputedEdges.empty() &&
3446b5630dbaSDimitry Andric "Computed Edge map should be empty before starting placement.");
344771d5a254SDimitry Andric
34486b3f41edSDimitry Andric unsigned TailDupSize = TailDupPlacementThreshold;
34496b3f41edSDimitry Andric // If only the aggressive threshold is explicitly set, use it.
34506b3f41edSDimitry Andric if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
34516b3f41edSDimitry Andric TailDupPlacementThreshold.getNumOccurrences() == 0)
34526b3f41edSDimitry Andric TailDupSize = TailDupPlacementAggressiveThreshold;
34536b3f41edSDimitry Andric
34546b3f41edSDimitry Andric TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
3455eb11fae6SDimitry Andric // For aggressive optimization, we can adjust some thresholds to be less
34566b3f41edSDimitry Andric // conservative.
3457b1c73532SDimitry Andric if (PassConfig->getOptLevel() >= CodeGenOptLevel::Aggressive) {
34586b3f41edSDimitry Andric // At O3 we should be more willing to copy blocks for tail duplication. This
34596b3f41edSDimitry Andric // increases size pressure, so we only do it at O3
34606b3f41edSDimitry Andric // Do this unless only the regular threshold is explicitly set.
34616b3f41edSDimitry Andric if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
34626b3f41edSDimitry Andric TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
34636b3f41edSDimitry Andric TailDupSize = TailDupPlacementAggressiveThreshold;
34646b3f41edSDimitry Andric }
34656b3f41edSDimitry Andric
3466344a3780SDimitry Andric // If there's no threshold provided through options, query the target
3467344a3780SDimitry Andric // information for a threshold instead.
3468344a3780SDimitry Andric if (TailDupPlacementThreshold.getNumOccurrences() == 0 &&
3469b1c73532SDimitry Andric (PassConfig->getOptLevel() < CodeGenOptLevel::Aggressive ||
3470344a3780SDimitry Andric TailDupPlacementAggressiveThreshold.getNumOccurrences() == 0))
3471344a3780SDimitry Andric TailDupSize = TII->getTailDuplicateSize(PassConfig->getOptLevel());
3472344a3780SDimitry Andric
3473eb11fae6SDimitry Andric if (allowTailDupPlacement()) {
3474ac9a064cSDimitry Andric MPDT = &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
3475706b4fc4SDimitry Andric bool OptForSize = MF.getFunction().hasOptSize() ||
3476706b4fc4SDimitry Andric llvm::shouldOptimizeForSize(&MF, PSI, &MBFI->getMBFI());
3477706b4fc4SDimitry Andric if (OptForSize)
3478b915e9e0SDimitry Andric TailDupSize = 1;
3479044eb2f6SDimitry Andric bool PreRegAlloc = false;
3480cfca06d7SDimitry Andric TailDup.initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI,
3481706b4fc4SDimitry Andric /* LayoutMode */ true, TailDupSize);
348271d5a254SDimitry Andric precomputeTriangleChains();
3483b915e9e0SDimitry Andric }
3484b915e9e0SDimitry Andric
348501095a5dSDimitry Andric buildCFGChains();
348601095a5dSDimitry Andric
348701095a5dSDimitry Andric // Changing the layout can create new tail merging opportunities.
348801095a5dSDimitry Andric // TailMerge can create jump into if branches that make CFG irreducible for
348901095a5dSDimitry Andric // HW that requires structured CFG.
349001095a5dSDimitry Andric bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
349101095a5dSDimitry Andric PassConfig->getEnableTailMerge() &&
349201095a5dSDimitry Andric BranchFoldPlacement;
349301095a5dSDimitry Andric // No tail merging opportunities if the block number is less than four.
349401095a5dSDimitry Andric if (MF.size() > 3 && EnableTailMerge) {
34956b3f41edSDimitry Andric unsigned TailMergeSize = TailDupSize + 1;
3496b60736ecSDimitry Andric BranchFolder BF(/*DefaultEnableTailMerge=*/true, /*CommonHoist=*/false,
3497b60736ecSDimitry Andric *MBFI, *MBPI, PSI, TailMergeSize);
349801095a5dSDimitry Andric
3499cfca06d7SDimitry Andric if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), MLI,
3500e6d15924SDimitry Andric /*AfterPlacement=*/true)) {
350101095a5dSDimitry Andric // Redo the layout if tail merging creates/removes/moves blocks.
350201095a5dSDimitry Andric BlockToChain.clear();
350371d5a254SDimitry Andric ComputedEdges.clear();
350471d5a254SDimitry Andric // Must redo the post-dominator tree if blocks were changed.
350571d5a254SDimitry Andric if (MPDT)
3506ac9a064cSDimitry Andric MPDT->recalculate(MF);
350701095a5dSDimitry Andric ChainAllocator.DestroyAll();
350801095a5dSDimitry Andric buildCFGChains();
350901095a5dSDimitry Andric }
351001095a5dSDimitry Andric }
351101095a5dSDimitry Andric
351277fc4c14SDimitry Andric // Apply a post-processing optimizing block placement.
3513145449b1SDimitry Andric if (MF.size() >= 3 && EnableExtTspBlockPlacement &&
3514145449b1SDimitry Andric (ApplyExtTspWithoutProfile || MF.getFunction().hasProfileData())) {
351577fc4c14SDimitry Andric // Find a new placement and modify the layout of the blocks in the function.
351677fc4c14SDimitry Andric applyExtTsp();
351777fc4c14SDimitry Andric
351877fc4c14SDimitry Andric // Re-create CFG chain so that we can optimizeBranches and alignBlocks.
351977fc4c14SDimitry Andric createCFGChainExtTsp();
352077fc4c14SDimitry Andric }
352177fc4c14SDimitry Andric
352201095a5dSDimitry Andric optimizeBranches();
352301095a5dSDimitry Andric alignBlocks();
352463faed5bSDimitry Andric
352563faed5bSDimitry Andric BlockToChain.clear();
352671d5a254SDimitry Andric ComputedEdges.clear();
352763faed5bSDimitry Andric ChainAllocator.DestroyAll();
352863faed5bSDimitry Andric
35296f8fc217SDimitry Andric bool HasMaxBytesOverride =
35306f8fc217SDimitry Andric MaxBytesForAlignmentOverride.getNumOccurrences() > 0;
35316f8fc217SDimitry Andric
353259d6cff9SDimitry Andric if (AlignAllBlock)
353359d6cff9SDimitry Andric // Align all of the blocks in the function to a specific alignment.
35346f8fc217SDimitry Andric for (MachineBasicBlock &MBB : MF) {
35356f8fc217SDimitry Andric if (HasMaxBytesOverride)
35366f8fc217SDimitry Andric MBB.setAlignment(Align(1ULL << AlignAllBlock),
35376f8fc217SDimitry Andric MaxBytesForAlignmentOverride);
35386f8fc217SDimitry Andric else
35391d5ae102SDimitry Andric MBB.setAlignment(Align(1ULL << AlignAllBlock));
35406f8fc217SDimitry Andric }
354101095a5dSDimitry Andric else if (AlignAllNonFallThruBlocks) {
354201095a5dSDimitry Andric // Align all of the blocks that have no fall-through predecessors to a
354301095a5dSDimitry Andric // specific alignment.
354401095a5dSDimitry Andric for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
354501095a5dSDimitry Andric auto LayoutPred = std::prev(MBI);
35466f8fc217SDimitry Andric if (!LayoutPred->isSuccessor(&*MBI)) {
35476f8fc217SDimitry Andric if (HasMaxBytesOverride)
35486f8fc217SDimitry Andric MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks),
35496f8fc217SDimitry Andric MaxBytesForAlignmentOverride);
35506f8fc217SDimitry Andric else
35511d5ae102SDimitry Andric MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks));
355201095a5dSDimitry Andric }
355301095a5dSDimitry Andric }
35546f8fc217SDimitry Andric }
355571d5a254SDimitry Andric if (ViewBlockLayoutWithBFI != GVDT_None &&
355671d5a254SDimitry Andric (ViewBlockFreqFuncName.empty() ||
3557ac9a064cSDimitry Andric F->getFunction().getName() == ViewBlockFreqFuncName)) {
3558e3b55780SDimitry Andric if (RenumberBlocksBeforeView)
3559e3b55780SDimitry Andric MF.RenumberBlocks();
356071d5a254SDimitry Andric MBFI->view("MBP." + MF.getName(), false);
356171d5a254SDimitry Andric }
356271d5a254SDimitry Andric
356363faed5bSDimitry Andric // We always return true as we have no way to track whether the final order
356463faed5bSDimitry Andric // differs from the original order.
356563faed5bSDimitry Andric return true;
356663faed5bSDimitry Andric }
356763faed5bSDimitry Andric
applyExtTsp()356877fc4c14SDimitry Andric void MachineBlockPlacement::applyExtTsp() {
356977fc4c14SDimitry Andric // Prepare data; blocks are indexed by their index in the current ordering.
357077fc4c14SDimitry Andric DenseMap<const MachineBasicBlock *, uint64_t> BlockIndex;
357177fc4c14SDimitry Andric BlockIndex.reserve(F->size());
357277fc4c14SDimitry Andric std::vector<const MachineBasicBlock *> CurrentBlockOrder;
357377fc4c14SDimitry Andric CurrentBlockOrder.reserve(F->size());
357477fc4c14SDimitry Andric size_t NumBlocks = 0;
357577fc4c14SDimitry Andric for (const MachineBasicBlock &MBB : *F) {
357677fc4c14SDimitry Andric BlockIndex[&MBB] = NumBlocks++;
357777fc4c14SDimitry Andric CurrentBlockOrder.push_back(&MBB);
357877fc4c14SDimitry Andric }
357977fc4c14SDimitry Andric
358077fc4c14SDimitry Andric auto BlockSizes = std::vector<uint64_t>(F->size());
358177fc4c14SDimitry Andric auto BlockCounts = std::vector<uint64_t>(F->size());
3582b1c73532SDimitry Andric std::vector<codelayout::EdgeCount> JumpCounts;
358377fc4c14SDimitry Andric for (MachineBasicBlock &MBB : *F) {
358477fc4c14SDimitry Andric // Getting the block frequency.
358577fc4c14SDimitry Andric BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
358677fc4c14SDimitry Andric BlockCounts[BlockIndex[&MBB]] = BlockFreq.getFrequency();
358777fc4c14SDimitry Andric // Getting the block size:
358877fc4c14SDimitry Andric // - approximate the size of an instruction by 4 bytes, and
358977fc4c14SDimitry Andric // - ignore debug instructions.
359077fc4c14SDimitry Andric // Note: getting the exact size of each block is target-dependent and can be
359177fc4c14SDimitry Andric // done by extending the interface of MCCodeEmitter. Experimentally we do
359277fc4c14SDimitry Andric // not see a perf improvement with the exact block sizes.
359377fc4c14SDimitry Andric auto NonDbgInsts =
359477fc4c14SDimitry Andric instructionsWithoutDebug(MBB.instr_begin(), MBB.instr_end());
359577fc4c14SDimitry Andric int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
359677fc4c14SDimitry Andric BlockSizes[BlockIndex[&MBB]] = 4 * NumInsts;
359777fc4c14SDimitry Andric // Getting jump frequencies.
359877fc4c14SDimitry Andric for (MachineBasicBlock *Succ : MBB.successors()) {
359977fc4c14SDimitry Andric auto EP = MBPI->getEdgeProbability(&MBB, Succ);
3600e3b55780SDimitry Andric BlockFrequency JumpFreq = BlockFreq * EP;
3601b1c73532SDimitry Andric JumpCounts.push_back(
3602b1c73532SDimitry Andric {BlockIndex[&MBB], BlockIndex[Succ], JumpFreq.getFrequency()});
360377fc4c14SDimitry Andric }
360477fc4c14SDimitry Andric }
360577fc4c14SDimitry Andric
360677fc4c14SDimitry Andric LLVM_DEBUG(dbgs() << "Applying ext-tsp layout for |V| = " << F->size()
360777fc4c14SDimitry Andric << " with profile = " << F->getFunction().hasProfileData()
360877fc4c14SDimitry Andric << " (" << F->getName().str() << ")"
360977fc4c14SDimitry Andric << "\n");
361077fc4c14SDimitry Andric LLVM_DEBUG(
361177fc4c14SDimitry Andric dbgs() << format(" original layout score: %0.2f\n",
361277fc4c14SDimitry Andric calcExtTspScore(BlockSizes, BlockCounts, JumpCounts)));
361377fc4c14SDimitry Andric
361477fc4c14SDimitry Andric // Run the layout algorithm.
3615b1c73532SDimitry Andric auto NewOrder = computeExtTspLayout(BlockSizes, BlockCounts, JumpCounts);
361677fc4c14SDimitry Andric std::vector<const MachineBasicBlock *> NewBlockOrder;
361777fc4c14SDimitry Andric NewBlockOrder.reserve(F->size());
361877fc4c14SDimitry Andric for (uint64_t Node : NewOrder) {
361977fc4c14SDimitry Andric NewBlockOrder.push_back(CurrentBlockOrder[Node]);
362077fc4c14SDimitry Andric }
362177fc4c14SDimitry Andric LLVM_DEBUG(dbgs() << format(" optimized layout score: %0.2f\n",
362277fc4c14SDimitry Andric calcExtTspScore(NewOrder, BlockSizes, BlockCounts,
362377fc4c14SDimitry Andric JumpCounts)));
362477fc4c14SDimitry Andric
362577fc4c14SDimitry Andric // Assign new block order.
362677fc4c14SDimitry Andric assignBlockOrder(NewBlockOrder);
362777fc4c14SDimitry Andric }
362877fc4c14SDimitry Andric
assignBlockOrder(const std::vector<const MachineBasicBlock * > & NewBlockOrder)362977fc4c14SDimitry Andric void MachineBlockPlacement::assignBlockOrder(
363077fc4c14SDimitry Andric const std::vector<const MachineBasicBlock *> &NewBlockOrder) {
363177fc4c14SDimitry Andric assert(F->size() == NewBlockOrder.size() && "Incorrect size of block order");
363277fc4c14SDimitry Andric F->RenumberBlocks();
363377fc4c14SDimitry Andric
363477fc4c14SDimitry Andric bool HasChanges = false;
363577fc4c14SDimitry Andric for (size_t I = 0; I < NewBlockOrder.size(); I++) {
363677fc4c14SDimitry Andric if (NewBlockOrder[I] != F->getBlockNumbered(I)) {
363777fc4c14SDimitry Andric HasChanges = true;
363877fc4c14SDimitry Andric break;
363977fc4c14SDimitry Andric }
364077fc4c14SDimitry Andric }
364177fc4c14SDimitry Andric // Stop early if the new block order is identical to the existing one.
364277fc4c14SDimitry Andric if (!HasChanges)
364377fc4c14SDimitry Andric return;
364477fc4c14SDimitry Andric
364577fc4c14SDimitry Andric SmallVector<MachineBasicBlock *, 4> PrevFallThroughs(F->getNumBlockIDs());
364677fc4c14SDimitry Andric for (auto &MBB : *F) {
364777fc4c14SDimitry Andric PrevFallThroughs[MBB.getNumber()] = MBB.getFallThrough();
364877fc4c14SDimitry Andric }
364977fc4c14SDimitry Andric
365077fc4c14SDimitry Andric // Sort basic blocks in the function according to the computed order.
365177fc4c14SDimitry Andric DenseMap<const MachineBasicBlock *, size_t> NewIndex;
365277fc4c14SDimitry Andric for (const MachineBasicBlock *MBB : NewBlockOrder) {
365377fc4c14SDimitry Andric NewIndex[MBB] = NewIndex.size();
365477fc4c14SDimitry Andric }
365577fc4c14SDimitry Andric F->sort([&](MachineBasicBlock &L, MachineBasicBlock &R) {
365677fc4c14SDimitry Andric return NewIndex[&L] < NewIndex[&R];
365777fc4c14SDimitry Andric });
365877fc4c14SDimitry Andric
365977fc4c14SDimitry Andric // Update basic block branches by inserting explicit fallthrough branches
366077fc4c14SDimitry Andric // when required and re-optimize branches when possible.
366177fc4c14SDimitry Andric const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
366277fc4c14SDimitry Andric SmallVector<MachineOperand, 4> Cond;
366377fc4c14SDimitry Andric for (auto &MBB : *F) {
366477fc4c14SDimitry Andric MachineFunction::iterator NextMBB = std::next(MBB.getIterator());
366577fc4c14SDimitry Andric MachineFunction::iterator EndIt = MBB.getParent()->end();
366677fc4c14SDimitry Andric auto *FTMBB = PrevFallThroughs[MBB.getNumber()];
366777fc4c14SDimitry Andric // If this block had a fallthrough before we need an explicit unconditional
366877fc4c14SDimitry Andric // branch to that block if the fallthrough block is not adjacent to the
366977fc4c14SDimitry Andric // block in the new order.
367077fc4c14SDimitry Andric if (FTMBB && (NextMBB == EndIt || &*NextMBB != FTMBB)) {
367177fc4c14SDimitry Andric TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
367277fc4c14SDimitry Andric }
367377fc4c14SDimitry Andric
367477fc4c14SDimitry Andric // It might be possible to optimize branches by flipping the condition.
367577fc4c14SDimitry Andric Cond.clear();
367677fc4c14SDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
367777fc4c14SDimitry Andric if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
367877fc4c14SDimitry Andric continue;
367977fc4c14SDimitry Andric MBB.updateTerminator(FTMBB);
368077fc4c14SDimitry Andric }
368177fc4c14SDimitry Andric
368277fc4c14SDimitry Andric #ifndef NDEBUG
368377fc4c14SDimitry Andric // Make sure we correctly constructed all branches.
368477fc4c14SDimitry Andric F->verify(this, "After optimized block reordering");
368577fc4c14SDimitry Andric #endif
368677fc4c14SDimitry Andric }
368777fc4c14SDimitry Andric
createCFGChainExtTsp()368877fc4c14SDimitry Andric void MachineBlockPlacement::createCFGChainExtTsp() {
368977fc4c14SDimitry Andric BlockToChain.clear();
369077fc4c14SDimitry Andric ComputedEdges.clear();
369177fc4c14SDimitry Andric ChainAllocator.DestroyAll();
369277fc4c14SDimitry Andric
369377fc4c14SDimitry Andric MachineBasicBlock *HeadBB = &F->front();
369477fc4c14SDimitry Andric BlockChain *FunctionChain =
369577fc4c14SDimitry Andric new (ChainAllocator.Allocate()) BlockChain(BlockToChain, HeadBB);
369677fc4c14SDimitry Andric
369777fc4c14SDimitry Andric for (MachineBasicBlock &MBB : *F) {
369877fc4c14SDimitry Andric if (HeadBB == &MBB)
369977fc4c14SDimitry Andric continue; // Ignore head of the chain
370077fc4c14SDimitry Andric FunctionChain->merge(&MBB, nullptr);
370177fc4c14SDimitry Andric }
370277fc4c14SDimitry Andric }
370377fc4c14SDimitry Andric
370463faed5bSDimitry Andric namespace {
3705044eb2f6SDimitry Andric
3706eb11fae6SDimitry Andric /// A pass to compute block placement statistics.
370763faed5bSDimitry Andric ///
370863faed5bSDimitry Andric /// A separate pass to compute interesting statistics for evaluating block
370963faed5bSDimitry Andric /// placement. This is separate from the actual placement pass so that they can
371058b69754SDimitry Andric /// be computed in the absence of any placement transformations or when using
371163faed5bSDimitry Andric /// alternative placement strategies.
371263faed5bSDimitry Andric class MachineBlockPlacementStats : public MachineFunctionPass {
3713eb11fae6SDimitry Andric /// A handle to the branch probability pass.
371463faed5bSDimitry Andric const MachineBranchProbabilityInfo *MBPI;
371563faed5bSDimitry Andric
3716eb11fae6SDimitry Andric /// A handle to the function-wide block frequency pass.
371763faed5bSDimitry Andric const MachineBlockFrequencyInfo *MBFI;
371863faed5bSDimitry Andric
371963faed5bSDimitry Andric public:
372063faed5bSDimitry Andric static char ID; // Pass identification, replacement for typeid
3721044eb2f6SDimitry Andric
MachineBlockPlacementStats()372263faed5bSDimitry Andric MachineBlockPlacementStats() : MachineFunctionPass(ID) {
372363faed5bSDimitry Andric initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
372463faed5bSDimitry Andric }
372563faed5bSDimitry Andric
37265ca98fd9SDimitry Andric bool runOnMachineFunction(MachineFunction &F) override;
372763faed5bSDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const37285ca98fd9SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
3729ac9a064cSDimitry Andric AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
3730ac9a064cSDimitry Andric AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
373163faed5bSDimitry Andric AU.setPreservesAll();
373263faed5bSDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
373363faed5bSDimitry Andric }
373463faed5bSDimitry Andric };
3735044eb2f6SDimitry Andric
3736044eb2f6SDimitry Andric } // end anonymous namespace
373763faed5bSDimitry Andric
373863faed5bSDimitry Andric char MachineBlockPlacementStats::ID = 0;
3739044eb2f6SDimitry Andric
374063faed5bSDimitry Andric char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
3741044eb2f6SDimitry Andric
374263faed5bSDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
374363faed5bSDimitry Andric "Basic Block Placement Stats", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)3744ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)
3745ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass)
374663faed5bSDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
374763faed5bSDimitry Andric "Basic Block Placement Stats", false, false)
374863faed5bSDimitry Andric
374963faed5bSDimitry Andric bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
375063faed5bSDimitry Andric // Check for single-block functions and skip them.
37515ca98fd9SDimitry Andric if (std::next(F.begin()) == F.end())
375263faed5bSDimitry Andric return false;
375363faed5bSDimitry Andric
3754145449b1SDimitry Andric if (!isFunctionInPrintList(F.getName()))
3755145449b1SDimitry Andric return false;
3756145449b1SDimitry Andric
3757ac9a064cSDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
3758ac9a064cSDimitry Andric MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
375963faed5bSDimitry Andric
37605a5ac124SDimitry Andric for (MachineBasicBlock &MBB : F) {
37615a5ac124SDimitry Andric BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
37625a5ac124SDimitry Andric Statistic &NumBranches =
37635a5ac124SDimitry Andric (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
37645a5ac124SDimitry Andric Statistic &BranchTakenFreq =
37655a5ac124SDimitry Andric (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
37665a5ac124SDimitry Andric for (MachineBasicBlock *Succ : MBB.successors()) {
376763faed5bSDimitry Andric // Skip if this successor is a fallthrough.
37685a5ac124SDimitry Andric if (MBB.isLayoutSuccessor(Succ))
376963faed5bSDimitry Andric continue;
377063faed5bSDimitry Andric
37715a5ac124SDimitry Andric BlockFrequency EdgeFreq =
37725a5ac124SDimitry Andric BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
377363faed5bSDimitry Andric ++NumBranches;
377463faed5bSDimitry Andric BranchTakenFreq += EdgeFreq.getFrequency();
377563faed5bSDimitry Andric }
377663faed5bSDimitry Andric }
377763faed5bSDimitry Andric
377863faed5bSDimitry Andric return false;
377963faed5bSDimitry Andric }
3780