12cab237bSDimitry Andric //===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===//
2dff0c46cSDimitry Andric //
3dff0c46cSDimitry Andric // The LLVM Compiler Infrastructure
4dff0c46cSDimitry Andric //
5dff0c46cSDimitry Andric // This file is distributed under the University of Illinois Open Source
6dff0c46cSDimitry Andric // License. See LICENSE.TXT for details.
7dff0c46cSDimitry Andric //
8dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
9dff0c46cSDimitry Andric //
10dff0c46cSDimitry Andric // This file implements basic block placement transformations using the CFG
11dff0c46cSDimitry Andric // structure and branch probability estimates.
12dff0c46cSDimitry Andric //
13dff0c46cSDimitry Andric // The pass strives to preserve the structure of the CFG (that is, retain
147ae0e2c9SDimitry Andric // a topological ordering of basic blocks) in the absence of a *strong* signal
15dff0c46cSDimitry Andric // to the contrary from probabilities. However, within the CFG structure, it
16dff0c46cSDimitry Andric // attempts to choose an ordering which favors placing more likely sequences of
17dff0c46cSDimitry Andric // blocks adjacent to each other.
18dff0c46cSDimitry Andric //
19dff0c46cSDimitry Andric // The algorithm works from the inner-most loop within a function outward, and
20dff0c46cSDimitry Andric // at each stage walks through the basic blocks, trying to coalesce them into
21dff0c46cSDimitry Andric // sequential chains where allowed by the CFG (or demanded by heavy
22dff0c46cSDimitry Andric // probabilities). Finally, it walks the blocks in topological order, and the
23dff0c46cSDimitry Andric // first time it reaches a chain of basic blocks, it schedules them in the
24dff0c46cSDimitry Andric // function in-order.
25dff0c46cSDimitry Andric //
26dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
27dff0c46cSDimitry Andric
283ca95b02SDimitry Andric #include "BranchFolding.h"
292cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
30139f7f9bSDimitry Andric #include "llvm/ADT/DenseMap.h"
312cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
322cab237bSDimitry Andric #include "llvm/ADT/SetVector.h"
33139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
34139f7f9bSDimitry Andric #include "llvm/ADT/SmallVector.h"
35139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
367a7e6055SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
37dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
38dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
39dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
40dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
41dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
42dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
43dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
447a7e6055SDimitry Andric #include "llvm/CodeGen/MachinePostDominators.h"
45d88c1a5aSDimitry Andric #include "llvm/CodeGen/TailDuplicator.h"
462cab237bSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
472cab237bSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
48db17bf38SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
492cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
502cab237bSDimitry Andric #include "llvm/IR/DebugLoc.h"
512cab237bSDimitry Andric #include "llvm/IR/Function.h"
522cab237bSDimitry Andric #include "llvm/Pass.h"
53dff0c46cSDimitry Andric #include "llvm/Support/Allocator.h"
542cab237bSDimitry Andric #include "llvm/Support/BlockFrequency.h"
552cab237bSDimitry Andric #include "llvm/Support/BranchProbability.h"
562cab237bSDimitry Andric #include "llvm/Support/CodeGen.h"
57284c1978SDimitry Andric #include "llvm/Support/CommandLine.h"
582cab237bSDimitry Andric #include "llvm/Support/Compiler.h"
59dff0c46cSDimitry Andric #include "llvm/Support/Debug.h"
60ff0cc061SDimitry Andric #include "llvm/Support/raw_ostream.h"
612cab237bSDimitry Andric #include "llvm/Target/TargetMachine.h"
62dff0c46cSDimitry Andric #include <algorithm>
632cab237bSDimitry Andric #include <cassert>
642cab237bSDimitry Andric #include <cstdint>
652cab237bSDimitry Andric #include <iterator>
662cab237bSDimitry Andric #include <memory>
672cab237bSDimitry Andric #include <string>
682cab237bSDimitry Andric #include <tuple>
697a7e6055SDimitry Andric #include <utility>
702cab237bSDimitry Andric #include <vector>
712cab237bSDimitry Andric
72dff0c46cSDimitry Andric using namespace llvm;
73dff0c46cSDimitry Andric
74ff0cc061SDimitry Andric #define DEBUG_TYPE "block-placement"
7591bc56edSDimitry Andric
76dff0c46cSDimitry Andric STATISTIC(NumCondBranches, "Number of conditional branches");
777d523365SDimitry Andric STATISTIC(NumUncondBranches, "Number of unconditional branches");
78dff0c46cSDimitry Andric STATISTIC(CondBranchTakenFreq,
79dff0c46cSDimitry Andric "Potential frequency of taking conditional branches");
80dff0c46cSDimitry Andric STATISTIC(UncondBranchTakenFreq,
81dff0c46cSDimitry Andric "Potential frequency of taking unconditional branches");
82dff0c46cSDimitry Andric
83284c1978SDimitry Andric static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
84284c1978SDimitry Andric cl::desc("Force the alignment of all "
85284c1978SDimitry Andric "blocks in the function."),
86284c1978SDimitry Andric cl::init(0), cl::Hidden);
87284c1978SDimitry Andric
883ca95b02SDimitry Andric static cl::opt<unsigned> AlignAllNonFallThruBlocks(
893ca95b02SDimitry Andric "align-all-nofallthru-blocks",
903ca95b02SDimitry Andric cl::desc("Force the alignment of all "
913ca95b02SDimitry Andric "blocks that have no fall-through predecessors (i.e. don't add "
923ca95b02SDimitry Andric "nops that are executed)."),
937d523365SDimitry Andric cl::init(0), cl::Hidden);
947d523365SDimitry Andric
9591bc56edSDimitry Andric // FIXME: Find a good default for this flag and remove the flag.
96ff0cc061SDimitry Andric static cl::opt<unsigned> ExitBlockBias(
97ff0cc061SDimitry Andric "block-placement-exit-block-bias",
9891bc56edSDimitry Andric cl::desc("Block frequency percentage a loop exit block needs "
9991bc56edSDimitry Andric "over the original exit to be considered the new exit."),
10091bc56edSDimitry Andric cl::init(0), cl::Hidden);
10191bc56edSDimitry Andric
102d88c1a5aSDimitry Andric // Definition:
103d88c1a5aSDimitry Andric // - Outlining: placement of a basic block outside the chain or hot path.
104d88c1a5aSDimitry Andric
1057d523365SDimitry Andric static cl::opt<unsigned> LoopToColdBlockRatio(
1067d523365SDimitry Andric "loop-to-cold-block-ratio",
1077d523365SDimitry Andric cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
1087d523365SDimitry Andric "(frequency of block) is greater than this ratio"),
1097d523365SDimitry Andric cl::init(5), cl::Hidden);
1107d523365SDimitry Andric
1112cab237bSDimitry Andric static cl::opt<bool> ForceLoopColdBlock(
1122cab237bSDimitry Andric "force-loop-cold-block",
1132cab237bSDimitry Andric cl::desc("Force outlining cold blocks from loops."),
1142cab237bSDimitry Andric cl::init(false), cl::Hidden);
1152cab237bSDimitry Andric
1167d523365SDimitry Andric static cl::opt<bool>
1177d523365SDimitry Andric PreciseRotationCost("precise-rotation-cost",
1187d523365SDimitry Andric cl::desc("Model the cost of loop rotation more "
1197d523365SDimitry Andric "precisely by using profile data."),
1207d523365SDimitry Andric cl::init(false), cl::Hidden);
1212cab237bSDimitry Andric
1223ca95b02SDimitry Andric static cl::opt<bool>
1233ca95b02SDimitry Andric ForcePreciseRotationCost("force-precise-rotation-cost",
1243ca95b02SDimitry Andric cl::desc("Force the use of precise cost "
1253ca95b02SDimitry Andric "loop rotation strategy."),
1263ca95b02SDimitry Andric cl::init(false), cl::Hidden);
1277d523365SDimitry Andric
1287d523365SDimitry Andric static cl::opt<unsigned> MisfetchCost(
1297d523365SDimitry Andric "misfetch-cost",
1303ca95b02SDimitry Andric cl::desc("Cost that models the probabilistic risk of an instruction "
1317d523365SDimitry Andric "misfetch due to a jump comparing to falling through, whose cost "
1327d523365SDimitry Andric "is zero."),
1337d523365SDimitry Andric cl::init(1), cl::Hidden);
1347d523365SDimitry Andric
1357d523365SDimitry Andric static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
1367d523365SDimitry Andric cl::desc("Cost of jump instructions."),
1377d523365SDimitry Andric cl::init(1), cl::Hidden);
138d88c1a5aSDimitry Andric static cl::opt<bool>
139d88c1a5aSDimitry Andric TailDupPlacement("tail-dup-placement",
140d88c1a5aSDimitry Andric cl::desc("Perform tail duplication during placement. "
141d88c1a5aSDimitry Andric "Creates more fallthrough opportunites in "
142d88c1a5aSDimitry Andric "outline branches."),
143d88c1a5aSDimitry Andric cl::init(true), cl::Hidden);
1447d523365SDimitry Andric
1453ca95b02SDimitry Andric static cl::opt<bool>
1463ca95b02SDimitry Andric BranchFoldPlacement("branch-fold-placement",
1473ca95b02SDimitry Andric cl::desc("Perform branch folding during placement. "
1483ca95b02SDimitry Andric "Reduces code size."),
1493ca95b02SDimitry Andric cl::init(true), cl::Hidden);
1503ca95b02SDimitry Andric
151d88c1a5aSDimitry Andric // Heuristic for tail duplication.
1527a7e6055SDimitry Andric static cl::opt<unsigned> TailDupPlacementThreshold(
153d88c1a5aSDimitry Andric "tail-dup-placement-threshold",
154d88c1a5aSDimitry Andric cl::desc("Instruction cutoff for tail duplication during layout. "
155d88c1a5aSDimitry Andric "Tail merging during layout is forced to have a threshold "
156d88c1a5aSDimitry Andric "that won't conflict."), cl::init(2),
157d88c1a5aSDimitry Andric cl::Hidden);
158d88c1a5aSDimitry Andric
1595517e702SDimitry Andric // Heuristic for aggressive tail duplication.
1605517e702SDimitry Andric static cl::opt<unsigned> TailDupPlacementAggressiveThreshold(
1615517e702SDimitry Andric "tail-dup-placement-aggressive-threshold",
1625517e702SDimitry Andric cl::desc("Instruction cutoff for aggressive tail duplication during "
1635517e702SDimitry Andric "layout. Used at -O3. Tail merging during layout is forced to "
1642cab237bSDimitry Andric "have a threshold that won't conflict."), cl::init(4),
1655517e702SDimitry Andric cl::Hidden);
1665517e702SDimitry Andric
1677a7e6055SDimitry Andric // Heuristic for tail duplication.
1687a7e6055SDimitry Andric static cl::opt<unsigned> TailDupPlacementPenalty(
1697a7e6055SDimitry Andric "tail-dup-placement-penalty",
1707a7e6055SDimitry Andric cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
1717a7e6055SDimitry Andric "Copying can increase fallthrough, but it also increases icache "
1727a7e6055SDimitry Andric "pressure. This parameter controls the penalty to account for that. "
1737a7e6055SDimitry Andric "Percent as integer."),
1747a7e6055SDimitry Andric cl::init(2),
1757a7e6055SDimitry Andric cl::Hidden);
1767a7e6055SDimitry Andric
1777a7e6055SDimitry Andric // Heuristic for triangle chains.
1787a7e6055SDimitry Andric static cl::opt<unsigned> TriangleChainCount(
1797a7e6055SDimitry Andric "triangle-chain-count",
1807a7e6055SDimitry Andric cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
1817a7e6055SDimitry Andric "triangle tail duplication heuristic to kick in. 0 to disable."),
1827a7e6055SDimitry Andric cl::init(2),
1837a7e6055SDimitry Andric cl::Hidden);
1847a7e6055SDimitry Andric
1853ca95b02SDimitry Andric extern cl::opt<unsigned> StaticLikelyProb;
1863ca95b02SDimitry Andric extern cl::opt<unsigned> ProfileLikelyProb;
1873ca95b02SDimitry Andric
1887a7e6055SDimitry Andric // Internal option used to control BFI display only after MBP pass.
1897a7e6055SDimitry Andric // Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
1907a7e6055SDimitry Andric // -view-block-layout-with-bfi=
1917a7e6055SDimitry Andric extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
1927a7e6055SDimitry Andric
1937a7e6055SDimitry Andric // Command line option to specify the name of the function for CFG dump
1947a7e6055SDimitry Andric // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
1957a7e6055SDimitry Andric extern cl::opt<std::string> ViewBlockFreqFuncName;
1967a7e6055SDimitry Andric
197dff0c46cSDimitry Andric namespace {
198dff0c46cSDimitry Andric
1992cab237bSDimitry Andric class BlockChain;
2002cab237bSDimitry Andric
2014ba319b5SDimitry Andric /// Type for our function-wide basic block -> block chain mapping.
2022cab237bSDimitry Andric using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>;
2032cab237bSDimitry Andric
2044ba319b5SDimitry Andric /// A chain of blocks which will be laid out contiguously.
205dff0c46cSDimitry Andric ///
206dff0c46cSDimitry Andric /// This is the datastructure representing a chain of consecutive blocks that
207dff0c46cSDimitry Andric /// are profitable to layout together in order to maximize fallthrough
2087ae0e2c9SDimitry Andric /// probabilities and code locality. We also can use a block chain to represent
2097ae0e2c9SDimitry Andric /// a sequence of basic blocks which have some external (correctness)
2107ae0e2c9SDimitry Andric /// requirement for sequential layout.
211dff0c46cSDimitry Andric ///
2127ae0e2c9SDimitry Andric /// Chains can be built around a single basic block and can be merged to grow
2137ae0e2c9SDimitry Andric /// them. They participate in a block-to-chain mapping, which is updated
2147ae0e2c9SDimitry Andric /// automatically as chains are merged together.
215dff0c46cSDimitry Andric class BlockChain {
2164ba319b5SDimitry Andric /// The sequence of blocks belonging to this chain.
217dff0c46cSDimitry Andric ///
218dff0c46cSDimitry Andric /// This is the sequence of blocks for a particular chain. These will be laid
219dff0c46cSDimitry Andric /// out in-order within the function.
220dff0c46cSDimitry Andric SmallVector<MachineBasicBlock *, 4> Blocks;
221dff0c46cSDimitry Andric
2224ba319b5SDimitry Andric /// A handle to the function-wide basic block to block chain mapping.
223dff0c46cSDimitry Andric ///
224dff0c46cSDimitry Andric /// This is retained in each block chain to simplify the computation of child
225dff0c46cSDimitry Andric /// block chains for SCC-formation and iteration. We store the edges to child
226dff0c46cSDimitry Andric /// basic blocks, and map them back to their associated chains using this
227dff0c46cSDimitry Andric /// structure.
228dff0c46cSDimitry Andric BlockToChainMapType &BlockToChain;
229dff0c46cSDimitry Andric
230dff0c46cSDimitry Andric public:
2314ba319b5SDimitry Andric /// Construct a new BlockChain.
232dff0c46cSDimitry Andric ///
233dff0c46cSDimitry Andric /// This builds a new block chain representing a single basic block in the
234dff0c46cSDimitry Andric /// function. It also registers itself as the chain that block participates
235dff0c46cSDimitry Andric /// in with the BlockToChain mapping.
BlockChain(BlockToChainMapType & BlockToChain,MachineBasicBlock * BB)236dff0c46cSDimitry Andric BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
2372cab237bSDimitry Andric : Blocks(1, BB), BlockToChain(BlockToChain) {
238dff0c46cSDimitry Andric assert(BB && "Cannot create a chain with a null basic block");
239dff0c46cSDimitry Andric BlockToChain[BB] = this;
240dff0c46cSDimitry Andric }
241dff0c46cSDimitry Andric
2424ba319b5SDimitry Andric /// Iterator over blocks within the chain.
2432cab237bSDimitry Andric using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
2442cab237bSDimitry Andric using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator;
245dff0c46cSDimitry Andric
2464ba319b5SDimitry Andric /// Beginning of blocks within the chain.
begin()247cb4dff85SDimitry Andric iterator begin() { return Blocks.begin(); }
begin() const2487a7e6055SDimitry Andric const_iterator begin() const { return Blocks.begin(); }
249dff0c46cSDimitry Andric
2504ba319b5SDimitry Andric /// End of blocks within the chain.
end()251cb4dff85SDimitry Andric iterator end() { return Blocks.end(); }
end() const2527a7e6055SDimitry Andric const_iterator end() const { return Blocks.end(); }
253dff0c46cSDimitry Andric
remove(MachineBasicBlock * BB)254d88c1a5aSDimitry Andric bool remove(MachineBasicBlock* BB) {
255d88c1a5aSDimitry Andric for(iterator i = begin(); i != end(); ++i) {
256d88c1a5aSDimitry Andric if (*i == BB) {
257d88c1a5aSDimitry Andric Blocks.erase(i);
258d88c1a5aSDimitry Andric return true;
259d88c1a5aSDimitry Andric }
260d88c1a5aSDimitry Andric }
261d88c1a5aSDimitry Andric return false;
262d88c1a5aSDimitry Andric }
263d88c1a5aSDimitry Andric
2644ba319b5SDimitry Andric /// Merge a block chain into this one.
265dff0c46cSDimitry Andric ///
266dff0c46cSDimitry Andric /// This routine merges a block chain into this one. It takes care of forming
267dff0c46cSDimitry Andric /// a contiguous sequence of basic blocks, updating the edge list, and
268dff0c46cSDimitry Andric /// updating the block -> chain mapping. It does not free or tear down the
269dff0c46cSDimitry Andric /// old chain, but the old chain's block list is no longer valid.
merge(MachineBasicBlock * BB,BlockChain * Chain)270dff0c46cSDimitry Andric void merge(MachineBasicBlock *BB, BlockChain *Chain) {
271d8866befSDimitry Andric assert(BB && "Can't merge a null block.");
272d8866befSDimitry Andric assert(!Blocks.empty() && "Can't merge into an empty chain.");
273dff0c46cSDimitry Andric
274dff0c46cSDimitry Andric // Fast path in case we don't have a chain already.
275dff0c46cSDimitry Andric if (!Chain) {
276d8866befSDimitry Andric assert(!BlockToChain[BB] &&
277d8866befSDimitry Andric "Passed chain is null, but BB has entry in BlockToChain.");
278dff0c46cSDimitry Andric Blocks.push_back(BB);
279dff0c46cSDimitry Andric BlockToChain[BB] = this;
280dff0c46cSDimitry Andric return;
281dff0c46cSDimitry Andric }
282dff0c46cSDimitry Andric
283d8866befSDimitry Andric assert(BB == *Chain->begin() && "Passed BB is not head of Chain.");
284dff0c46cSDimitry Andric assert(Chain->begin() != Chain->end());
285dff0c46cSDimitry Andric
286dff0c46cSDimitry Andric // Update the incoming blocks to point to this chain, and add them to the
287dff0c46cSDimitry Andric // chain structure.
288ff0cc061SDimitry Andric for (MachineBasicBlock *ChainBB : *Chain) {
289ff0cc061SDimitry Andric Blocks.push_back(ChainBB);
290d8866befSDimitry Andric assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain.");
291ff0cc061SDimitry Andric BlockToChain[ChainBB] = this;
292dff0c46cSDimitry Andric }
293dff0c46cSDimitry Andric }
294dff0c46cSDimitry Andric
295dff0c46cSDimitry Andric #ifndef NDEBUG
2964ba319b5SDimitry Andric /// Dump the blocks in this chain.
dump()29791bc56edSDimitry Andric LLVM_DUMP_METHOD void dump() {
298ff0cc061SDimitry Andric for (MachineBasicBlock *MBB : *this)
299ff0cc061SDimitry Andric MBB->dump();
300dff0c46cSDimitry Andric }
301dff0c46cSDimitry Andric #endif // NDEBUG
302dff0c46cSDimitry Andric
3034ba319b5SDimitry Andric /// Count of predecessors of any block within the chain which have not
3043ca95b02SDimitry Andric /// yet been scheduled. In general, we will delay scheduling this chain
3053ca95b02SDimitry Andric /// until those predecessors are scheduled (or we find a sufficiently good
3063ca95b02SDimitry Andric /// reason to override this heuristic.) Note that when forming loop chains,
3073ca95b02SDimitry Andric /// blocks outside the loop are ignored and treated as if they were already
3083ca95b02SDimitry Andric /// scheduled.
309dff0c46cSDimitry Andric ///
3103ca95b02SDimitry Andric /// Note: This field is reinitialized multiple times - once for each loop,
3113ca95b02SDimitry Andric /// and then once for the function as a whole.
3122cab237bSDimitry Andric unsigned UnscheduledPredecessors = 0;
313dff0c46cSDimitry Andric };
314dff0c46cSDimitry Andric
315dff0c46cSDimitry Andric class MachineBlockPlacement : public MachineFunctionPass {
3164ba319b5SDimitry Andric /// A type for a block filter set.
3172cab237bSDimitry Andric using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
3187a7e6055SDimitry Andric
319*b5893f02SDimitry Andric /// Pair struct containing basic block and taildup profitability
3207a7e6055SDimitry Andric struct BlockAndTailDupResult {
3217a7e6055SDimitry Andric MachineBasicBlock *BB;
3227a7e6055SDimitry Andric bool ShouldTailDup;
3237a7e6055SDimitry Andric };
3247a7e6055SDimitry Andric
3257a7e6055SDimitry Andric /// Triple struct containing edge weight and the edge.
3267a7e6055SDimitry Andric struct WeightedEdge {
3277a7e6055SDimitry Andric BlockFrequency Weight;
3287a7e6055SDimitry Andric MachineBasicBlock *Src;
3297a7e6055SDimitry Andric MachineBasicBlock *Dest;
3307a7e6055SDimitry Andric };
331dff0c46cSDimitry Andric
3324ba319b5SDimitry Andric /// work lists of blocks that are ready to be laid out
3333ca95b02SDimitry Andric SmallVector<MachineBasicBlock *, 16> BlockWorkList;
3343ca95b02SDimitry Andric SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
3353ca95b02SDimitry Andric
3367a7e6055SDimitry Andric /// Edges that have already been computed as optimal.
3377a7e6055SDimitry Andric DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
3387a7e6055SDimitry Andric
3394ba319b5SDimitry Andric /// Machine Function
3403ca95b02SDimitry Andric MachineFunction *F;
3413ca95b02SDimitry Andric
3424ba319b5SDimitry Andric /// A handle to the branch probability pass.
343dff0c46cSDimitry Andric const MachineBranchProbabilityInfo *MBPI;
344dff0c46cSDimitry Andric
3454ba319b5SDimitry Andric /// A handle to the function-wide block frequency pass.
3463ca95b02SDimitry Andric std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
347dff0c46cSDimitry Andric
3484ba319b5SDimitry Andric /// A handle to the loop info.
3493ca95b02SDimitry Andric MachineLoopInfo *MLI;
350dff0c46cSDimitry Andric
3514ba319b5SDimitry Andric /// Preferred loop exit.
352d88c1a5aSDimitry Andric /// Member variable for convenience. It may be removed by duplication deep
353d88c1a5aSDimitry Andric /// in the call stack.
354d88c1a5aSDimitry Andric MachineBasicBlock *PreferredLoopExit;
355d88c1a5aSDimitry Andric
3564ba319b5SDimitry Andric /// A handle to the target's instruction info.
357dff0c46cSDimitry Andric const TargetInstrInfo *TII;
358dff0c46cSDimitry Andric
3594ba319b5SDimitry Andric /// A handle to the target's lowering info.
360139f7f9bSDimitry Andric const TargetLoweringBase *TLI;
361dff0c46cSDimitry Andric
3624ba319b5SDimitry Andric /// A handle to the post dominator tree.
3637a7e6055SDimitry Andric MachinePostDominatorTree *MPDT;
364ff0cc061SDimitry Andric
3654ba319b5SDimitry Andric /// Duplicator used to duplicate tails during placement.
366d88c1a5aSDimitry Andric ///
367d88c1a5aSDimitry Andric /// Placement decisions can open up new tail duplication opportunities, but
368d88c1a5aSDimitry Andric /// since tail duplication affects placement decisions of later blocks, it
369d88c1a5aSDimitry Andric /// must be done inline.
370d88c1a5aSDimitry Andric TailDuplicator TailDup;
371d88c1a5aSDimitry Andric
3724ba319b5SDimitry Andric /// Allocator and owner of BlockChain structures.
373dff0c46cSDimitry Andric ///
3747ae0e2c9SDimitry Andric /// We build BlockChains lazily while processing the loop structure of
3757ae0e2c9SDimitry Andric /// a function. To reduce malloc traffic, we allocate them using this
3767ae0e2c9SDimitry Andric /// slab-like allocator, and destroy them after the pass completes. An
3777ae0e2c9SDimitry Andric /// important guarantee is that this allocator produces stable pointers to
3787ae0e2c9SDimitry Andric /// the chains.
379dff0c46cSDimitry Andric SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
380dff0c46cSDimitry Andric
3814ba319b5SDimitry Andric /// Function wide BasicBlock to BlockChain mapping.
382dff0c46cSDimitry Andric ///
383dff0c46cSDimitry Andric /// This mapping allows efficiently moving from any given basic block to the
384dff0c46cSDimitry Andric /// BlockChain it participates in, if any. We use it to, among other things,
385dff0c46cSDimitry Andric /// allow implicitly defining edges between chains as the existing edges
386dff0c46cSDimitry Andric /// between basic blocks.
3877a7e6055SDimitry Andric DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
388dff0c46cSDimitry Andric
389d88c1a5aSDimitry Andric #ifndef NDEBUG
390d88c1a5aSDimitry Andric /// The set of basic blocks that have terminators that cannot be fully
391d88c1a5aSDimitry Andric /// analyzed. These basic blocks cannot be re-ordered safely by
392d88c1a5aSDimitry Andric /// MachineBlockPlacement, and we must preserve physical layout of these
393d88c1a5aSDimitry Andric /// blocks and their successors through the pass.
394d88c1a5aSDimitry Andric SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
395d88c1a5aSDimitry Andric #endif
396d88c1a5aSDimitry Andric
397d88c1a5aSDimitry Andric /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
398d88c1a5aSDimitry Andric /// if the count goes to 0, add them to the appropriate work list.
3997a7e6055SDimitry Andric void markChainSuccessors(
4007a7e6055SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
40191bc56edSDimitry Andric const BlockFilterSet *BlockFilter = nullptr);
402d88c1a5aSDimitry Andric
403d88c1a5aSDimitry Andric /// Decrease the UnscheduledPredecessors count for a single block, and
404d88c1a5aSDimitry Andric /// if the count goes to 0, add them to the appropriate work list.
405d88c1a5aSDimitry Andric void markBlockSuccessors(
4067a7e6055SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *BB,
4077a7e6055SDimitry Andric const MachineBasicBlock *LoopHeaderBB,
408d88c1a5aSDimitry Andric const BlockFilterSet *BlockFilter = nullptr);
409d88c1a5aSDimitry Andric
4103ca95b02SDimitry Andric BranchProbability
4117a7e6055SDimitry Andric collectViableSuccessors(
4127a7e6055SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain,
4133ca95b02SDimitry Andric const BlockFilterSet *BlockFilter,
4143ca95b02SDimitry Andric SmallVector<MachineBasicBlock *, 4> &Successors);
4157a7e6055SDimitry Andric bool shouldPredBlockBeOutlined(
4167a7e6055SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
4177a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter,
4187a7e6055SDimitry Andric BranchProbability SuccProb, BranchProbability HotProb);
419d88c1a5aSDimitry Andric bool repeatedlyTailDuplicateBlock(
420d88c1a5aSDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *&LPred,
4217a7e6055SDimitry Andric const MachineBasicBlock *LoopHeaderBB,
422d88c1a5aSDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter,
423d88c1a5aSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt);
4247a7e6055SDimitry Andric bool maybeTailDuplicateBlock(
4257a7e6055SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *LPred,
4267a7e6055SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter,
427d88c1a5aSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt,
4284ba319b5SDimitry Andric bool &DuplicatedToLPred);
4297a7e6055SDimitry Andric bool hasBetterLayoutPredecessor(
4307a7e6055SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
4317a7e6055SDimitry Andric const BlockChain &SuccChain, BranchProbability SuccProb,
4327a7e6055SDimitry Andric BranchProbability RealSuccProb, const BlockChain &Chain,
4333ca95b02SDimitry Andric const BlockFilterSet *BlockFilter);
4347a7e6055SDimitry Andric BlockAndTailDupResult selectBestSuccessor(
4357a7e6055SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain,
436dff0c46cSDimitry Andric const BlockFilterSet *BlockFilter);
4377a7e6055SDimitry Andric MachineBasicBlock *selectBestCandidateBlock(
4387a7e6055SDimitry Andric const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
4397a7e6055SDimitry Andric MachineBasicBlock *getFirstUnplacedBlock(
4407a7e6055SDimitry Andric const BlockChain &PlacedChain,
441dff0c46cSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt,
442dff0c46cSDimitry Andric const BlockFilterSet *BlockFilter);
4433ca95b02SDimitry Andric
4444ba319b5SDimitry Andric /// Add a basic block to the work list if it is appropriate.
4453ca95b02SDimitry Andric ///
4463ca95b02SDimitry Andric /// If the optional parameter BlockFilter is provided, only MBB
4473ca95b02SDimitry Andric /// present in the set will be added to the worklist. If nullptr
4483ca95b02SDimitry Andric /// is provided, no filtering occurs.
4497a7e6055SDimitry Andric void fillWorkLists(const MachineBasicBlock *MBB,
4503ca95b02SDimitry Andric SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
4513ca95b02SDimitry Andric const BlockFilterSet *BlockFilter);
4522cab237bSDimitry Andric
4537a7e6055SDimitry Andric void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
454d88c1a5aSDimitry Andric BlockFilterSet *BlockFilter = nullptr);
4557a7e6055SDimitry Andric MachineBasicBlock *findBestLoopTop(
4567a7e6055SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
4577a7e6055SDimitry Andric MachineBasicBlock *findBestLoopExit(
4587a7e6055SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
4597a7e6055SDimitry Andric BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
4607a7e6055SDimitry Andric void buildLoopChains(const MachineLoop &L);
4617a7e6055SDimitry Andric void rotateLoop(
4627a7e6055SDimitry Andric BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
463cb4dff85SDimitry Andric const BlockFilterSet &LoopBlockSet);
4647a7e6055SDimitry Andric void rotateLoopWithProfile(
4657a7e6055SDimitry Andric BlockChain &LoopChain, const MachineLoop &L,
466dff0c46cSDimitry Andric const BlockFilterSet &LoopBlockSet);
4673ca95b02SDimitry Andric void buildCFGChains();
4683ca95b02SDimitry Andric void optimizeBranches();
4693ca95b02SDimitry Andric void alignBlocks();
4707a7e6055SDimitry Andric /// Returns true if a block should be tail-duplicated to increase fallthrough
4717a7e6055SDimitry Andric /// opportunities.
4727a7e6055SDimitry Andric bool shouldTailDuplicate(MachineBasicBlock *BB);
4737a7e6055SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase
4747a7e6055SDimitry Andric /// fallthroughs.
4757a7e6055SDimitry Andric bool isProfitableToTailDup(
4767a7e6055SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
4774ba319b5SDimitry Andric BranchProbability QProb,
4787a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter);
4792cab237bSDimitry Andric
4807a7e6055SDimitry Andric /// Check for a trellis layout.
4817a7e6055SDimitry Andric bool isTrellis(const MachineBasicBlock *BB,
4827a7e6055SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
4837a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter);
4842cab237bSDimitry Andric
4857a7e6055SDimitry Andric /// Get the best successor given a trellis layout.
4867a7e6055SDimitry Andric BlockAndTailDupResult getBestTrellisSuccessor(
4877a7e6055SDimitry Andric const MachineBasicBlock *BB,
4887a7e6055SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
4897a7e6055SDimitry Andric BranchProbability AdjustedSumProb, const BlockChain &Chain,
4907a7e6055SDimitry Andric const BlockFilterSet *BlockFilter);
4912cab237bSDimitry Andric
4927a7e6055SDimitry Andric /// Get the best pair of non-conflicting edges.
4937a7e6055SDimitry Andric static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
4947a7e6055SDimitry Andric const MachineBasicBlock *BB,
4957a7e6055SDimitry Andric MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
4962cab237bSDimitry Andric
4977a7e6055SDimitry Andric /// Returns true if a block can tail duplicate into all unplaced
4987a7e6055SDimitry Andric /// predecessors. Filters based on loop.
4997a7e6055SDimitry Andric bool canTailDuplicateUnplacedPreds(
5007a7e6055SDimitry Andric const MachineBasicBlock *BB, MachineBasicBlock *Succ,
5017a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter);
5022cab237bSDimitry Andric
5037a7e6055SDimitry Andric /// Find chains of triangles to tail-duplicate where a global analysis works,
5047a7e6055SDimitry Andric /// but a local analysis would not find them.
5057a7e6055SDimitry Andric void precomputeTriangleChains();
506dff0c46cSDimitry Andric
507dff0c46cSDimitry Andric public:
508dff0c46cSDimitry Andric static char ID; // Pass identification, replacement for typeid
5092cab237bSDimitry Andric
MachineBlockPlacement()510dff0c46cSDimitry Andric MachineBlockPlacement() : MachineFunctionPass(ID) {
511dff0c46cSDimitry Andric initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
512dff0c46cSDimitry Andric }
513dff0c46cSDimitry Andric
51491bc56edSDimitry Andric bool runOnMachineFunction(MachineFunction &F) override;
515dff0c46cSDimitry Andric
allowTailDupPlacement() const5166ccc06f6SDimitry Andric bool allowTailDupPlacement() const {
5176ccc06f6SDimitry Andric assert(F);
5186ccc06f6SDimitry Andric return TailDupPlacement && !F->getTarget().requiresStructuredCFG();
5196ccc06f6SDimitry Andric }
5206ccc06f6SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const52191bc56edSDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
522dff0c46cSDimitry Andric AU.addRequired<MachineBranchProbabilityInfo>();
523dff0c46cSDimitry Andric AU.addRequired<MachineBlockFrequencyInfo>();
5247a7e6055SDimitry Andric if (TailDupPlacement)
5257a7e6055SDimitry Andric AU.addRequired<MachinePostDominatorTree>();
526dff0c46cSDimitry Andric AU.addRequired<MachineLoopInfo>();
5273ca95b02SDimitry Andric AU.addRequired<TargetPassConfig>();
528dff0c46cSDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
529dff0c46cSDimitry Andric }
530dff0c46cSDimitry Andric };
5312cab237bSDimitry Andric
5322cab237bSDimitry Andric } // end anonymous namespace
533dff0c46cSDimitry Andric
534dff0c46cSDimitry Andric char MachineBlockPlacement::ID = 0;
5352cab237bSDimitry Andric
536dff0c46cSDimitry Andric char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
5372cab237bSDimitry Andric
538302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE,
539dff0c46cSDimitry Andric "Branch Probability Basic Block Placement", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)540dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
541dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
5427a7e6055SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
543dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
544302affcbSDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE,
545dff0c46cSDimitry Andric "Branch Probability Basic Block Placement", false, false)
546dff0c46cSDimitry Andric
547dff0c46cSDimitry Andric #ifndef NDEBUG
5484ba319b5SDimitry Andric /// Helper to print the name of a MBB.
549dff0c46cSDimitry Andric ///
550dff0c46cSDimitry Andric /// Only used by debug logging.
5517a7e6055SDimitry Andric static std::string getBlockName(const MachineBasicBlock *BB) {
552dff0c46cSDimitry Andric std::string Result;
553dff0c46cSDimitry Andric raw_string_ostream OS(Result);
5542cab237bSDimitry Andric OS << printMBBReference(*BB);
5553ca95b02SDimitry Andric OS << " ('" << BB->getName() << "')";
556dff0c46cSDimitry Andric OS.flush();
557dff0c46cSDimitry Andric return Result;
558dff0c46cSDimitry Andric }
559dff0c46cSDimitry Andric #endif
560dff0c46cSDimitry Andric
5614ba319b5SDimitry Andric /// Mark a chain's successors as having one fewer preds.
562dff0c46cSDimitry Andric ///
563dff0c46cSDimitry Andric /// When a chain is being merged into the "placed" chain, this routine will
564dff0c46cSDimitry Andric /// quickly walk the successors of each block in the chain and mark them as
565dff0c46cSDimitry Andric /// having one fewer active predecessor. It also adds any successors of this
566d88c1a5aSDimitry Andric /// chain which reach the zero-predecessor state to the appropriate worklist.
markChainSuccessors(const BlockChain & Chain,const MachineBasicBlock * LoopHeaderBB,const BlockFilterSet * BlockFilter)567dff0c46cSDimitry Andric void MachineBlockPlacement::markChainSuccessors(
5687a7e6055SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
569dff0c46cSDimitry Andric const BlockFilterSet *BlockFilter) {
570dff0c46cSDimitry Andric // Walk all the blocks in this chain, marking their successors as having
571dff0c46cSDimitry Andric // a predecessor placed.
572ff0cc061SDimitry Andric for (MachineBasicBlock *MBB : Chain) {
573d88c1a5aSDimitry Andric markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
574d88c1a5aSDimitry Andric }
575d88c1a5aSDimitry Andric }
576d88c1a5aSDimitry Andric
5774ba319b5SDimitry Andric /// Mark a single block's successors as having one fewer preds.
578d88c1a5aSDimitry Andric ///
579d88c1a5aSDimitry Andric /// Under normal circumstances, this is only called by markChainSuccessors,
580d88c1a5aSDimitry Andric /// but if a block that was to be placed is completely tail-duplicated away,
581d88c1a5aSDimitry Andric /// and was duplicated into the chain end, we need to redo markBlockSuccessors
582d88c1a5aSDimitry Andric /// for just that block.
markBlockSuccessors(const BlockChain & Chain,const MachineBasicBlock * MBB,const MachineBasicBlock * LoopHeaderBB,const BlockFilterSet * BlockFilter)583d88c1a5aSDimitry Andric void MachineBlockPlacement::markBlockSuccessors(
5847a7e6055SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *MBB,
5857a7e6055SDimitry Andric const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
586dff0c46cSDimitry Andric // Add any successors for which this is the only un-placed in-loop
587dff0c46cSDimitry Andric // predecessor to the worklist as a viable candidate for CFG-neutral
588dff0c46cSDimitry Andric // placement. No subsequent placement of this block will violate the CFG
589dff0c46cSDimitry Andric // shape, so we get to use heuristics to choose a favorable placement.
590ff0cc061SDimitry Andric for (MachineBasicBlock *Succ : MBB->successors()) {
591ff0cc061SDimitry Andric if (BlockFilter && !BlockFilter->count(Succ))
592dff0c46cSDimitry Andric continue;
593ff0cc061SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ];
594dff0c46cSDimitry Andric // Disregard edges within a fixed chain, or edges to the loop header.
595ff0cc061SDimitry Andric if (&Chain == &SuccChain || Succ == LoopHeaderBB)
596dff0c46cSDimitry Andric continue;
597dff0c46cSDimitry Andric
598dff0c46cSDimitry Andric // This is a cross-chain edge that is within the loop, so decrement the
599dff0c46cSDimitry Andric // loop predecessor count of the destination chain.
6003ca95b02SDimitry Andric if (SuccChain.UnscheduledPredecessors == 0 ||
6013ca95b02SDimitry Andric --SuccChain.UnscheduledPredecessors > 0)
6023ca95b02SDimitry Andric continue;
6033ca95b02SDimitry Andric
604d88c1a5aSDimitry Andric auto *NewBB = *SuccChain.begin();
605d88c1a5aSDimitry Andric if (NewBB->isEHPad())
606d88c1a5aSDimitry Andric EHPadWorkList.push_back(NewBB);
6073ca95b02SDimitry Andric else
608d88c1a5aSDimitry Andric BlockWorkList.push_back(NewBB);
609dff0c46cSDimitry Andric }
610dff0c46cSDimitry Andric }
611dff0c46cSDimitry Andric
6123ca95b02SDimitry Andric /// This helper function collects the set of successors of block
6133ca95b02SDimitry Andric /// \p BB that are allowed to be its layout successors, and return
6143ca95b02SDimitry Andric /// the total branch probability of edges from \p BB to those
6153ca95b02SDimitry Andric /// blocks.
collectViableSuccessors(const MachineBasicBlock * BB,const BlockChain & Chain,const BlockFilterSet * BlockFilter,SmallVector<MachineBasicBlock *,4> & Successors)6163ca95b02SDimitry Andric BranchProbability MachineBlockPlacement::collectViableSuccessors(
6177a7e6055SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain,
6187a7e6055SDimitry Andric const BlockFilterSet *BlockFilter,
6193ca95b02SDimitry Andric SmallVector<MachineBasicBlock *, 4> &Successors) {
6203ca95b02SDimitry Andric // Adjust edge probabilities by excluding edges pointing to blocks that is
6213ca95b02SDimitry Andric // either not in BlockFilter or is already in the current chain. Consider the
6223ca95b02SDimitry Andric // following CFG:
6233ca95b02SDimitry Andric //
6243ca95b02SDimitry Andric // --->A
6253ca95b02SDimitry Andric // | / \
6263ca95b02SDimitry Andric // | B C
6273ca95b02SDimitry Andric // | \ / \
6283ca95b02SDimitry Andric // ----D E
6293ca95b02SDimitry Andric //
6303ca95b02SDimitry Andric // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
6313ca95b02SDimitry Andric // A->C is chosen as a fall-through, D won't be selected as a successor of C
6323ca95b02SDimitry Andric // due to CFG constraint (the probability of C->D is not greater than
63324d58133SDimitry Andric // HotProb to break topo-order). If we exclude E that is not in BlockFilter
6343ca95b02SDimitry Andric // when calculating the probability of C->D, D will be selected and we
6353ca95b02SDimitry Andric // will get A C D B as the layout of this loop.
6363ca95b02SDimitry Andric auto AdjustedSumProb = BranchProbability::getOne();
6373ca95b02SDimitry Andric for (MachineBasicBlock *Succ : BB->successors()) {
6383ca95b02SDimitry Andric bool SkipSucc = false;
6393ca95b02SDimitry Andric if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
6403ca95b02SDimitry Andric SkipSucc = true;
6413ca95b02SDimitry Andric } else {
6423ca95b02SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ];
6433ca95b02SDimitry Andric if (SuccChain == &Chain) {
6443ca95b02SDimitry Andric SkipSucc = true;
6453ca95b02SDimitry Andric } else if (Succ != *SuccChain->begin()) {
6464ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " " << getBlockName(Succ)
6474ba319b5SDimitry Andric << " -> Mid chain!\n");
6483ca95b02SDimitry Andric continue;
6493ca95b02SDimitry Andric }
6503ca95b02SDimitry Andric }
6513ca95b02SDimitry Andric if (SkipSucc)
6523ca95b02SDimitry Andric AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
6533ca95b02SDimitry Andric else
6543ca95b02SDimitry Andric Successors.push_back(Succ);
6553ca95b02SDimitry Andric }
6563ca95b02SDimitry Andric
6573ca95b02SDimitry Andric return AdjustedSumProb;
6583ca95b02SDimitry Andric }
6593ca95b02SDimitry Andric
6603ca95b02SDimitry Andric /// The helper function returns the branch probability that is adjusted
6613ca95b02SDimitry Andric /// or normalized over the new total \p AdjustedSumProb.
6623ca95b02SDimitry Andric static BranchProbability
getAdjustedProbability(BranchProbability OrigProb,BranchProbability AdjustedSumProb)6633ca95b02SDimitry Andric getAdjustedProbability(BranchProbability OrigProb,
6643ca95b02SDimitry Andric BranchProbability AdjustedSumProb) {
6653ca95b02SDimitry Andric BranchProbability SuccProb;
6663ca95b02SDimitry Andric uint32_t SuccProbN = OrigProb.getNumerator();
6673ca95b02SDimitry Andric uint32_t SuccProbD = AdjustedSumProb.getNumerator();
6683ca95b02SDimitry Andric if (SuccProbN >= SuccProbD)
6693ca95b02SDimitry Andric SuccProb = BranchProbability::getOne();
6703ca95b02SDimitry Andric else
6713ca95b02SDimitry Andric SuccProb = BranchProbability(SuccProbN, SuccProbD);
6723ca95b02SDimitry Andric
6733ca95b02SDimitry Andric return SuccProb;
6743ca95b02SDimitry Andric }
6753ca95b02SDimitry Andric
6767a7e6055SDimitry Andric /// Check if \p BB has exactly the successors in \p Successors.
6777a7e6055SDimitry Andric static bool
hasSameSuccessors(MachineBasicBlock & BB,SmallPtrSetImpl<const MachineBasicBlock * > & Successors)6787a7e6055SDimitry Andric hasSameSuccessors(MachineBasicBlock &BB,
6797a7e6055SDimitry Andric SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
6807a7e6055SDimitry Andric if (BB.succ_size() != Successors.size())
6813ca95b02SDimitry Andric return false;
6827a7e6055SDimitry Andric // We don't want to count self-loops
6837a7e6055SDimitry Andric if (Successors.count(&BB))
6847a7e6055SDimitry Andric return false;
6857a7e6055SDimitry Andric for (MachineBasicBlock *Succ : BB.successors())
6867a7e6055SDimitry Andric if (!Successors.count(Succ))
6877a7e6055SDimitry Andric return false;
6887a7e6055SDimitry Andric return true;
6897a7e6055SDimitry Andric }
6907a7e6055SDimitry Andric
6917a7e6055SDimitry Andric /// Check if a block should be tail duplicated to increase fallthrough
6927a7e6055SDimitry Andric /// opportunities.
6937a7e6055SDimitry Andric /// \p BB Block to check.
shouldTailDuplicate(MachineBasicBlock * BB)6947a7e6055SDimitry Andric bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
6957a7e6055SDimitry Andric // Blocks with single successors don't create additional fallthrough
6967a7e6055SDimitry Andric // opportunities. Don't duplicate them. TODO: When conditional exits are
6977a7e6055SDimitry Andric // analyzable, allow them to be duplicated.
6987a7e6055SDimitry Andric bool IsSimple = TailDup.isSimpleBB(BB);
6997a7e6055SDimitry Andric
7007a7e6055SDimitry Andric if (BB->succ_size() == 1)
7017a7e6055SDimitry Andric return false;
7027a7e6055SDimitry Andric return TailDup.shouldTailDuplicate(IsSimple, *BB);
7037a7e6055SDimitry Andric }
7047a7e6055SDimitry Andric
7057a7e6055SDimitry Andric /// Compare 2 BlockFrequency's with a small penalty for \p A.
7067a7e6055SDimitry Andric /// In order to be conservative, we apply a X% penalty to account for
7077a7e6055SDimitry Andric /// increased icache pressure and static heuristics. For small frequencies
7087a7e6055SDimitry Andric /// we use only the numerators to improve accuracy. For simplicity, we assume the
7097a7e6055SDimitry Andric /// penalty is less than 100%
7107a7e6055SDimitry Andric /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
greaterWithBias(BlockFrequency A,BlockFrequency B,uint64_t EntryFreq)7117a7e6055SDimitry Andric static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
7127a7e6055SDimitry Andric uint64_t EntryFreq) {
7137a7e6055SDimitry Andric BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
7147a7e6055SDimitry Andric BlockFrequency Gain = A - B;
7157a7e6055SDimitry Andric return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
7167a7e6055SDimitry Andric }
7177a7e6055SDimitry Andric
7187a7e6055SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase
7197a7e6055SDimitry Andric /// fallthroughs. It only makes sense to call this function when
7207a7e6055SDimitry Andric /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
7217a7e6055SDimitry Andric /// always locally profitable if we would have picked \p Succ without
7227a7e6055SDimitry Andric /// considering duplication.
isProfitableToTailDup(const MachineBasicBlock * BB,const MachineBasicBlock * Succ,BranchProbability QProb,const BlockChain & Chain,const BlockFilterSet * BlockFilter)7237a7e6055SDimitry Andric bool MachineBlockPlacement::isProfitableToTailDup(
7247a7e6055SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
7257a7e6055SDimitry Andric BranchProbability QProb,
7267a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
7277a7e6055SDimitry Andric // We need to do a probability calculation to make sure this is profitable.
7287a7e6055SDimitry Andric // First: does succ have a successor that post-dominates? This affects the
7297a7e6055SDimitry Andric // calculation. The 2 relevant cases are:
7307a7e6055SDimitry Andric // BB BB
7317a7e6055SDimitry Andric // | \Qout | \Qout
7327a7e6055SDimitry Andric // P| C |P C
7337a7e6055SDimitry Andric // = C' = C'
7347a7e6055SDimitry Andric // | /Qin | /Qin
7357a7e6055SDimitry Andric // | / | /
7367a7e6055SDimitry Andric // Succ Succ
7377a7e6055SDimitry Andric // / \ | \ V
7387a7e6055SDimitry Andric // U/ =V |U \
7397a7e6055SDimitry Andric // / \ = D
7407a7e6055SDimitry Andric // D E | /
7417a7e6055SDimitry Andric // | /
7427a7e6055SDimitry Andric // |/
7437a7e6055SDimitry Andric // PDom
7447a7e6055SDimitry Andric // '=' : Branch taken for that CFG edge
7457a7e6055SDimitry Andric // In the second case, Placing Succ while duplicating it into C prevents the
7467a7e6055SDimitry Andric // fallthrough of Succ into either D or PDom, because they now have C as an
7477a7e6055SDimitry Andric // unplaced predecessor
7487a7e6055SDimitry Andric
7497a7e6055SDimitry Andric // Start by figuring out which case we fall into
7507a7e6055SDimitry Andric MachineBasicBlock *PDom = nullptr;
7517a7e6055SDimitry Andric SmallVector<MachineBasicBlock *, 4> SuccSuccs;
7527a7e6055SDimitry Andric // Only scan the relevant successors
7537a7e6055SDimitry Andric auto AdjustedSuccSumProb =
7547a7e6055SDimitry Andric collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
7557a7e6055SDimitry Andric BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
7567a7e6055SDimitry Andric auto BBFreq = MBFI->getBlockFreq(BB);
7577a7e6055SDimitry Andric auto SuccFreq = MBFI->getBlockFreq(Succ);
7587a7e6055SDimitry Andric BlockFrequency P = BBFreq * PProb;
7597a7e6055SDimitry Andric BlockFrequency Qout = BBFreq * QProb;
7607a7e6055SDimitry Andric uint64_t EntryFreq = MBFI->getEntryFreq();
7617a7e6055SDimitry Andric // If there are no more successors, it is profitable to copy, as it strictly
7627a7e6055SDimitry Andric // increases fallthrough.
7637a7e6055SDimitry Andric if (SuccSuccs.size() == 0)
7647a7e6055SDimitry Andric return greaterWithBias(P, Qout, EntryFreq);
7657a7e6055SDimitry Andric
7667a7e6055SDimitry Andric auto BestSuccSucc = BranchProbability::getZero();
7677a7e6055SDimitry Andric // Find the PDom or the best Succ if no PDom exists.
7687a7e6055SDimitry Andric for (MachineBasicBlock *SuccSucc : SuccSuccs) {
7697a7e6055SDimitry Andric auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
7707a7e6055SDimitry Andric if (Prob > BestSuccSucc)
7717a7e6055SDimitry Andric BestSuccSucc = Prob;
7727a7e6055SDimitry Andric if (PDom == nullptr)
7737a7e6055SDimitry Andric if (MPDT->dominates(SuccSucc, Succ)) {
7747a7e6055SDimitry Andric PDom = SuccSucc;
7757a7e6055SDimitry Andric break;
7767a7e6055SDimitry Andric }
7777a7e6055SDimitry Andric }
7787a7e6055SDimitry Andric // For the comparisons, we need to know Succ's best incoming edge that isn't
7797a7e6055SDimitry Andric // from BB.
7807a7e6055SDimitry Andric auto SuccBestPred = BlockFrequency(0);
7817a7e6055SDimitry Andric for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
7827a7e6055SDimitry Andric if (SuccPred == Succ || SuccPred == BB
7837a7e6055SDimitry Andric || BlockToChain[SuccPred] == &Chain
7847a7e6055SDimitry Andric || (BlockFilter && !BlockFilter->count(SuccPred)))
7853ca95b02SDimitry Andric continue;
7867a7e6055SDimitry Andric auto Freq = MBFI->getBlockFreq(SuccPred)
7877a7e6055SDimitry Andric * MBPI->getEdgeProbability(SuccPred, Succ);
7887a7e6055SDimitry Andric if (Freq > SuccBestPred)
7897a7e6055SDimitry Andric SuccBestPred = Freq;
7907a7e6055SDimitry Andric }
7917a7e6055SDimitry Andric // Qin is Succ's best unplaced incoming edge that isn't BB
7927a7e6055SDimitry Andric BlockFrequency Qin = SuccBestPred;
7937a7e6055SDimitry Andric // If it doesn't have a post-dominating successor, here is the calculation:
7947a7e6055SDimitry Andric // BB BB
7957a7e6055SDimitry Andric // | \Qout | \
7967a7e6055SDimitry Andric // P| C | =
7977a7e6055SDimitry Andric // = C' | C
7987a7e6055SDimitry Andric // | /Qin | |
7997a7e6055SDimitry Andric // | / | C' (+Succ)
8007a7e6055SDimitry Andric // Succ Succ /|
8017a7e6055SDimitry Andric // / \ | \/ |
8027a7e6055SDimitry Andric // U/ =V | == |
8037a7e6055SDimitry Andric // / \ | / \|
8047a7e6055SDimitry Andric // D E D E
8057a7e6055SDimitry Andric // '=' : Branch taken for that CFG edge
8067a7e6055SDimitry Andric // Cost in the first case is: P + V
8077a7e6055SDimitry Andric // For this calculation, we always assume P > Qout. If Qout > P
8087a7e6055SDimitry Andric // The result of this function will be ignored at the caller.
8097a7e6055SDimitry Andric // Let F = SuccFreq - Qin
8107a7e6055SDimitry Andric // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
8117a7e6055SDimitry Andric
8127a7e6055SDimitry Andric if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
8137a7e6055SDimitry Andric BranchProbability UProb = BestSuccSucc;
8147a7e6055SDimitry Andric BranchProbability VProb = AdjustedSuccSumProb - UProb;
8157a7e6055SDimitry Andric BlockFrequency F = SuccFreq - Qin;
8167a7e6055SDimitry Andric BlockFrequency V = SuccFreq * VProb;
8177a7e6055SDimitry Andric BlockFrequency QinU = std::min(Qin, F) * UProb;
8187a7e6055SDimitry Andric BlockFrequency BaseCost = P + V;
8197a7e6055SDimitry Andric BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
8207a7e6055SDimitry Andric return greaterWithBias(BaseCost, DupCost, EntryFreq);
8217a7e6055SDimitry Andric }
8227a7e6055SDimitry Andric BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
8237a7e6055SDimitry Andric BranchProbability VProb = AdjustedSuccSumProb - UProb;
8247a7e6055SDimitry Andric BlockFrequency U = SuccFreq * UProb;
8257a7e6055SDimitry Andric BlockFrequency V = SuccFreq * VProb;
8267a7e6055SDimitry Andric BlockFrequency F = SuccFreq - Qin;
8277a7e6055SDimitry Andric // If there is a post-dominating successor, here is the calculation:
8287a7e6055SDimitry Andric // BB BB BB BB
8297a7e6055SDimitry Andric // | \Qout | \ | \Qout | \
8307a7e6055SDimitry Andric // |P C | = |P C | =
8317a7e6055SDimitry Andric // = C' |P C = C' |P C
8327a7e6055SDimitry Andric // | /Qin | | | /Qin | |
8337a7e6055SDimitry Andric // | / | C' (+Succ) | / | C' (+Succ)
8347a7e6055SDimitry Andric // Succ Succ /| Succ Succ /|
8357a7e6055SDimitry Andric // | \ V | \/ | | \ V | \/ |
8367a7e6055SDimitry Andric // |U \ |U /\ =? |U = |U /\ |
8377a7e6055SDimitry Andric // = D = = =?| | D | = =|
8387a7e6055SDimitry Andric // | / |/ D | / |/ D
8397a7e6055SDimitry Andric // | / | / | = | /
8407a7e6055SDimitry Andric // |/ | / |/ | =
8417a7e6055SDimitry Andric // Dom Dom Dom Dom
8427a7e6055SDimitry Andric // '=' : Branch taken for that CFG edge
8437a7e6055SDimitry Andric // The cost for taken branches in the first case is P + U
8447a7e6055SDimitry Andric // Let F = SuccFreq - Qin
8457a7e6055SDimitry Andric // The cost in the second case (assuming independence), given the layout:
8467a7e6055SDimitry Andric // BB, Succ, (C+Succ), D, Dom or the layout:
8477a7e6055SDimitry Andric // BB, Succ, D, Dom, (C+Succ)
8487a7e6055SDimitry Andric // is Qout + max(F, Qin) * U + min(F, Qin)
8497a7e6055SDimitry Andric // compare P + U vs Qout + P * U + Qin.
8507a7e6055SDimitry Andric //
8517a7e6055SDimitry Andric // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
8527a7e6055SDimitry Andric //
8537a7e6055SDimitry Andric // For the 3rd case, the cost is P + 2 * V
8547a7e6055SDimitry Andric // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
8557a7e6055SDimitry Andric // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
8567a7e6055SDimitry Andric if (UProb > AdjustedSuccSumProb / 2 &&
8577a7e6055SDimitry Andric !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
8587a7e6055SDimitry Andric Chain, BlockFilter))
8597a7e6055SDimitry Andric // Cases 3 & 4
8607a7e6055SDimitry Andric return greaterWithBias(
8617a7e6055SDimitry Andric (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
8627a7e6055SDimitry Andric EntryFreq);
8637a7e6055SDimitry Andric // Cases 1 & 2
8647a7e6055SDimitry Andric return greaterWithBias((P + U),
8657a7e6055SDimitry Andric (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
8667a7e6055SDimitry Andric std::max(Qin, F) * UProb),
8677a7e6055SDimitry Andric EntryFreq);
8687a7e6055SDimitry Andric }
8697a7e6055SDimitry Andric
8707a7e6055SDimitry Andric /// Check for a trellis layout. \p BB is the upper part of a trellis if its
8717a7e6055SDimitry Andric /// successors form the lower part of a trellis. A successor set S forms the
8727a7e6055SDimitry Andric /// lower part of a trellis if all of the predecessors of S are either in S or
8737a7e6055SDimitry Andric /// have all of S as successors. We ignore trellises where BB doesn't have 2
8747a7e6055SDimitry Andric /// successors because for fewer than 2, it's trivial, and for 3 or greater they
8757a7e6055SDimitry Andric /// are very uncommon and complex to compute optimally. Allowing edges within S
8767a7e6055SDimitry 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)8777a7e6055SDimitry Andric bool MachineBlockPlacement::isTrellis(
8787a7e6055SDimitry Andric const MachineBasicBlock *BB,
8797a7e6055SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
8807a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
8817a7e6055SDimitry Andric // Technically BB could form a trellis with branching factor higher than 2.
8827a7e6055SDimitry Andric // But that's extremely uncommon.
8837a7e6055SDimitry Andric if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
8847a7e6055SDimitry Andric return false;
8857a7e6055SDimitry Andric
8867a7e6055SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
8877a7e6055SDimitry Andric BB->succ_end());
8887a7e6055SDimitry Andric // To avoid reviewing the same predecessors twice.
8897a7e6055SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
8907a7e6055SDimitry Andric
8917a7e6055SDimitry Andric for (MachineBasicBlock *Succ : ViableSuccs) {
8927a7e6055SDimitry Andric int PredCount = 0;
8937a7e6055SDimitry Andric for (auto SuccPred : Succ->predecessors()) {
8947a7e6055SDimitry Andric // Allow triangle successors, but don't count them.
8957a7e6055SDimitry Andric if (Successors.count(SuccPred)) {
8967a7e6055SDimitry Andric // Make sure that it is actually a triangle.
8977a7e6055SDimitry Andric for (MachineBasicBlock *CheckSucc : SuccPred->successors())
8987a7e6055SDimitry Andric if (!Successors.count(CheckSucc))
8997a7e6055SDimitry Andric return false;
9003ca95b02SDimitry Andric continue;
9017a7e6055SDimitry Andric }
9027a7e6055SDimitry Andric const BlockChain *PredChain = BlockToChain[SuccPred];
9037a7e6055SDimitry Andric if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
9047a7e6055SDimitry Andric PredChain == &Chain || PredChain == BlockToChain[Succ])
9057a7e6055SDimitry Andric continue;
9067a7e6055SDimitry Andric ++PredCount;
9077a7e6055SDimitry Andric // Perform the successor check only once.
9087a7e6055SDimitry Andric if (!SeenPreds.insert(SuccPred).second)
9097a7e6055SDimitry Andric continue;
9107a7e6055SDimitry Andric if (!hasSameSuccessors(*SuccPred, Successors))
9117a7e6055SDimitry Andric return false;
9127a7e6055SDimitry Andric }
9137a7e6055SDimitry Andric // If one of the successors has only BB as a predecessor, it is not a
9147a7e6055SDimitry Andric // trellis.
9157a7e6055SDimitry Andric if (PredCount < 1)
9163ca95b02SDimitry Andric return false;
9173ca95b02SDimitry Andric }
9183ca95b02SDimitry Andric return true;
9197a7e6055SDimitry Andric }
9207a7e6055SDimitry Andric
9217a7e6055SDimitry Andric /// Pick the highest total weight pair of edges that can both be laid out.
9227a7e6055SDimitry Andric /// The edges in \p Edges[0] are assumed to have a different destination than
9237a7e6055SDimitry Andric /// the edges in \p Edges[1]. Simple counting shows that the best pair is either
9247a7e6055SDimitry Andric /// the individual highest weight edges to the 2 different destinations, or in
9257a7e6055SDimitry Andric /// case of a conflict, one of them should be replaced with a 2nd best edge.
9267a7e6055SDimitry Andric std::pair<MachineBlockPlacement::WeightedEdge,
9277a7e6055SDimitry Andric MachineBlockPlacement::WeightedEdge>
getBestNonConflictingEdges(const MachineBasicBlock * BB,MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge,8>> Edges)9287a7e6055SDimitry Andric MachineBlockPlacement::getBestNonConflictingEdges(
9297a7e6055SDimitry Andric const MachineBasicBlock *BB,
9307a7e6055SDimitry Andric MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
9317a7e6055SDimitry Andric Edges) {
9327a7e6055SDimitry Andric // Sort the edges, and then for each successor, find the best incoming
9337a7e6055SDimitry Andric // predecessor. If the best incoming predecessors aren't the same,
9347a7e6055SDimitry Andric // then that is clearly the best layout. If there is a conflict, one of the
9357a7e6055SDimitry Andric // successors will have to fallthrough from the second best predecessor. We
9367a7e6055SDimitry Andric // compare which combination is better overall.
9377a7e6055SDimitry Andric
9387a7e6055SDimitry Andric // Sort for highest frequency.
9397a7e6055SDimitry Andric auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
9407a7e6055SDimitry Andric
9417a7e6055SDimitry Andric std::stable_sort(Edges[0].begin(), Edges[0].end(), Cmp);
9427a7e6055SDimitry Andric std::stable_sort(Edges[1].begin(), Edges[1].end(), Cmp);
9437a7e6055SDimitry Andric auto BestA = Edges[0].begin();
9447a7e6055SDimitry Andric auto BestB = Edges[1].begin();
9457a7e6055SDimitry Andric // Arrange for the correct answer to be in BestA and BestB
9467a7e6055SDimitry Andric // If the 2 best edges don't conflict, the answer is already there.
9477a7e6055SDimitry Andric if (BestA->Src == BestB->Src) {
9487a7e6055SDimitry Andric // Compare the total fallthrough of (Best + Second Best) for both pairs
9497a7e6055SDimitry Andric auto SecondBestA = std::next(BestA);
9507a7e6055SDimitry Andric auto SecondBestB = std::next(BestB);
9517a7e6055SDimitry Andric BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
9527a7e6055SDimitry Andric BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
9537a7e6055SDimitry Andric if (BestAScore < BestBScore)
9547a7e6055SDimitry Andric BestA = SecondBestA;
9557a7e6055SDimitry Andric else
9567a7e6055SDimitry Andric BestB = SecondBestB;
9577a7e6055SDimitry Andric }
9587a7e6055SDimitry Andric // Arrange for the BB edge to be in BestA if it exists.
9597a7e6055SDimitry Andric if (BestB->Src == BB)
9607a7e6055SDimitry Andric std::swap(BestA, BestB);
9617a7e6055SDimitry Andric return std::make_pair(*BestA, *BestB);
9627a7e6055SDimitry Andric }
9637a7e6055SDimitry Andric
9647a7e6055SDimitry Andric /// Get the best successor from \p BB based on \p BB being part of a trellis.
9657a7e6055SDimitry Andric /// We only handle trellises with 2 successors, so the algorithm is
9667a7e6055SDimitry Andric /// straightforward: Find the best pair of edges that don't conflict. We find
9677a7e6055SDimitry Andric /// the best incoming edge for each successor in the trellis. If those conflict,
9687a7e6055SDimitry Andric /// we consider which of them should be replaced with the second best.
9697a7e6055SDimitry Andric /// Upon return the two best edges will be in \p BestEdges. If one of the edges
9707a7e6055SDimitry Andric /// comes from \p BB, it will be in \p BestEdges[0]
9717a7e6055SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult
getBestTrellisSuccessor(const MachineBasicBlock * BB,const SmallVectorImpl<MachineBasicBlock * > & ViableSuccs,BranchProbability AdjustedSumProb,const BlockChain & Chain,const BlockFilterSet * BlockFilter)9727a7e6055SDimitry Andric MachineBlockPlacement::getBestTrellisSuccessor(
9737a7e6055SDimitry Andric const MachineBasicBlock *BB,
9747a7e6055SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
9757a7e6055SDimitry Andric BranchProbability AdjustedSumProb, const BlockChain &Chain,
9767a7e6055SDimitry Andric const BlockFilterSet *BlockFilter) {
9777a7e6055SDimitry Andric
9787a7e6055SDimitry Andric BlockAndTailDupResult Result = {nullptr, false};
9797a7e6055SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
9807a7e6055SDimitry Andric BB->succ_end());
9817a7e6055SDimitry Andric
9827a7e6055SDimitry Andric // We assume size 2 because it's common. For general n, we would have to do
9837a7e6055SDimitry Andric // the Hungarian algorithm, but it's not worth the complexity because more
9847a7e6055SDimitry Andric // than 2 successors is fairly uncommon, and a trellis even more so.
9857a7e6055SDimitry Andric if (Successors.size() != 2 || ViableSuccs.size() != 2)
9867a7e6055SDimitry Andric return Result;
9877a7e6055SDimitry Andric
9887a7e6055SDimitry Andric // Collect the edge frequencies of all edges that form the trellis.
9897a7e6055SDimitry Andric SmallVector<WeightedEdge, 8> Edges[2];
9907a7e6055SDimitry Andric int SuccIndex = 0;
9917a7e6055SDimitry Andric for (auto Succ : ViableSuccs) {
9927a7e6055SDimitry Andric for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
9937a7e6055SDimitry Andric // Skip any placed predecessors that are not BB
9947a7e6055SDimitry Andric if (SuccPred != BB)
9957a7e6055SDimitry Andric if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
9967a7e6055SDimitry Andric BlockToChain[SuccPred] == &Chain ||
9977a7e6055SDimitry Andric BlockToChain[SuccPred] == BlockToChain[Succ])
9987a7e6055SDimitry Andric continue;
9997a7e6055SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
10007a7e6055SDimitry Andric MBPI->getEdgeProbability(SuccPred, Succ);
10017a7e6055SDimitry Andric Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
10027a7e6055SDimitry Andric }
10037a7e6055SDimitry Andric ++SuccIndex;
10047a7e6055SDimitry Andric }
10057a7e6055SDimitry Andric
10067a7e6055SDimitry Andric // Pick the best combination of 2 edges from all the edges in the trellis.
10077a7e6055SDimitry Andric WeightedEdge BestA, BestB;
10087a7e6055SDimitry Andric std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
10097a7e6055SDimitry Andric
10107a7e6055SDimitry Andric if (BestA.Src != BB) {
10117a7e6055SDimitry Andric // If we have a trellis, and BB doesn't have the best fallthrough edges,
10127a7e6055SDimitry Andric // we shouldn't choose any successor. We've already looked and there's a
10137a7e6055SDimitry Andric // better fallthrough edge for all the successors.
10144ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
10157a7e6055SDimitry Andric return Result;
10167a7e6055SDimitry Andric }
10177a7e6055SDimitry Andric
10187a7e6055SDimitry Andric // Did we pick the triangle edge? If tail-duplication is profitable, do
10197a7e6055SDimitry Andric // that instead. Otherwise merge the triangle edge now while we know it is
10207a7e6055SDimitry Andric // optimal.
10217a7e6055SDimitry Andric if (BestA.Dest == BestB.Src) {
10227a7e6055SDimitry Andric // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
10237a7e6055SDimitry Andric // would be better.
10247a7e6055SDimitry Andric MachineBasicBlock *Succ1 = BestA.Dest;
10257a7e6055SDimitry Andric MachineBasicBlock *Succ2 = BestB.Dest;
10267a7e6055SDimitry Andric // Check to see if tail-duplication would be profitable.
10276ccc06f6SDimitry Andric if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) &&
10287a7e6055SDimitry Andric canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
10297a7e6055SDimitry Andric isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
10307a7e6055SDimitry Andric Chain, BlockFilter)) {
10314ba319b5SDimitry Andric LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
10327a7e6055SDimitry Andric MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
10337a7e6055SDimitry Andric dbgs() << " Selected: " << getBlockName(Succ2)
10344ba319b5SDimitry Andric << ", probability: " << Succ2Prob
10354ba319b5SDimitry Andric << " (Tail Duplicate)\n");
10367a7e6055SDimitry Andric Result.BB = Succ2;
10377a7e6055SDimitry Andric Result.ShouldTailDup = true;
10387a7e6055SDimitry Andric return Result;
10397a7e6055SDimitry Andric }
10407a7e6055SDimitry Andric }
10417a7e6055SDimitry Andric // We have already computed the optimal edge for the other side of the
10427a7e6055SDimitry Andric // trellis.
10437a7e6055SDimitry Andric ComputedEdges[BestB.Src] = { BestB.Dest, false };
10447a7e6055SDimitry Andric
10457a7e6055SDimitry Andric auto TrellisSucc = BestA.Dest;
10464ba319b5SDimitry Andric LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability(
10477a7e6055SDimitry Andric MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
10487a7e6055SDimitry Andric dbgs() << " Selected: " << getBlockName(TrellisSucc)
10497a7e6055SDimitry Andric << ", probability: " << SuccProb << " (Trellis)\n");
10507a7e6055SDimitry Andric Result.BB = TrellisSucc;
10517a7e6055SDimitry Andric return Result;
10527a7e6055SDimitry Andric }
10537a7e6055SDimitry Andric
10546ccc06f6SDimitry Andric /// When the option allowTailDupPlacement() is on, this method checks if the
10557a7e6055SDimitry Andric /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
10567a7e6055SDimitry Andric /// into all of its unplaced, unfiltered predecessors, that are not BB.
canTailDuplicateUnplacedPreds(const MachineBasicBlock * BB,MachineBasicBlock * Succ,const BlockChain & Chain,const BlockFilterSet * BlockFilter)10577a7e6055SDimitry Andric bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
10587a7e6055SDimitry Andric const MachineBasicBlock *BB, MachineBasicBlock *Succ,
10597a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
10607a7e6055SDimitry Andric if (!shouldTailDuplicate(Succ))
10613ca95b02SDimitry Andric return false;
10627a7e6055SDimitry Andric
10637a7e6055SDimitry Andric // For CFG checking.
10647a7e6055SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
10657a7e6055SDimitry Andric BB->succ_end());
10667a7e6055SDimitry Andric for (MachineBasicBlock *Pred : Succ->predecessors()) {
10677a7e6055SDimitry Andric // Make sure all unplaced and unfiltered predecessors can be
10687a7e6055SDimitry Andric // tail-duplicated into.
10697a7e6055SDimitry Andric // Skip any blocks that are already placed or not in this loop.
10707a7e6055SDimitry Andric if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
10717a7e6055SDimitry Andric || BlockToChain[Pred] == &Chain)
10727a7e6055SDimitry Andric continue;
10737a7e6055SDimitry Andric if (!TailDup.canTailDuplicate(Succ, Pred)) {
10747a7e6055SDimitry Andric if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
10757a7e6055SDimitry Andric // This will result in a trellis after tail duplication, so we don't
10767a7e6055SDimitry Andric // need to copy Succ into this predecessor. In the presence
10777a7e6055SDimitry Andric // of a trellis tail duplication can continue to be profitable.
10787a7e6055SDimitry Andric // For example:
10797a7e6055SDimitry Andric // A A
10807a7e6055SDimitry Andric // |\ |\
10817a7e6055SDimitry Andric // | \ | \
10827a7e6055SDimitry Andric // | C | C+BB
10837a7e6055SDimitry Andric // | / | |
10847a7e6055SDimitry Andric // |/ | |
10857a7e6055SDimitry Andric // BB => BB |
10867a7e6055SDimitry Andric // |\ |\/|
10877a7e6055SDimitry Andric // | \ |/\|
10887a7e6055SDimitry Andric // | D | D
10897a7e6055SDimitry Andric // | / | /
10907a7e6055SDimitry Andric // |/ |/
10917a7e6055SDimitry Andric // Succ Succ
10927a7e6055SDimitry Andric //
10937a7e6055SDimitry Andric // After BB was duplicated into C, the layout looks like the one on the
10947a7e6055SDimitry Andric // right. BB and C now have the same successors. When considering
10957a7e6055SDimitry Andric // whether Succ can be duplicated into all its unplaced predecessors, we
10967a7e6055SDimitry Andric // ignore C.
10977a7e6055SDimitry Andric // We can do this because C already has a profitable fallthrough, namely
10987a7e6055SDimitry Andric // D. TODO(iteratee): ignore sufficiently cold predecessors for
10997a7e6055SDimitry Andric // duplication and for this test.
11007a7e6055SDimitry Andric //
11017a7e6055SDimitry Andric // This allows trellises to be laid out in 2 separate chains
11027a7e6055SDimitry Andric // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
11037a7e6055SDimitry Andric // because it allows the creation of 2 fallthrough paths with links
11047a7e6055SDimitry Andric // between them, and we correctly identify the best layout for these
11057a7e6055SDimitry Andric // CFGs. We want to extend trellises that the user created in addition
11067a7e6055SDimitry Andric // to trellises created by tail-duplication, so we just look for the
11077a7e6055SDimitry Andric // CFG.
11087a7e6055SDimitry Andric continue;
11097a7e6055SDimitry Andric return false;
11107a7e6055SDimitry Andric }
11117a7e6055SDimitry Andric }
11127a7e6055SDimitry Andric return true;
11137a7e6055SDimitry Andric }
11147a7e6055SDimitry Andric
11157a7e6055SDimitry Andric /// Find chains of triangles where we believe it would be profitable to
11167a7e6055SDimitry Andric /// tail-duplicate them all, but a local analysis would not find them.
11177a7e6055SDimitry Andric /// There are 3 ways this can be profitable:
11187a7e6055SDimitry Andric /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
11197a7e6055SDimitry Andric /// longer chains)
11207a7e6055SDimitry Andric /// 2) The chains are statically correlated. Branch probabilities have a very
11217a7e6055SDimitry Andric /// U-shaped distribution.
11227a7e6055SDimitry Andric /// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
11237a7e6055SDimitry Andric /// If the branches in a chain are likely to be from the same side of the
11247a7e6055SDimitry Andric /// distribution as their predecessor, but are independent at runtime, this
11257a7e6055SDimitry Andric /// transformation is profitable. (Because the cost of being wrong is a small
11267a7e6055SDimitry Andric /// fixed cost, unlike the standard triangle layout where the cost of being
11277a7e6055SDimitry Andric /// wrong scales with the # of triangles.)
11287a7e6055SDimitry Andric /// 3) The chains are dynamically correlated. If the probability that a previous
11297a7e6055SDimitry Andric /// branch was taken positively influences whether the next branch will be
11307a7e6055SDimitry Andric /// taken
11317a7e6055SDimitry Andric /// We believe that 2 and 3 are common enough to justify the small margin in 1.
precomputeTriangleChains()11327a7e6055SDimitry Andric void MachineBlockPlacement::precomputeTriangleChains() {
11337a7e6055SDimitry Andric struct TriangleChain {
11347a7e6055SDimitry Andric std::vector<MachineBasicBlock *> Edges;
11352cab237bSDimitry Andric
11367a7e6055SDimitry Andric TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
11377a7e6055SDimitry Andric : Edges({src, dst}) {}
11387a7e6055SDimitry Andric
11397a7e6055SDimitry Andric void append(MachineBasicBlock *dst) {
11407a7e6055SDimitry Andric assert(getKey()->isSuccessor(dst) &&
11417a7e6055SDimitry Andric "Attempting to append a block that is not a successor.");
11427a7e6055SDimitry Andric Edges.push_back(dst);
11437a7e6055SDimitry Andric }
11447a7e6055SDimitry Andric
11457a7e6055SDimitry Andric unsigned count() const { return Edges.size() - 1; }
11467a7e6055SDimitry Andric
11477a7e6055SDimitry Andric MachineBasicBlock *getKey() const {
11487a7e6055SDimitry Andric return Edges.back();
11497a7e6055SDimitry Andric }
11507a7e6055SDimitry Andric };
11517a7e6055SDimitry Andric
11527a7e6055SDimitry Andric if (TriangleChainCount == 0)
11537a7e6055SDimitry Andric return;
11547a7e6055SDimitry Andric
11554ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n");
11567a7e6055SDimitry Andric // Map from last block to the chain that contains it. This allows us to extend
11577a7e6055SDimitry Andric // chains as we find new triangles.
11587a7e6055SDimitry Andric DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
11597a7e6055SDimitry Andric for (MachineBasicBlock &BB : *F) {
11607a7e6055SDimitry Andric // If BB doesn't have 2 successors, it doesn't start a triangle.
11617a7e6055SDimitry Andric if (BB.succ_size() != 2)
11627a7e6055SDimitry Andric continue;
11637a7e6055SDimitry Andric MachineBasicBlock *PDom = nullptr;
11647a7e6055SDimitry Andric for (MachineBasicBlock *Succ : BB.successors()) {
11657a7e6055SDimitry Andric if (!MPDT->dominates(Succ, &BB))
11667a7e6055SDimitry Andric continue;
11677a7e6055SDimitry Andric PDom = Succ;
11687a7e6055SDimitry Andric break;
11697a7e6055SDimitry Andric }
11707a7e6055SDimitry Andric // If BB doesn't have a post-dominating successor, it doesn't form a
11717a7e6055SDimitry Andric // triangle.
11727a7e6055SDimitry Andric if (PDom == nullptr)
11737a7e6055SDimitry Andric continue;
11747a7e6055SDimitry Andric // If PDom has a hint that it is low probability, skip this triangle.
11757a7e6055SDimitry Andric if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
11767a7e6055SDimitry Andric continue;
11777a7e6055SDimitry Andric // If PDom isn't eligible for duplication, this isn't the kind of triangle
11787a7e6055SDimitry Andric // we're looking for.
11797a7e6055SDimitry Andric if (!shouldTailDuplicate(PDom))
11807a7e6055SDimitry Andric continue;
11817a7e6055SDimitry Andric bool CanTailDuplicate = true;
11827a7e6055SDimitry Andric // If PDom can't tail-duplicate into it's non-BB predecessors, then this
11837a7e6055SDimitry Andric // isn't the kind of triangle we're looking for.
11847a7e6055SDimitry Andric for (MachineBasicBlock* Pred : PDom->predecessors()) {
11857a7e6055SDimitry Andric if (Pred == &BB)
11867a7e6055SDimitry Andric continue;
11877a7e6055SDimitry Andric if (!TailDup.canTailDuplicate(PDom, Pred)) {
11887a7e6055SDimitry Andric CanTailDuplicate = false;
11897a7e6055SDimitry Andric break;
11907a7e6055SDimitry Andric }
11917a7e6055SDimitry Andric }
11927a7e6055SDimitry Andric // If we can't tail-duplicate PDom to its predecessors, then skip this
11937a7e6055SDimitry Andric // triangle.
11947a7e6055SDimitry Andric if (!CanTailDuplicate)
11957a7e6055SDimitry Andric continue;
11967a7e6055SDimitry Andric
11977a7e6055SDimitry Andric // Now we have an interesting triangle. Insert it if it's not part of an
119824d58133SDimitry Andric // existing chain.
11997a7e6055SDimitry Andric // Note: This cannot be replaced with a call insert() or emplace() because
12007a7e6055SDimitry Andric // the find key is BB, but the insert/emplace key is PDom.
12017a7e6055SDimitry Andric auto Found = TriangleChainMap.find(&BB);
12027a7e6055SDimitry Andric // If it is, remove the chain from the map, grow it, and put it back in the
12037a7e6055SDimitry Andric // map with the end as the new key.
12047a7e6055SDimitry Andric if (Found != TriangleChainMap.end()) {
12057a7e6055SDimitry Andric TriangleChain Chain = std::move(Found->second);
12067a7e6055SDimitry Andric TriangleChainMap.erase(Found);
12077a7e6055SDimitry Andric Chain.append(PDom);
12087a7e6055SDimitry Andric TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
12097a7e6055SDimitry Andric } else {
12107a7e6055SDimitry Andric auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
12117a7e6055SDimitry Andric assert(InsertResult.second && "Block seen twice.");
12127a7e6055SDimitry Andric (void)InsertResult;
12137a7e6055SDimitry Andric }
12147a7e6055SDimitry Andric }
12157a7e6055SDimitry Andric
12167a7e6055SDimitry Andric // Iterating over a DenseMap is safe here, because the only thing in the body
12177a7e6055SDimitry Andric // of the loop is inserting into another DenseMap (ComputedEdges).
12187a7e6055SDimitry Andric // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
12197a7e6055SDimitry Andric for (auto &ChainPair : TriangleChainMap) {
12207a7e6055SDimitry Andric TriangleChain &Chain = ChainPair.second;
12217a7e6055SDimitry Andric // Benchmarking has shown that due to branch correlation duplicating 2 or
12227a7e6055SDimitry Andric // more triangles is profitable, despite the calculations assuming
12237a7e6055SDimitry Andric // independence.
12247a7e6055SDimitry Andric if (Chain.count() < TriangleChainCount)
12257a7e6055SDimitry Andric continue;
12267a7e6055SDimitry Andric MachineBasicBlock *dst = Chain.Edges.back();
12277a7e6055SDimitry Andric Chain.Edges.pop_back();
12287a7e6055SDimitry Andric for (MachineBasicBlock *src : reverse(Chain.Edges)) {
12294ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->"
12304ba319b5SDimitry Andric << getBlockName(dst)
12314ba319b5SDimitry Andric << " as pre-computed based on triangles.\n");
12327a7e6055SDimitry Andric
12337a7e6055SDimitry Andric auto InsertResult = ComputedEdges.insert({src, {dst, true}});
12347a7e6055SDimitry Andric assert(InsertResult.second && "Block seen twice.");
12357a7e6055SDimitry Andric (void)InsertResult;
12367a7e6055SDimitry Andric
12377a7e6055SDimitry Andric dst = src;
12387a7e6055SDimitry Andric }
12397a7e6055SDimitry Andric }
12403ca95b02SDimitry Andric }
12413ca95b02SDimitry Andric
12423ca95b02SDimitry Andric // When profile is not present, return the StaticLikelyProb.
12433ca95b02SDimitry Andric // When profile is available, we need to handle the triangle-shape CFG.
getLayoutSuccessorProbThreshold(const MachineBasicBlock * BB)12443ca95b02SDimitry Andric static BranchProbability getLayoutSuccessorProbThreshold(
12457a7e6055SDimitry Andric const MachineBasicBlock *BB) {
1246da09e106SDimitry Andric if (!BB->getParent()->getFunction().hasProfileData())
12473ca95b02SDimitry Andric return BranchProbability(StaticLikelyProb, 100);
12483ca95b02SDimitry Andric if (BB->succ_size() == 2) {
12493ca95b02SDimitry Andric const MachineBasicBlock *Succ1 = *BB->succ_begin();
12503ca95b02SDimitry Andric const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
12513ca95b02SDimitry Andric if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
12523ca95b02SDimitry Andric /* See case 1 below for the cost analysis. For BB->Succ to
12533ca95b02SDimitry Andric * be taken with smaller cost, the following needs to hold:
12543ca95b02SDimitry Andric * Prob(BB->Succ) > 2 * Prob(BB->Pred)
12557a7e6055SDimitry Andric * So the threshold T in the calculation below
12567a7e6055SDimitry Andric * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
12577a7e6055SDimitry Andric * So T / (1 - T) = 2, Yielding T = 2/3
12587a7e6055SDimitry Andric * Also adding user specified branch bias, we have
12593ca95b02SDimitry Andric * T = (2/3)*(ProfileLikelyProb/50)
12603ca95b02SDimitry Andric * = (2*ProfileLikelyProb)/150)
12613ca95b02SDimitry Andric */
12623ca95b02SDimitry Andric return BranchProbability(2 * ProfileLikelyProb, 150);
12633ca95b02SDimitry Andric }
12643ca95b02SDimitry Andric }
12653ca95b02SDimitry Andric return BranchProbability(ProfileLikelyProb, 100);
12663ca95b02SDimitry Andric }
12673ca95b02SDimitry Andric
12683ca95b02SDimitry Andric /// Checks to see if the layout candidate block \p Succ has a better layout
12693ca95b02SDimitry Andric /// predecessor than \c BB. If yes, returns true.
12707a7e6055SDimitry Andric /// \p SuccProb: The probability adjusted for only remaining blocks.
12717a7e6055SDimitry Andric /// Only used for logging
12727a7e6055SDimitry Andric /// \p RealSuccProb: The un-adjusted probability.
12737a7e6055SDimitry Andric /// \p Chain: The chain that BB belongs to and Succ is being considered for.
12747a7e6055SDimitry Andric /// \p BlockFilter: if non-null, the set of blocks that make up the loop being
12757a7e6055SDimitry Andric /// considered
hasBetterLayoutPredecessor(const MachineBasicBlock * BB,const MachineBasicBlock * Succ,const BlockChain & SuccChain,BranchProbability SuccProb,BranchProbability RealSuccProb,const BlockChain & Chain,const BlockFilterSet * BlockFilter)12763ca95b02SDimitry Andric bool MachineBlockPlacement::hasBetterLayoutPredecessor(
12777a7e6055SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
12787a7e6055SDimitry Andric const BlockChain &SuccChain, BranchProbability SuccProb,
12797a7e6055SDimitry Andric BranchProbability RealSuccProb, const BlockChain &Chain,
12807a7e6055SDimitry Andric const BlockFilterSet *BlockFilter) {
12813ca95b02SDimitry Andric
12823ca95b02SDimitry Andric // There isn't a better layout when there are no unscheduled predecessors.
12833ca95b02SDimitry Andric if (SuccChain.UnscheduledPredecessors == 0)
12843ca95b02SDimitry Andric return false;
12853ca95b02SDimitry Andric
12863ca95b02SDimitry Andric // There are two basic scenarios here:
12873ca95b02SDimitry Andric // -------------------------------------
12883ca95b02SDimitry Andric // Case 1: triangular shape CFG (if-then):
12893ca95b02SDimitry Andric // BB
12903ca95b02SDimitry Andric // | \
12913ca95b02SDimitry Andric // | \
12923ca95b02SDimitry Andric // | Pred
12933ca95b02SDimitry Andric // | /
12943ca95b02SDimitry Andric // Succ
12953ca95b02SDimitry Andric // In this case, we are evaluating whether to select edge -> Succ, e.g.
12963ca95b02SDimitry Andric // set Succ as the layout successor of BB. Picking Succ as BB's
12973ca95b02SDimitry Andric // successor breaks the CFG constraints (FIXME: define these constraints).
12983ca95b02SDimitry Andric // With this layout, Pred BB
12993ca95b02SDimitry Andric // is forced to be outlined, so the overall cost will be cost of the
13003ca95b02SDimitry Andric // branch taken from BB to Pred, plus the cost of back taken branch
13013ca95b02SDimitry Andric // from Pred to Succ, as well as the additional cost associated
13023ca95b02SDimitry Andric // with the needed unconditional jump instruction from Pred To Succ.
13033ca95b02SDimitry Andric
13043ca95b02SDimitry Andric // The cost of the topological order layout is the taken branch cost
13053ca95b02SDimitry Andric // from BB to Succ, so to make BB->Succ a viable candidate, the following
13063ca95b02SDimitry Andric // must hold:
13073ca95b02SDimitry Andric // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
13083ca95b02SDimitry Andric // < freq(BB->Succ) * taken_branch_cost.
13093ca95b02SDimitry Andric // Ignoring unconditional jump cost, we get
13103ca95b02SDimitry Andric // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
13113ca95b02SDimitry Andric // prob(BB->Succ) > 2 * prob(BB->Pred)
13123ca95b02SDimitry Andric //
13133ca95b02SDimitry Andric // When real profile data is available, we can precisely compute the
13143ca95b02SDimitry Andric // probability threshold that is needed for edge BB->Succ to be considered.
13153ca95b02SDimitry Andric // Without profile data, the heuristic requires the branch bias to be
13163ca95b02SDimitry Andric // a lot larger to make sure the signal is very strong (e.g. 80% default).
13173ca95b02SDimitry Andric // -----------------------------------------------------------------
13183ca95b02SDimitry Andric // Case 2: diamond like CFG (if-then-else):
13193ca95b02SDimitry Andric // S
13203ca95b02SDimitry Andric // / \
13213ca95b02SDimitry Andric // | \
13223ca95b02SDimitry Andric // BB Pred
13233ca95b02SDimitry Andric // \ /
13243ca95b02SDimitry Andric // Succ
13253ca95b02SDimitry Andric // ..
13263ca95b02SDimitry Andric //
13273ca95b02SDimitry Andric // The current block is BB and edge BB->Succ is now being evaluated.
13283ca95b02SDimitry Andric // Note that edge S->BB was previously already selected because
13293ca95b02SDimitry Andric // prob(S->BB) > prob(S->Pred).
13303ca95b02SDimitry Andric // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
13313ca95b02SDimitry Andric // choose Pred, we will have a topological ordering as shown on the left
13323ca95b02SDimitry Andric // in the picture below. If we choose Succ, we have the solution as shown
13333ca95b02SDimitry Andric // on the right:
13343ca95b02SDimitry Andric //
13353ca95b02SDimitry Andric // topo-order:
13363ca95b02SDimitry Andric //
13373ca95b02SDimitry Andric // S----- ---S
13383ca95b02SDimitry Andric // | | | |
13393ca95b02SDimitry Andric // ---BB | | BB
13403ca95b02SDimitry Andric // | | | |
134124d58133SDimitry Andric // | Pred-- | Succ--
13423ca95b02SDimitry Andric // | | | |
134324d58133SDimitry Andric // ---Succ ---Pred--
13443ca95b02SDimitry Andric //
13453ca95b02SDimitry Andric // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
13463ca95b02SDimitry Andric // = freq(S->Pred) + freq(S->BB)
13473ca95b02SDimitry Andric //
13483ca95b02SDimitry Andric // If we have profile data (i.e, branch probabilities can be trusted), the
13493ca95b02SDimitry Andric // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
13503ca95b02SDimitry Andric // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
13513ca95b02SDimitry Andric // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
13523ca95b02SDimitry Andric // means the cost of topological order is greater.
13533ca95b02SDimitry Andric // When profile data is not available, however, we need to be more
13543ca95b02SDimitry Andric // conservative. If the branch prediction is wrong, breaking the topo-order
13553ca95b02SDimitry Andric // will actually yield a layout with large cost. For this reason, we need
13563ca95b02SDimitry Andric // strong biased branch at block S with Prob(S->BB) in order to select
13573ca95b02SDimitry Andric // BB->Succ. This is equivalent to looking the CFG backward with backward
13583ca95b02SDimitry Andric // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
13593ca95b02SDimitry Andric // profile data).
1360d88c1a5aSDimitry Andric // --------------------------------------------------------------------------
1361d88c1a5aSDimitry Andric // Case 3: forked diamond
1362d88c1a5aSDimitry Andric // S
1363d88c1a5aSDimitry Andric // / \
1364d88c1a5aSDimitry Andric // / \
1365d88c1a5aSDimitry Andric // BB Pred
1366d88c1a5aSDimitry Andric // | \ / |
1367d88c1a5aSDimitry Andric // | \ / |
1368d88c1a5aSDimitry Andric // | X |
1369d88c1a5aSDimitry Andric // | / \ |
1370d88c1a5aSDimitry Andric // | / \ |
1371d88c1a5aSDimitry Andric // S1 S2
1372d88c1a5aSDimitry Andric //
1373d88c1a5aSDimitry Andric // The current block is BB and edge BB->S1 is now being evaluated.
1374d88c1a5aSDimitry Andric // As above S->BB was already selected because
1375d88c1a5aSDimitry Andric // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1376d88c1a5aSDimitry Andric //
1377d88c1a5aSDimitry Andric // topo-order:
1378d88c1a5aSDimitry Andric //
1379d88c1a5aSDimitry Andric // S-------| ---S
1380d88c1a5aSDimitry Andric // | | | |
1381d88c1a5aSDimitry Andric // ---BB | | BB
1382d88c1a5aSDimitry Andric // | | | |
1383d88c1a5aSDimitry Andric // | Pred----| | S1----
1384d88c1a5aSDimitry Andric // | | | |
1385d88c1a5aSDimitry Andric // --(S1 or S2) ---Pred--
13867a7e6055SDimitry Andric // |
13877a7e6055SDimitry Andric // S2
1388d88c1a5aSDimitry Andric //
1389d88c1a5aSDimitry Andric // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1390d88c1a5aSDimitry Andric // + min(freq(Pred->S1), freq(Pred->S2))
1391d88c1a5aSDimitry Andric // Non-topo-order cost:
1392d88c1a5aSDimitry Andric // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1393d88c1a5aSDimitry Andric // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1394d88c1a5aSDimitry Andric // is 0. Then the non topo layout is better when
1395d88c1a5aSDimitry Andric // freq(S->Pred) < freq(BB->S1).
1396d88c1a5aSDimitry Andric // This is exactly what is checked below.
1397d88c1a5aSDimitry Andric // Note there are other shapes that apply (Pred may not be a single block,
1398d88c1a5aSDimitry Andric // but they all fit this general pattern.)
13993ca95b02SDimitry Andric BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
14003ca95b02SDimitry Andric
14013ca95b02SDimitry Andric // Make sure that a hot successor doesn't have a globally more
14023ca95b02SDimitry Andric // important predecessor.
14033ca95b02SDimitry Andric BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
14043ca95b02SDimitry Andric bool BadCFGConflict = false;
14053ca95b02SDimitry Andric
14063ca95b02SDimitry Andric for (MachineBasicBlock *Pred : Succ->predecessors()) {
14073ca95b02SDimitry Andric if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
14083ca95b02SDimitry Andric (BlockFilter && !BlockFilter->count(Pred)) ||
14097a7e6055SDimitry Andric BlockToChain[Pred] == &Chain ||
14107a7e6055SDimitry Andric // This check is redundant except for look ahead. This function is
14117a7e6055SDimitry Andric // called for lookahead by isProfitableToTailDup when BB hasn't been
14127a7e6055SDimitry Andric // placed yet.
14137a7e6055SDimitry Andric (Pred == BB))
14143ca95b02SDimitry Andric continue;
1415d88c1a5aSDimitry Andric // Do backward checking.
1416d88c1a5aSDimitry Andric // For all cases above, we need a backward checking to filter out edges that
14177a7e6055SDimitry Andric // are not 'strongly' biased.
14183ca95b02SDimitry Andric // BB Pred
14193ca95b02SDimitry Andric // \ /
14203ca95b02SDimitry Andric // Succ
14213ca95b02SDimitry Andric // We select edge BB->Succ if
14223ca95b02SDimitry Andric // freq(BB->Succ) > freq(Succ) * HotProb
14233ca95b02SDimitry Andric // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
14243ca95b02SDimitry Andric // HotProb
14253ca95b02SDimitry Andric // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
1426d88c1a5aSDimitry Andric // Case 1 is covered too, because the first equation reduces to:
1427d88c1a5aSDimitry Andric // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
14283ca95b02SDimitry Andric BlockFrequency PredEdgeFreq =
14293ca95b02SDimitry Andric MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
14303ca95b02SDimitry Andric if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
14313ca95b02SDimitry Andric BadCFGConflict = true;
14323ca95b02SDimitry Andric break;
14333ca95b02SDimitry Andric }
14343ca95b02SDimitry Andric }
14353ca95b02SDimitry Andric
14363ca95b02SDimitry Andric if (BadCFGConflict) {
14374ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> "
14384ba319b5SDimitry Andric << SuccProb << " (prob) (non-cold CFG conflict)\n");
14393ca95b02SDimitry Andric return true;
14403ca95b02SDimitry Andric }
14413ca95b02SDimitry Andric
14423ca95b02SDimitry Andric return false;
14433ca95b02SDimitry Andric }
14443ca95b02SDimitry Andric
14454ba319b5SDimitry Andric /// Select the best successor for a block.
1446dff0c46cSDimitry Andric ///
1447dff0c46cSDimitry Andric /// This looks across all successors of a particular block and attempts to
1448dff0c46cSDimitry Andric /// select the "best" one to be the layout successor. It only considers direct
1449dff0c46cSDimitry Andric /// successors which also pass the block filter. It will attempt to avoid
1450dff0c46cSDimitry Andric /// breaking CFG structure, but cave and break such structures in the case of
1451dff0c46cSDimitry Andric /// very hot successor edges.
1452dff0c46cSDimitry Andric ///
14537a7e6055SDimitry Andric /// \returns The best successor block found, or null if none are viable, along
14547a7e6055SDimitry Andric /// with a boolean indicating if tail duplication is necessary.
14557a7e6055SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult
selectBestSuccessor(const MachineBasicBlock * BB,const BlockChain & Chain,const BlockFilterSet * BlockFilter)14567a7e6055SDimitry Andric MachineBlockPlacement::selectBestSuccessor(
14577a7e6055SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain,
1458dff0c46cSDimitry Andric const BlockFilterSet *BlockFilter) {
14593ca95b02SDimitry Andric const BranchProbability HotProb(StaticLikelyProb, 100);
1460dff0c46cSDimitry Andric
14617a7e6055SDimitry Andric BlockAndTailDupResult BestSucc = { nullptr, false };
14627d523365SDimitry Andric auto BestProb = BranchProbability::getZero();
14637d523365SDimitry Andric
14647d523365SDimitry Andric SmallVector<MachineBasicBlock *, 4> Successors;
14653ca95b02SDimitry Andric auto AdjustedSumProb =
14663ca95b02SDimitry Andric collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1467dff0c46cSDimitry Andric
14684ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB)
14694ba319b5SDimitry Andric << "\n");
14707a7e6055SDimitry Andric
14717a7e6055SDimitry Andric // if we already precomputed the best successor for BB, return that if still
14727a7e6055SDimitry Andric // applicable.
14737a7e6055SDimitry Andric auto FoundEdge = ComputedEdges.find(BB);
14747a7e6055SDimitry Andric if (FoundEdge != ComputedEdges.end()) {
14757a7e6055SDimitry Andric MachineBasicBlock *Succ = FoundEdge->second.BB;
14767a7e6055SDimitry Andric ComputedEdges.erase(FoundEdge);
14777a7e6055SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ];
14787a7e6055SDimitry Andric if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
14797a7e6055SDimitry Andric SuccChain != &Chain && Succ == *SuccChain->begin())
14807a7e6055SDimitry Andric return FoundEdge->second;
14817a7e6055SDimitry Andric }
14827a7e6055SDimitry Andric
14837a7e6055SDimitry Andric // if BB is part of a trellis, Use the trellis to determine the optimal
14847a7e6055SDimitry Andric // fallthrough edges
14857a7e6055SDimitry Andric if (isTrellis(BB, Successors, Chain, BlockFilter))
14867a7e6055SDimitry Andric return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
14877a7e6055SDimitry Andric BlockFilter);
14887a7e6055SDimitry Andric
14897a7e6055SDimitry Andric // For blocks with CFG violations, we may be able to lay them out anyway with
14907a7e6055SDimitry Andric // tail-duplication. We keep this vector so we can perform the probability
14917a7e6055SDimitry Andric // calculations the minimum number of times.
14927a7e6055SDimitry Andric SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
14937a7e6055SDimitry Andric DupCandidates;
14947d523365SDimitry Andric for (MachineBasicBlock *Succ : Successors) {
14957d523365SDimitry Andric auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
14963ca95b02SDimitry Andric BranchProbability SuccProb =
14973ca95b02SDimitry Andric getAdjustedProbability(RealSuccProb, AdjustedSumProb);
1498dff0c46cSDimitry Andric
14993ca95b02SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ];
15003ca95b02SDimitry Andric // Skip the edge \c BB->Succ if block \c Succ has a better layout
15013ca95b02SDimitry Andric // predecessor that yields lower global cost.
15023ca95b02SDimitry Andric if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
15037a7e6055SDimitry Andric Chain, BlockFilter)) {
15047a7e6055SDimitry Andric // If tail duplication would make Succ profitable, place it.
15056ccc06f6SDimitry Andric if (allowTailDupPlacement() && shouldTailDuplicate(Succ))
15067a7e6055SDimitry Andric DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
15073ca95b02SDimitry Andric continue;
15087a7e6055SDimitry Andric }
15093ca95b02SDimitry Andric
15104ba319b5SDimitry Andric LLVM_DEBUG(
15114ba319b5SDimitry Andric dbgs() << " Candidate: " << getBlockName(Succ)
15124ba319b5SDimitry Andric << ", probability: " << SuccProb
15133ca95b02SDimitry Andric << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1514dff0c46cSDimitry Andric << "\n");
1515d88c1a5aSDimitry Andric
15167a7e6055SDimitry Andric if (BestSucc.BB && BestProb >= SuccProb) {
15174ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n");
1518dff0c46cSDimitry Andric continue;
1519d88c1a5aSDimitry Andric }
1520d88c1a5aSDimitry Andric
15214ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Setting it as best candidate\n");
15227a7e6055SDimitry Andric BestSucc.BB = Succ;
15237d523365SDimitry Andric BestProb = SuccProb;
1524dff0c46cSDimitry Andric }
15257a7e6055SDimitry Andric // Handle the tail duplication candidates in order of decreasing probability.
15267a7e6055SDimitry Andric // Stop at the first one that is profitable. Also stop if they are less
15277a7e6055SDimitry Andric // profitable than BestSucc. Position is important because we preserve it and
15287a7e6055SDimitry Andric // prefer first best match. Here we aren't comparing in order, so we capture
15297a7e6055SDimitry Andric // the position instead.
15307a7e6055SDimitry Andric if (DupCandidates.size() != 0) {
15317a7e6055SDimitry Andric auto cmp =
15327a7e6055SDimitry Andric [](const std::tuple<BranchProbability, MachineBasicBlock *> &a,
15337a7e6055SDimitry Andric const std::tuple<BranchProbability, MachineBasicBlock *> &b) {
15347a7e6055SDimitry Andric return std::get<0>(a) > std::get<0>(b);
15357a7e6055SDimitry Andric };
15367a7e6055SDimitry Andric std::stable_sort(DupCandidates.begin(), DupCandidates.end(), cmp);
15377a7e6055SDimitry Andric }
15387a7e6055SDimitry Andric for(auto &Tup : DupCandidates) {
15397a7e6055SDimitry Andric BranchProbability DupProb;
15407a7e6055SDimitry Andric MachineBasicBlock *Succ;
15417a7e6055SDimitry Andric std::tie(DupProb, Succ) = Tup;
15427a7e6055SDimitry Andric if (DupProb < BestProb)
15437a7e6055SDimitry Andric break;
15447a7e6055SDimitry Andric if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
15457a7e6055SDimitry Andric && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
15464ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ)
15474ba319b5SDimitry Andric << ", probability: " << DupProb
15487a7e6055SDimitry Andric << " (Tail Duplicate)\n");
15497a7e6055SDimitry Andric BestSucc.BB = Succ;
15507a7e6055SDimitry Andric BestSucc.ShouldTailDup = true;
15517a7e6055SDimitry Andric break;
15527a7e6055SDimitry Andric }
15537a7e6055SDimitry Andric }
15547a7e6055SDimitry Andric
15557a7e6055SDimitry Andric if (BestSucc.BB)
15564ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
1557d88c1a5aSDimitry Andric
1558dff0c46cSDimitry Andric return BestSucc;
1559dff0c46cSDimitry Andric }
1560dff0c46cSDimitry Andric
15614ba319b5SDimitry Andric /// Select the best block from a worklist.
1562dff0c46cSDimitry Andric ///
1563dff0c46cSDimitry Andric /// This looks through the provided worklist as a list of candidate basic
1564dff0c46cSDimitry Andric /// blocks and select the most profitable one to place. The definition of
1565dff0c46cSDimitry Andric /// profitable only really makes sense in the context of a loop. This returns
1566dff0c46cSDimitry Andric /// the most frequently visited block in the worklist, which in the case of
1567dff0c46cSDimitry Andric /// a loop, is the one most desirable to be physically close to the rest of the
15683ca95b02SDimitry Andric /// loop body in order to improve i-cache behavior.
1569dff0c46cSDimitry Andric ///
1570dff0c46cSDimitry Andric /// \returns The best block found, or null if none are viable.
selectBestCandidateBlock(const BlockChain & Chain,SmallVectorImpl<MachineBasicBlock * > & WorkList)1571dff0c46cSDimitry Andric MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
15727a7e6055SDimitry Andric const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
1573dff0c46cSDimitry Andric // Once we need to walk the worklist looking for a candidate, cleanup the
1574dff0c46cSDimitry Andric // worklist of already placed entries.
1575dff0c46cSDimitry Andric // FIXME: If this shows up on profiles, it could be folded (at the cost of
1576dff0c46cSDimitry Andric // some code complexity) into the loop below.
15772cab237bSDimitry Andric WorkList.erase(llvm::remove_if(WorkList,
157891bc56edSDimitry Andric [&](MachineBasicBlock *BB) {
157991bc56edSDimitry Andric return BlockToChain.lookup(BB) == &Chain;
158091bc56edSDimitry Andric }),
1581dff0c46cSDimitry Andric WorkList.end());
1582dff0c46cSDimitry Andric
15833ca95b02SDimitry Andric if (WorkList.empty())
15843ca95b02SDimitry Andric return nullptr;
15853ca95b02SDimitry Andric
15863ca95b02SDimitry Andric bool IsEHPad = WorkList[0]->isEHPad();
15873ca95b02SDimitry Andric
158891bc56edSDimitry Andric MachineBasicBlock *BestBlock = nullptr;
1589dff0c46cSDimitry Andric BlockFrequency BestFreq;
1590ff0cc061SDimitry Andric for (MachineBasicBlock *MBB : WorkList) {
1591d8866befSDimitry Andric assert(MBB->isEHPad() == IsEHPad &&
1592d8866befSDimitry Andric "EHPad mismatch between block and work list.");
15933ca95b02SDimitry Andric
1594ff0cc061SDimitry Andric BlockChain &SuccChain = *BlockToChain[MBB];
15953ca95b02SDimitry Andric if (&SuccChain == &Chain)
1596dff0c46cSDimitry Andric continue;
15973ca95b02SDimitry Andric
1598d8866befSDimitry Andric assert(SuccChain.UnscheduledPredecessors == 0 &&
1599d8866befSDimitry Andric "Found CFG-violating block");
1600dff0c46cSDimitry Andric
1601ff0cc061SDimitry Andric BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
16024ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
160391bc56edSDimitry Andric MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
16043ca95b02SDimitry Andric
16053ca95b02SDimitry Andric // For ehpad, we layout the least probable first as to avoid jumping back
16063ca95b02SDimitry Andric // from least probable landingpads to more probable ones.
16073ca95b02SDimitry Andric //
16083ca95b02SDimitry Andric // FIXME: Using probability is probably (!) not the best way to achieve
16093ca95b02SDimitry Andric // this. We should probably have a more principled approach to layout
16103ca95b02SDimitry Andric // cleanup code.
16113ca95b02SDimitry Andric //
16123ca95b02SDimitry Andric // The goal is to get:
16133ca95b02SDimitry Andric //
16143ca95b02SDimitry Andric // +--------------------------+
16153ca95b02SDimitry Andric // | V
16163ca95b02SDimitry Andric // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
16173ca95b02SDimitry Andric //
16183ca95b02SDimitry Andric // Rather than:
16193ca95b02SDimitry Andric //
16203ca95b02SDimitry Andric // +-------------------------------------+
16213ca95b02SDimitry Andric // V |
16223ca95b02SDimitry Andric // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
16233ca95b02SDimitry Andric if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
1624dff0c46cSDimitry Andric continue;
16253ca95b02SDimitry Andric
1626ff0cc061SDimitry Andric BestBlock = MBB;
1627dff0c46cSDimitry Andric BestFreq = CandidateFreq;
1628dff0c46cSDimitry Andric }
16293ca95b02SDimitry Andric
1630dff0c46cSDimitry Andric return BestBlock;
1631dff0c46cSDimitry Andric }
1632dff0c46cSDimitry Andric
16334ba319b5SDimitry Andric /// Retrieve the first unplaced basic block.
1634dff0c46cSDimitry Andric ///
1635dff0c46cSDimitry Andric /// This routine is called when we are unable to use the CFG to walk through
1636dff0c46cSDimitry Andric /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
1637dff0c46cSDimitry Andric /// We walk through the function's blocks in order, starting from the
1638dff0c46cSDimitry Andric /// LastUnplacedBlockIt. We update this iterator on each call to avoid
1639dff0c46cSDimitry Andric /// re-scanning the entire sequence on repeated calls to this routine.
getFirstUnplacedBlock(const BlockChain & PlacedChain,MachineFunction::iterator & PrevUnplacedBlockIt,const BlockFilterSet * BlockFilter)1640dff0c46cSDimitry Andric MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
16413ca95b02SDimitry Andric const BlockChain &PlacedChain,
1642dff0c46cSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt,
1643dff0c46cSDimitry Andric const BlockFilterSet *BlockFilter) {
16443ca95b02SDimitry Andric for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
1645dff0c46cSDimitry Andric ++I) {
16467d523365SDimitry Andric if (BlockFilter && !BlockFilter->count(&*I))
1647dff0c46cSDimitry Andric continue;
16487d523365SDimitry Andric if (BlockToChain[&*I] != &PlacedChain) {
1649dff0c46cSDimitry Andric PrevUnplacedBlockIt = I;
1650dff0c46cSDimitry Andric // Now select the head of the chain to which the unplaced block belongs
1651dff0c46cSDimitry Andric // as the block to place. This will force the entire chain to be placed,
1652dff0c46cSDimitry Andric // and satisfies the requirements of merging chains.
16537d523365SDimitry Andric return *BlockToChain[&*I]->begin();
1654dff0c46cSDimitry Andric }
1655dff0c46cSDimitry Andric }
165691bc56edSDimitry Andric return nullptr;
1657dff0c46cSDimitry Andric }
1658dff0c46cSDimitry Andric
fillWorkLists(const MachineBasicBlock * MBB,SmallPtrSetImpl<BlockChain * > & UpdatedPreds,const BlockFilterSet * BlockFilter=nullptr)16593ca95b02SDimitry Andric void MachineBlockPlacement::fillWorkLists(
16607a7e6055SDimitry Andric const MachineBasicBlock *MBB,
16613ca95b02SDimitry Andric SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
16623ca95b02SDimitry Andric const BlockFilterSet *BlockFilter = nullptr) {
16633ca95b02SDimitry Andric BlockChain &Chain = *BlockToChain[MBB];
16643ca95b02SDimitry Andric if (!UpdatedPreds.insert(&Chain).second)
16653ca95b02SDimitry Andric return;
16663ca95b02SDimitry Andric
1667d8866befSDimitry Andric assert(
1668d8866befSDimitry Andric Chain.UnscheduledPredecessors == 0 &&
1669d8866befSDimitry Andric "Attempting to place block with unscheduled predecessors in worklist.");
16703ca95b02SDimitry Andric for (MachineBasicBlock *ChainBB : Chain) {
1671d8866befSDimitry Andric assert(BlockToChain[ChainBB] == &Chain &&
1672d8866befSDimitry Andric "Block in chain doesn't match BlockToChain map.");
16733ca95b02SDimitry Andric for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
16743ca95b02SDimitry Andric if (BlockFilter && !BlockFilter->count(Pred))
16753ca95b02SDimitry Andric continue;
16763ca95b02SDimitry Andric if (BlockToChain[Pred] == &Chain)
16773ca95b02SDimitry Andric continue;
16783ca95b02SDimitry Andric ++Chain.UnscheduledPredecessors;
16793ca95b02SDimitry Andric }
16803ca95b02SDimitry Andric }
16813ca95b02SDimitry Andric
16823ca95b02SDimitry Andric if (Chain.UnscheduledPredecessors != 0)
16833ca95b02SDimitry Andric return;
16843ca95b02SDimitry Andric
16857a7e6055SDimitry Andric MachineBasicBlock *BB = *Chain.begin();
16867a7e6055SDimitry Andric if (BB->isEHPad())
16877a7e6055SDimitry Andric EHPadWorkList.push_back(BB);
16883ca95b02SDimitry Andric else
16897a7e6055SDimitry Andric BlockWorkList.push_back(BB);
16903ca95b02SDimitry Andric }
16913ca95b02SDimitry Andric
buildChain(const MachineBasicBlock * HeadBB,BlockChain & Chain,BlockFilterSet * BlockFilter)1692dff0c46cSDimitry Andric void MachineBlockPlacement::buildChain(
16937a7e6055SDimitry Andric const MachineBasicBlock *HeadBB, BlockChain &Chain,
1694d88c1a5aSDimitry Andric BlockFilterSet *BlockFilter) {
16957a7e6055SDimitry Andric assert(HeadBB && "BB must not be null.\n");
16967a7e6055SDimitry Andric assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
16973ca95b02SDimitry Andric MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
1698dff0c46cSDimitry Andric
16997a7e6055SDimitry Andric const MachineBasicBlock *LoopHeaderBB = HeadBB;
17003ca95b02SDimitry Andric markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
17017a7e6055SDimitry Andric MachineBasicBlock *BB = *std::prev(Chain.end());
17022cab237bSDimitry Andric while (true) {
17033ca95b02SDimitry Andric assert(BB && "null block found at end of chain in loop.");
17043ca95b02SDimitry Andric assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
17053ca95b02SDimitry Andric assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
17063ca95b02SDimitry Andric
1707dff0c46cSDimitry Andric
1708dff0c46cSDimitry Andric // Look for the best viable successor if there is one to place immediately
1709dff0c46cSDimitry Andric // after this block.
17107a7e6055SDimitry Andric auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
17117a7e6055SDimitry Andric MachineBasicBlock* BestSucc = Result.BB;
17127a7e6055SDimitry Andric bool ShouldTailDup = Result.ShouldTailDup;
17136ccc06f6SDimitry Andric if (allowTailDupPlacement())
17147a7e6055SDimitry Andric ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
1715dff0c46cSDimitry Andric
1716dff0c46cSDimitry Andric // If an immediate successor isn't available, look for the best viable
1717dff0c46cSDimitry Andric // block among those we've identified as not violating the loop's CFG at
1718dff0c46cSDimitry Andric // this point. This won't be a fallthrough, but it will increase locality.
1719dff0c46cSDimitry Andric if (!BestSucc)
17203ca95b02SDimitry Andric BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
17213ca95b02SDimitry Andric if (!BestSucc)
17223ca95b02SDimitry Andric BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
1723dff0c46cSDimitry Andric
1724dff0c46cSDimitry Andric if (!BestSucc) {
17253ca95b02SDimitry Andric BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
1726dff0c46cSDimitry Andric if (!BestSucc)
1727dff0c46cSDimitry Andric break;
1728dff0c46cSDimitry Andric
17294ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1730dff0c46cSDimitry Andric "layout successor until the CFG reduces\n");
1731dff0c46cSDimitry Andric }
1732dff0c46cSDimitry Andric
1733d88c1a5aSDimitry Andric // Placement may have changed tail duplication opportunities.
1734d88c1a5aSDimitry Andric // Check for that now.
17356ccc06f6SDimitry Andric if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
1736d88c1a5aSDimitry Andric // If the chosen successor was duplicated into all its predecessors,
1737d88c1a5aSDimitry Andric // don't bother laying it out, just go round the loop again with BB as
1738d88c1a5aSDimitry Andric // the chain end.
1739d88c1a5aSDimitry Andric if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1740d88c1a5aSDimitry Andric BlockFilter, PrevUnplacedBlockIt))
1741d88c1a5aSDimitry Andric continue;
1742d88c1a5aSDimitry Andric }
1743d88c1a5aSDimitry Andric
1744dff0c46cSDimitry Andric // Place this block, updating the datastructures to reflect its placement.
1745dff0c46cSDimitry Andric BlockChain &SuccChain = *BlockToChain[BestSucc];
17463ca95b02SDimitry Andric // Zero out UnscheduledPredecessors for the successor we're about to merge in case
1747dff0c46cSDimitry Andric // we selected a successor that didn't fit naturally into the CFG.
17483ca95b02SDimitry Andric SuccChain.UnscheduledPredecessors = 0;
17494ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
17503ca95b02SDimitry Andric << getBlockName(BestSucc) << "\n");
17513ca95b02SDimitry Andric markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
1752dff0c46cSDimitry Andric Chain.merge(BestSucc, &SuccChain);
175391bc56edSDimitry Andric BB = *std::prev(Chain.end());
1754dff0c46cSDimitry Andric }
1755dff0c46cSDimitry Andric
17564ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Finished forming chain for header block "
17573ca95b02SDimitry Andric << getBlockName(*Chain.begin()) << "\n");
1758dff0c46cSDimitry Andric }
1759dff0c46cSDimitry Andric
17604ba319b5SDimitry Andric /// Find the best loop top block for layout.
1761dff0c46cSDimitry Andric ///
1762cb4dff85SDimitry Andric /// Look for a block which is strictly better than the loop header for laying
1763cb4dff85SDimitry Andric /// out at the top of the loop. This looks for one and only one pattern:
1764cb4dff85SDimitry Andric /// a latch block with no conditional exit. This block will cause a conditional
1765cb4dff85SDimitry Andric /// jump around it or will be the bottom of the loop if we lay it out in place,
1766cb4dff85SDimitry Andric /// but if it it doesn't end up at the bottom of the loop for any reason,
1767cb4dff85SDimitry Andric /// rotation alone won't fix it. Because such a block will always result in an
1768cb4dff85SDimitry Andric /// unconditional jump (for the backedge) rotating it in front of the loop
1769cb4dff85SDimitry Andric /// header is always profitable.
1770cb4dff85SDimitry Andric MachineBasicBlock *
findBestLoopTop(const MachineLoop & L,const BlockFilterSet & LoopBlockSet)17717a7e6055SDimitry Andric MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
1772cb4dff85SDimitry Andric const BlockFilterSet &LoopBlockSet) {
1773d88c1a5aSDimitry Andric // Placing the latch block before the header may introduce an extra branch
1774d88c1a5aSDimitry Andric // that skips this block the first time the loop is executed, which we want
1775d88c1a5aSDimitry Andric // to avoid when optimising for size.
1776d88c1a5aSDimitry Andric // FIXME: in theory there is a case that does not introduce a new branch,
1777d88c1a5aSDimitry Andric // i.e. when the layout predecessor does not fallthrough to the loop header.
1778d88c1a5aSDimitry Andric // In practice this never happens though: there always seems to be a preheader
1779d88c1a5aSDimitry Andric // that can fallthrough and that is also placed before the header.
17802cab237bSDimitry Andric if (F->getFunction().optForSize())
1781d88c1a5aSDimitry Andric return L.getHeader();
1782d88c1a5aSDimitry Andric
1783cb4dff85SDimitry Andric // Check that the header hasn't been fused with a preheader block due to
1784cb4dff85SDimitry Andric // crazy branches. If it has, we need to start with the header at the top to
1785cb4dff85SDimitry Andric // prevent pulling the preheader into the loop body.
1786cb4dff85SDimitry Andric BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1787cb4dff85SDimitry Andric if (!LoopBlockSet.count(*HeaderChain.begin()))
1788cb4dff85SDimitry Andric return L.getHeader();
1789cb4dff85SDimitry Andric
17904ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Finding best loop top for: "
17914ba319b5SDimitry Andric << getBlockName(L.getHeader()) << "\n");
1792cb4dff85SDimitry Andric
1793cb4dff85SDimitry Andric BlockFrequency BestPredFreq;
179491bc56edSDimitry Andric MachineBasicBlock *BestPred = nullptr;
1795ff0cc061SDimitry Andric for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
1796cb4dff85SDimitry Andric if (!LoopBlockSet.count(Pred))
1797cb4dff85SDimitry Andric continue;
17984ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
179991bc56edSDimitry Andric << Pred->succ_size() << " successors, ";
180091bc56edSDimitry Andric MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
1801cb4dff85SDimitry Andric if (Pred->succ_size() > 1)
1802cb4dff85SDimitry Andric continue;
1803cb4dff85SDimitry Andric
1804cb4dff85SDimitry Andric BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1805cb4dff85SDimitry Andric if (!BestPred || PredFreq > BestPredFreq ||
1806cb4dff85SDimitry Andric (!(PredFreq < BestPredFreq) &&
1807cb4dff85SDimitry Andric Pred->isLayoutSuccessor(L.getHeader()))) {
1808cb4dff85SDimitry Andric BestPred = Pred;
1809cb4dff85SDimitry Andric BestPredFreq = PredFreq;
1810cb4dff85SDimitry Andric }
1811cb4dff85SDimitry Andric }
1812cb4dff85SDimitry Andric
1813cb4dff85SDimitry Andric // If no direct predecessor is fine, just use the loop header.
18143ca95b02SDimitry Andric if (!BestPred) {
18154ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " final top unchanged\n");
1816cb4dff85SDimitry Andric return L.getHeader();
18173ca95b02SDimitry Andric }
1818cb4dff85SDimitry Andric
1819cb4dff85SDimitry Andric // Walk backwards through any straight line of predecessors.
1820cb4dff85SDimitry Andric while (BestPred->pred_size() == 1 &&
1821cb4dff85SDimitry Andric (*BestPred->pred_begin())->succ_size() == 1 &&
1822cb4dff85SDimitry Andric *BestPred->pred_begin() != L.getHeader())
1823cb4dff85SDimitry Andric BestPred = *BestPred->pred_begin();
1824cb4dff85SDimitry Andric
18254ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
1826cb4dff85SDimitry Andric return BestPred;
1827cb4dff85SDimitry Andric }
1828cb4dff85SDimitry Andric
18294ba319b5SDimitry Andric /// Find the best loop exiting block for layout.
1830cb4dff85SDimitry Andric ///
1831dff0c46cSDimitry Andric /// This routine implements the logic to analyze the loop looking for the best
1832dff0c46cSDimitry Andric /// block to layout at the top of the loop. Typically this is done to maximize
1833dff0c46cSDimitry Andric /// fallthrough opportunities.
1834dff0c46cSDimitry Andric MachineBasicBlock *
findBestLoopExit(const MachineLoop & L,const BlockFilterSet & LoopBlockSet)18357a7e6055SDimitry Andric MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
1836dff0c46cSDimitry Andric const BlockFilterSet &LoopBlockSet) {
1837dff0c46cSDimitry Andric // We don't want to layout the loop linearly in all cases. If the loop header
1838dff0c46cSDimitry Andric // is just a normal basic block in the loop, we want to look for what block
1839dff0c46cSDimitry Andric // within the loop is the best one to layout at the top. However, if the loop
1840dff0c46cSDimitry Andric // header has be pre-merged into a chain due to predecessors not having
1841dff0c46cSDimitry Andric // analyzable branches, *and* the predecessor it is merged with is *not* part
1842dff0c46cSDimitry Andric // of the loop, rotating the header into the middle of the loop will create
1843dff0c46cSDimitry Andric // a non-contiguous range of blocks which is Very Bad. So start with the
1844dff0c46cSDimitry Andric // header and only rotate if safe.
1845dff0c46cSDimitry Andric BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1846dff0c46cSDimitry Andric if (!LoopBlockSet.count(*HeaderChain.begin()))
184791bc56edSDimitry Andric return nullptr;
1848dff0c46cSDimitry Andric
1849dff0c46cSDimitry Andric BlockFrequency BestExitEdgeFreq;
1850cb4dff85SDimitry Andric unsigned BestExitLoopDepth = 0;
185191bc56edSDimitry Andric MachineBasicBlock *ExitingBB = nullptr;
1852dff0c46cSDimitry Andric // If there are exits to outer loops, loop rotation can severely limit
18533ca95b02SDimitry Andric // fallthrough opportunities unless it selects such an exit. Keep a set of
1854dff0c46cSDimitry Andric // blocks where rotating to exit with that block will reach an outer loop.
1855dff0c46cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1856dff0c46cSDimitry Andric
18574ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Finding best loop exit for: "
18584ba319b5SDimitry Andric << getBlockName(L.getHeader()) << "\n");
1859ff0cc061SDimitry Andric for (MachineBasicBlock *MBB : L.getBlocks()) {
1860ff0cc061SDimitry Andric BlockChain &Chain = *BlockToChain[MBB];
1861dff0c46cSDimitry Andric // Ensure that this block is at the end of a chain; otherwise it could be
1862ff0cc061SDimitry Andric // mid-way through an inner loop or a successor of an unanalyzable branch.
1863ff0cc061SDimitry Andric if (MBB != *std::prev(Chain.end()))
1864dff0c46cSDimitry Andric continue;
1865dff0c46cSDimitry Andric
1866dff0c46cSDimitry Andric // Now walk the successors. We need to establish whether this has a viable
1867dff0c46cSDimitry Andric // exiting successor and whether it has a viable non-exiting successor.
1868dff0c46cSDimitry Andric // We store the old exiting state and restore it if a viable looping
1869dff0c46cSDimitry Andric // successor isn't found.
1870dff0c46cSDimitry Andric MachineBasicBlock *OldExitingBB = ExitingBB;
1871dff0c46cSDimitry Andric BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
1872cb4dff85SDimitry Andric bool HasLoopingSucc = false;
1873ff0cc061SDimitry Andric for (MachineBasicBlock *Succ : MBB->successors()) {
18747d523365SDimitry Andric if (Succ->isEHPad())
1875dff0c46cSDimitry Andric continue;
1876ff0cc061SDimitry Andric if (Succ == MBB)
1877dff0c46cSDimitry Andric continue;
1878ff0cc061SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ];
1879dff0c46cSDimitry Andric // Don't split chains, either this chain or the successor's chain.
1880cb4dff85SDimitry Andric if (&Chain == &SuccChain) {
18814ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1882ff0cc061SDimitry Andric << getBlockName(Succ) << " (chain conflict)\n");
1883dff0c46cSDimitry Andric continue;
1884dff0c46cSDimitry Andric }
1885dff0c46cSDimitry Andric
18867d523365SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
1887ff0cc061SDimitry Andric if (LoopBlockSet.count(Succ)) {
18884ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
18897d523365SDimitry Andric << getBlockName(Succ) << " (" << SuccProb << ")\n");
1890cb4dff85SDimitry Andric HasLoopingSucc = true;
1891dff0c46cSDimitry Andric continue;
1892cb4dff85SDimitry Andric }
1893dff0c46cSDimitry Andric
1894cb4dff85SDimitry Andric unsigned SuccLoopDepth = 0;
1895ff0cc061SDimitry Andric if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
1896cb4dff85SDimitry Andric SuccLoopDepth = ExitLoop->getLoopDepth();
1897cb4dff85SDimitry Andric if (ExitLoop->contains(&L))
1898ff0cc061SDimitry Andric BlocksExitingToOuterLoop.insert(MBB);
1899dff0c46cSDimitry Andric }
1900dff0c46cSDimitry Andric
1901ff0cc061SDimitry Andric BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
19024ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
19034ba319b5SDimitry Andric << getBlockName(Succ) << " [L:" << SuccLoopDepth
19044ba319b5SDimitry Andric << "] (";
190591bc56edSDimitry Andric MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
190691bc56edSDimitry Andric // Note that we bias this toward an existing layout successor to retain
190791bc56edSDimitry Andric // incoming order in the absence of better information. The exit must have
190891bc56edSDimitry Andric // a frequency higher than the current exit before we consider breaking
190991bc56edSDimitry Andric // the layout.
191091bc56edSDimitry Andric BranchProbability Bias(100 - ExitBlockBias, 100);
1911ff0cc061SDimitry Andric if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
1912cb4dff85SDimitry Andric ExitEdgeFreq > BestExitEdgeFreq ||
1913ff0cc061SDimitry Andric (MBB->isLayoutSuccessor(Succ) &&
191491bc56edSDimitry Andric !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
1915dff0c46cSDimitry Andric BestExitEdgeFreq = ExitEdgeFreq;
1916ff0cc061SDimitry Andric ExitingBB = MBB;
1917dff0c46cSDimitry Andric }
1918dff0c46cSDimitry Andric }
1919dff0c46cSDimitry Andric
1920cb4dff85SDimitry Andric if (!HasLoopingSucc) {
1921ff0cc061SDimitry Andric // Restore the old exiting state, no viable looping successor was found.
1922dff0c46cSDimitry Andric ExitingBB = OldExitingBB;
1923dff0c46cSDimitry Andric BestExitEdgeFreq = OldBestExitEdgeFreq;
1924dff0c46cSDimitry Andric }
1925dff0c46cSDimitry Andric }
1926cb4dff85SDimitry Andric // Without a candidate exiting block or with only a single block in the
1927dff0c46cSDimitry Andric // loop, just use the loop header to layout the loop.
1928d88c1a5aSDimitry Andric if (!ExitingBB) {
19294ba319b5SDimitry Andric LLVM_DEBUG(
19304ba319b5SDimitry Andric dbgs() << " No other candidate exit blocks, using loop header\n");
193191bc56edSDimitry Andric return nullptr;
1932d88c1a5aSDimitry Andric }
1933d88c1a5aSDimitry Andric if (L.getNumBlocks() == 1) {
19344ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
1935d88c1a5aSDimitry Andric return nullptr;
1936d88c1a5aSDimitry Andric }
1937dff0c46cSDimitry Andric
1938dff0c46cSDimitry Andric // Also, if we have exit blocks which lead to outer loops but didn't select
1939dff0c46cSDimitry Andric // one of them as the exiting block we are rotating toward, disable loop
1940dff0c46cSDimitry Andric // rotation altogether.
1941dff0c46cSDimitry Andric if (!BlocksExitingToOuterLoop.empty() &&
1942dff0c46cSDimitry Andric !BlocksExitingToOuterLoop.count(ExitingBB))
194391bc56edSDimitry Andric return nullptr;
1944dff0c46cSDimitry Andric
19454ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB)
19464ba319b5SDimitry Andric << "\n");
1947cb4dff85SDimitry Andric return ExitingBB;
1948cb4dff85SDimitry Andric }
1949cb4dff85SDimitry Andric
19504ba319b5SDimitry Andric /// Attempt to rotate an exiting block to the bottom of the loop.
1951cb4dff85SDimitry Andric ///
1952cb4dff85SDimitry Andric /// Once we have built a chain, try to rotate it to line up the hot exit block
1953cb4dff85SDimitry Andric /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1954cb4dff85SDimitry Andric /// branches. For example, if the loop has fallthrough into its header and out
1955cb4dff85SDimitry Andric /// of its bottom already, don't rotate it.
rotateLoop(BlockChain & LoopChain,const MachineBasicBlock * ExitingBB,const BlockFilterSet & LoopBlockSet)1956cb4dff85SDimitry Andric void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
19577a7e6055SDimitry Andric const MachineBasicBlock *ExitingBB,
1958cb4dff85SDimitry Andric const BlockFilterSet &LoopBlockSet) {
1959cb4dff85SDimitry Andric if (!ExitingBB)
1960cb4dff85SDimitry Andric return;
1961cb4dff85SDimitry Andric
1962cb4dff85SDimitry Andric MachineBasicBlock *Top = *LoopChain.begin();
1963c4394386SDimitry Andric MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
1964c4394386SDimitry Andric
1965c4394386SDimitry Andric // If ExitingBB is already the last one in a chain then nothing to do.
1966c4394386SDimitry Andric if (Bottom == ExitingBB)
1967c4394386SDimitry Andric return;
1968c4394386SDimitry Andric
1969cb4dff85SDimitry Andric bool ViableTopFallthrough = false;
1970ff0cc061SDimitry Andric for (MachineBasicBlock *Pred : Top->predecessors()) {
1971ff0cc061SDimitry Andric BlockChain *PredChain = BlockToChain[Pred];
1972ff0cc061SDimitry Andric if (!LoopBlockSet.count(Pred) &&
1973ff0cc061SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) {
1974cb4dff85SDimitry Andric ViableTopFallthrough = true;
1975cb4dff85SDimitry Andric break;
1976cb4dff85SDimitry Andric }
1977cb4dff85SDimitry Andric }
1978cb4dff85SDimitry Andric
1979cb4dff85SDimitry Andric // If the header has viable fallthrough, check whether the current loop
1980cb4dff85SDimitry Andric // bottom is a viable exiting block. If so, bail out as rotating will
1981cb4dff85SDimitry Andric // introduce an unnecessary branch.
1982cb4dff85SDimitry Andric if (ViableTopFallthrough) {
1983ff0cc061SDimitry Andric for (MachineBasicBlock *Succ : Bottom->successors()) {
1984ff0cc061SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ];
1985ff0cc061SDimitry Andric if (!LoopBlockSet.count(Succ) &&
1986ff0cc061SDimitry Andric (!SuccChain || Succ == *SuccChain->begin()))
1987cb4dff85SDimitry Andric return;
1988cb4dff85SDimitry Andric }
1989cb4dff85SDimitry Andric }
1990cb4dff85SDimitry Andric
19912cab237bSDimitry Andric BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
1992cb4dff85SDimitry Andric if (ExitIt == LoopChain.end())
1993cb4dff85SDimitry Andric return;
1994cb4dff85SDimitry Andric
1995c4394386SDimitry Andric // Rotating a loop exit to the bottom when there is a fallthrough to top
1996c4394386SDimitry Andric // trades the entry fallthrough for an exit fallthrough.
1997c4394386SDimitry Andric // If there is no bottom->top edge, but the chosen exit block does have
1998c4394386SDimitry Andric // a fallthrough, we break that fallthrough for nothing in return.
1999c4394386SDimitry Andric
2000c4394386SDimitry Andric // Let's consider an example. We have a built chain of basic blocks
2001c4394386SDimitry Andric // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
2002c4394386SDimitry Andric // By doing a rotation we get
2003c4394386SDimitry Andric // Bk+1, ..., Bn, B1, ..., Bk
2004c4394386SDimitry Andric // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
2005c4394386SDimitry Andric // If we had a fallthrough Bk -> Bk+1 it is broken now.
2006c4394386SDimitry Andric // It might be compensated by fallthrough Bn -> B1.
2007c4394386SDimitry Andric // So we have a condition to avoid creation of extra branch by loop rotation.
2008c4394386SDimitry Andric // All below must be true to avoid loop rotation:
2009c4394386SDimitry Andric // If there is a fallthrough to top (B1)
2010c4394386SDimitry Andric // There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
2011c4394386SDimitry Andric // There is no fallthrough from bottom (Bn) to top (B1).
2012c4394386SDimitry Andric // Please note that there is no exit fallthrough from Bn because we checked it
2013c4394386SDimitry Andric // above.
2014c4394386SDimitry Andric if (ViableTopFallthrough) {
2015c4394386SDimitry Andric assert(std::next(ExitIt) != LoopChain.end() &&
2016c4394386SDimitry Andric "Exit should not be last BB");
2017c4394386SDimitry Andric MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
2018c4394386SDimitry Andric if (ExitingBB->isSuccessor(NextBlockInChain))
2019c4394386SDimitry Andric if (!Bottom->isSuccessor(Top))
2020c4394386SDimitry Andric return;
2021c4394386SDimitry Andric }
2022c4394386SDimitry Andric
20234ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
2024c4394386SDimitry Andric << " at bottom\n");
202591bc56edSDimitry Andric std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
2026dff0c46cSDimitry Andric }
2027dff0c46cSDimitry Andric
20284ba319b5SDimitry Andric /// Attempt to rotate a loop based on profile data to reduce branch cost.
20297d523365SDimitry Andric ///
20307d523365SDimitry Andric /// With profile data, we can determine the cost in terms of missed fall through
20317d523365SDimitry Andric /// opportunities when rotating a loop chain and select the best rotation.
20327d523365SDimitry Andric /// Basically, there are three kinds of cost to consider for each rotation:
20337d523365SDimitry Andric /// 1. The possibly missed fall through edge (if it exists) from BB out of
20347d523365SDimitry Andric /// the loop to the loop header.
20357d523365SDimitry Andric /// 2. The possibly missed fall through edges (if they exist) from the loop
20367d523365SDimitry Andric /// exits to BB out of the loop.
20377d523365SDimitry Andric /// 3. The missed fall through edge (if it exists) from the last BB to the
20387d523365SDimitry Andric /// first BB in the loop chain.
20397d523365SDimitry Andric /// Therefore, the cost for a given rotation is the sum of costs listed above.
20407d523365SDimitry Andric /// We select the best rotation with the smallest cost.
rotateLoopWithProfile(BlockChain & LoopChain,const MachineLoop & L,const BlockFilterSet & LoopBlockSet)20417d523365SDimitry Andric void MachineBlockPlacement::rotateLoopWithProfile(
20427a7e6055SDimitry Andric BlockChain &LoopChain, const MachineLoop &L,
20437a7e6055SDimitry Andric const BlockFilterSet &LoopBlockSet) {
20447d523365SDimitry Andric auto HeaderBB = L.getHeader();
20452cab237bSDimitry Andric auto HeaderIter = llvm::find(LoopChain, HeaderBB);
20467d523365SDimitry Andric auto RotationPos = LoopChain.end();
20477d523365SDimitry Andric
20487d523365SDimitry Andric BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
20497d523365SDimitry Andric
20507d523365SDimitry Andric // A utility lambda that scales up a block frequency by dividing it by a
20517d523365SDimitry Andric // branch probability which is the reciprocal of the scale.
20527d523365SDimitry Andric auto ScaleBlockFrequency = [](BlockFrequency Freq,
20537d523365SDimitry Andric unsigned Scale) -> BlockFrequency {
20547d523365SDimitry Andric if (Scale == 0)
20557d523365SDimitry Andric return 0;
20567d523365SDimitry Andric // Use operator / between BlockFrequency and BranchProbability to implement
20577d523365SDimitry Andric // saturating multiplication.
20587d523365SDimitry Andric return Freq / BranchProbability(1, Scale);
20597d523365SDimitry Andric };
20607d523365SDimitry Andric
20617d523365SDimitry Andric // Compute the cost of the missed fall-through edge to the loop header if the
20627d523365SDimitry Andric // chain head is not the loop header. As we only consider natural loops with
20637d523365SDimitry Andric // single header, this computation can be done only once.
20647d523365SDimitry Andric BlockFrequency HeaderFallThroughCost(0);
20657d523365SDimitry Andric for (auto *Pred : HeaderBB->predecessors()) {
20667d523365SDimitry Andric BlockChain *PredChain = BlockToChain[Pred];
20677d523365SDimitry Andric if (!LoopBlockSet.count(Pred) &&
20687d523365SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) {
20697d523365SDimitry Andric auto EdgeFreq =
20707d523365SDimitry Andric MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
20717d523365SDimitry Andric auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
20727d523365SDimitry Andric // If the predecessor has only an unconditional jump to the header, we
20737d523365SDimitry Andric // need to consider the cost of this jump.
20747d523365SDimitry Andric if (Pred->succ_size() == 1)
20757d523365SDimitry Andric FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
20767d523365SDimitry Andric HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
20777d523365SDimitry Andric }
20787d523365SDimitry Andric }
20797d523365SDimitry Andric
20807d523365SDimitry Andric // Here we collect all exit blocks in the loop, and for each exit we find out
20817d523365SDimitry Andric // its hottest exit edge. For each loop rotation, we define the loop exit cost
20827d523365SDimitry Andric // as the sum of frequencies of exit edges we collect here, excluding the exit
20837d523365SDimitry Andric // edge from the tail of the loop chain.
20847d523365SDimitry Andric SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
20857d523365SDimitry Andric for (auto BB : LoopChain) {
20867d523365SDimitry Andric auto LargestExitEdgeProb = BranchProbability::getZero();
20877d523365SDimitry Andric for (auto *Succ : BB->successors()) {
20887d523365SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ];
20897d523365SDimitry Andric if (!LoopBlockSet.count(Succ) &&
20907d523365SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) {
20917d523365SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
20927d523365SDimitry Andric LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
20937d523365SDimitry Andric }
20947d523365SDimitry Andric }
20957d523365SDimitry Andric if (LargestExitEdgeProb > BranchProbability::getZero()) {
20967d523365SDimitry Andric auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
20977d523365SDimitry Andric ExitsWithFreq.emplace_back(BB, ExitFreq);
20987d523365SDimitry Andric }
20997d523365SDimitry Andric }
21007d523365SDimitry Andric
21017d523365SDimitry Andric // In this loop we iterate every block in the loop chain and calculate the
21027d523365SDimitry Andric // cost assuming the block is the head of the loop chain. When the loop ends,
21037d523365SDimitry Andric // we should have found the best candidate as the loop chain's head.
21047d523365SDimitry Andric for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
21057d523365SDimitry Andric EndIter = LoopChain.end();
21067d523365SDimitry Andric Iter != EndIter; Iter++, TailIter++) {
21077d523365SDimitry Andric // TailIter is used to track the tail of the loop chain if the block we are
21087d523365SDimitry Andric // checking (pointed by Iter) is the head of the chain.
21097d523365SDimitry Andric if (TailIter == LoopChain.end())
21107d523365SDimitry Andric TailIter = LoopChain.begin();
21117d523365SDimitry Andric
21127d523365SDimitry Andric auto TailBB = *TailIter;
21137d523365SDimitry Andric
21147d523365SDimitry Andric // Calculate the cost by putting this BB to the top.
21157d523365SDimitry Andric BlockFrequency Cost = 0;
21167d523365SDimitry Andric
21177d523365SDimitry Andric // If the current BB is the loop header, we need to take into account the
21187d523365SDimitry Andric // cost of the missed fall through edge from outside of the loop to the
21197d523365SDimitry Andric // header.
21207d523365SDimitry Andric if (Iter != HeaderIter)
21217d523365SDimitry Andric Cost += HeaderFallThroughCost;
21227d523365SDimitry Andric
21237d523365SDimitry Andric // Collect the loop exit cost by summing up frequencies of all exit edges
21247d523365SDimitry Andric // except the one from the chain tail.
21257d523365SDimitry Andric for (auto &ExitWithFreq : ExitsWithFreq)
21267d523365SDimitry Andric if (TailBB != ExitWithFreq.first)
21277d523365SDimitry Andric Cost += ExitWithFreq.second;
21287d523365SDimitry Andric
21297d523365SDimitry Andric // The cost of breaking the once fall-through edge from the tail to the top
21307d523365SDimitry Andric // of the loop chain. Here we need to consider three cases:
21317d523365SDimitry Andric // 1. If the tail node has only one successor, then we will get an
21327d523365SDimitry Andric // additional jmp instruction. So the cost here is (MisfetchCost +
21337d523365SDimitry Andric // JumpInstCost) * tail node frequency.
21347d523365SDimitry Andric // 2. If the tail node has two successors, then we may still get an
21357d523365SDimitry Andric // additional jmp instruction if the layout successor after the loop
21367d523365SDimitry Andric // chain is not its CFG successor. Note that the more frequently executed
21377d523365SDimitry Andric // jmp instruction will be put ahead of the other one. Assume the
21387d523365SDimitry Andric // frequency of those two branches are x and y, where x is the frequency
21397d523365SDimitry Andric // of the edge to the chain head, then the cost will be
21407d523365SDimitry Andric // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
21417d523365SDimitry Andric // 3. If the tail node has more than two successors (this rarely happens),
21427d523365SDimitry Andric // we won't consider any additional cost.
21437d523365SDimitry Andric if (TailBB->isSuccessor(*Iter)) {
21447d523365SDimitry Andric auto TailBBFreq = MBFI->getBlockFreq(TailBB);
21457d523365SDimitry Andric if (TailBB->succ_size() == 1)
21467d523365SDimitry Andric Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
21477d523365SDimitry Andric MisfetchCost + JumpInstCost);
21487d523365SDimitry Andric else if (TailBB->succ_size() == 2) {
21497d523365SDimitry Andric auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
21507d523365SDimitry Andric auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
21517d523365SDimitry Andric auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
21527d523365SDimitry Andric ? TailBBFreq * TailToHeadProb.getCompl()
21537d523365SDimitry Andric : TailToHeadFreq;
21547d523365SDimitry Andric Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
21557d523365SDimitry Andric ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
21567d523365SDimitry Andric }
21577d523365SDimitry Andric }
21587d523365SDimitry Andric
21594ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "The cost of loop rotation by making "
21604ba319b5SDimitry Andric << getBlockName(*Iter)
21617d523365SDimitry Andric << " to the top: " << Cost.getFrequency() << "\n");
21627d523365SDimitry Andric
21637d523365SDimitry Andric if (Cost < SmallestRotationCost) {
21647d523365SDimitry Andric SmallestRotationCost = Cost;
21657d523365SDimitry Andric RotationPos = Iter;
21667d523365SDimitry Andric }
21677d523365SDimitry Andric }
21687d523365SDimitry Andric
21697d523365SDimitry Andric if (RotationPos != LoopChain.end()) {
21704ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
21717d523365SDimitry Andric << " to the top\n");
21727d523365SDimitry Andric std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
21737d523365SDimitry Andric }
21747d523365SDimitry Andric }
21757d523365SDimitry Andric
21764ba319b5SDimitry Andric /// Collect blocks in the given loop that are to be placed.
21777d523365SDimitry Andric ///
21787d523365SDimitry Andric /// When profile data is available, exclude cold blocks from the returned set;
21797d523365SDimitry Andric /// otherwise, collect all blocks in the loop.
21807d523365SDimitry Andric MachineBlockPlacement::BlockFilterSet
collectLoopBlockSet(const MachineLoop & L)21817a7e6055SDimitry Andric MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
21827d523365SDimitry Andric BlockFilterSet LoopBlockSet;
21837d523365SDimitry Andric
21847d523365SDimitry Andric // Filter cold blocks off from LoopBlockSet when profile data is available.
21857d523365SDimitry Andric // Collect the sum of frequencies of incoming edges to the loop header from
21867d523365SDimitry Andric // outside. If we treat the loop as a super block, this is the frequency of
21877d523365SDimitry Andric // the loop. Then for each block in the loop, we calculate the ratio between
21887d523365SDimitry Andric // its frequency and the frequency of the loop block. When it is too small,
21897d523365SDimitry Andric // don't add it to the loop chain. If there are outer loops, then this block
21907d523365SDimitry Andric // will be merged into the first outer loop chain for which this block is not
21917d523365SDimitry Andric // cold anymore. This needs precise profile data and we only do this when
21927d523365SDimitry Andric // profile data is available.
2193da09e106SDimitry Andric if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
21947d523365SDimitry Andric BlockFrequency LoopFreq(0);
21957d523365SDimitry Andric for (auto LoopPred : L.getHeader()->predecessors())
21967d523365SDimitry Andric if (!L.contains(LoopPred))
21977d523365SDimitry Andric LoopFreq += MBFI->getBlockFreq(LoopPred) *
21987d523365SDimitry Andric MBPI->getEdgeProbability(LoopPred, L.getHeader());
21997d523365SDimitry Andric
22007d523365SDimitry Andric for (MachineBasicBlock *LoopBB : L.getBlocks()) {
22017d523365SDimitry Andric auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
22027d523365SDimitry Andric if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
22037d523365SDimitry Andric continue;
22047d523365SDimitry Andric LoopBlockSet.insert(LoopBB);
22057d523365SDimitry Andric }
22067d523365SDimitry Andric } else
22077d523365SDimitry Andric LoopBlockSet.insert(L.block_begin(), L.block_end());
22087d523365SDimitry Andric
22097d523365SDimitry Andric return LoopBlockSet;
22107d523365SDimitry Andric }
22117d523365SDimitry Andric
22124ba319b5SDimitry Andric /// Forms basic block chains from the natural loop structures.
2213dff0c46cSDimitry Andric ///
2214dff0c46cSDimitry Andric /// These chains are designed to preserve the existing *structure* of the code
2215dff0c46cSDimitry Andric /// as much as possible. We can then stitch the chains together in a way which
2216dff0c46cSDimitry Andric /// both preserves the topological structure and minimizes taken conditional
2217dff0c46cSDimitry Andric /// branches.
buildLoopChains(const MachineLoop & L)22187a7e6055SDimitry Andric void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
2219dff0c46cSDimitry Andric // First recurse through any nested loops, building chains for those inner
2220dff0c46cSDimitry Andric // loops.
22217a7e6055SDimitry Andric for (const MachineLoop *InnerLoop : L)
22223ca95b02SDimitry Andric buildLoopChains(*InnerLoop);
2223dff0c46cSDimitry Andric
2224d8866befSDimitry Andric assert(BlockWorkList.empty() &&
2225d8866befSDimitry Andric "BlockWorkList not empty when starting to build loop chains.");
2226d8866befSDimitry Andric assert(EHPadWorkList.empty() &&
2227d8866befSDimitry Andric "EHPadWorkList not empty when starting to build loop chains.");
22283ca95b02SDimitry Andric BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
22297d523365SDimitry Andric
22307d523365SDimitry Andric // Check if we have profile data for this function. If yes, we will rotate
22317d523365SDimitry Andric // this loop by modeling costs more precisely which requires the profile data
22327d523365SDimitry Andric // for better layout.
22337d523365SDimitry Andric bool RotateLoopWithProfile =
22343ca95b02SDimitry Andric ForcePreciseRotationCost ||
2235da09e106SDimitry Andric (PreciseRotationCost && F->getFunction().hasProfileData());
2236dff0c46cSDimitry Andric
2237cb4dff85SDimitry Andric // First check to see if there is an obviously preferable top block for the
2238cb4dff85SDimitry Andric // loop. This will default to the header, but may end up as one of the
2239cb4dff85SDimitry Andric // predecessors to the header if there is one which will result in strictly
2240cb4dff85SDimitry Andric // fewer branches in the loop body.
22417d523365SDimitry Andric // When we use profile data to rotate the loop, this is unnecessary.
22427d523365SDimitry Andric MachineBasicBlock *LoopTop =
22437d523365SDimitry Andric RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
2244cb4dff85SDimitry Andric
2245cb4dff85SDimitry Andric // If we selected just the header for the loop top, look for a potentially
2246cb4dff85SDimitry Andric // profitable exit block in the event that rotating the loop can eliminate
2247cb4dff85SDimitry Andric // branches by placing an exit edge at the bottom.
22482cab237bSDimitry Andric //
22492cab237bSDimitry Andric // Loops are processed innermost to uttermost, make sure we clear
22502cab237bSDimitry Andric // PreferredLoopExit before processing a new loop.
22512cab237bSDimitry Andric PreferredLoopExit = nullptr;
22527d523365SDimitry Andric if (!RotateLoopWithProfile && LoopTop == L.getHeader())
2253d88c1a5aSDimitry Andric PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
2254cb4dff85SDimitry Andric
2255cb4dff85SDimitry Andric BlockChain &LoopChain = *BlockToChain[LoopTop];
2256dff0c46cSDimitry Andric
2257dff0c46cSDimitry Andric // FIXME: This is a really lame way of walking the chains in the loop: we
2258dff0c46cSDimitry Andric // walk the blocks, and use a set to prevent visiting a particular chain
2259dff0c46cSDimitry Andric // twice.
2260dff0c46cSDimitry Andric SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2261d8866befSDimitry Andric assert(LoopChain.UnscheduledPredecessors == 0 &&
2262d8866befSDimitry Andric "LoopChain should not have unscheduled predecessors.");
2263dff0c46cSDimitry Andric UpdatedPreds.insert(&LoopChain);
22647d523365SDimitry Andric
22657a7e6055SDimitry Andric for (const MachineBasicBlock *LoopBB : LoopBlockSet)
22663ca95b02SDimitry Andric fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
2267dff0c46cSDimitry Andric
22683ca95b02SDimitry Andric buildChain(LoopTop, LoopChain, &LoopBlockSet);
22697d523365SDimitry Andric
22707d523365SDimitry Andric if (RotateLoopWithProfile)
22717d523365SDimitry Andric rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
22727d523365SDimitry Andric else
2273d88c1a5aSDimitry Andric rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
2274dff0c46cSDimitry Andric
22754ba319b5SDimitry Andric LLVM_DEBUG({
2276dff0c46cSDimitry Andric // Crash at the end so we get all of the debugging output first.
2277dff0c46cSDimitry Andric bool BadLoop = false;
22783ca95b02SDimitry Andric if (LoopChain.UnscheduledPredecessors) {
2279dff0c46cSDimitry Andric BadLoop = true;
2280dff0c46cSDimitry Andric dbgs() << "Loop chain contains a block without its preds placed!\n"
2281dff0c46cSDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2282dff0c46cSDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
2283dff0c46cSDimitry Andric }
2284ff0cc061SDimitry Andric for (MachineBasicBlock *ChainBB : LoopChain) {
2285ff0cc061SDimitry Andric dbgs() << " ... " << getBlockName(ChainBB) << "\n";
2286d88c1a5aSDimitry Andric if (!LoopBlockSet.remove(ChainBB)) {
2287dff0c46cSDimitry Andric // We don't mark the loop as bad here because there are real situations
2288dff0c46cSDimitry Andric // where this can occur. For example, with an unanalyzable fallthrough
2289dff0c46cSDimitry Andric // from a loop block to a non-loop block or vice versa.
2290dff0c46cSDimitry Andric dbgs() << "Loop chain contains a block not contained by the loop!\n"
2291dff0c46cSDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2292dff0c46cSDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2293ff0cc061SDimitry Andric << " Bad block: " << getBlockName(ChainBB) << "\n";
2294dff0c46cSDimitry Andric }
2295cb4dff85SDimitry Andric }
2296dff0c46cSDimitry Andric
2297dff0c46cSDimitry Andric if (!LoopBlockSet.empty()) {
2298dff0c46cSDimitry Andric BadLoop = true;
22997a7e6055SDimitry Andric for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2300dff0c46cSDimitry Andric dbgs() << "Loop contains blocks never placed into a chain!\n"
2301dff0c46cSDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2302dff0c46cSDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2303ff0cc061SDimitry Andric << " Bad block: " << getBlockName(LoopBB) << "\n";
2304dff0c46cSDimitry Andric }
2305dff0c46cSDimitry Andric assert(!BadLoop && "Detected problems with the placement of this loop.");
2306dff0c46cSDimitry Andric });
23073ca95b02SDimitry Andric
23083ca95b02SDimitry Andric BlockWorkList.clear();
23093ca95b02SDimitry Andric EHPadWorkList.clear();
2310dff0c46cSDimitry Andric }
2311dff0c46cSDimitry Andric
buildCFGChains()23123ca95b02SDimitry Andric void MachineBlockPlacement::buildCFGChains() {
2313dff0c46cSDimitry Andric // Ensure that every BB in the function has an associated chain to simplify
2314dff0c46cSDimitry Andric // the assumptions of the remaining algorithm.
2315dff0c46cSDimitry Andric SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
23163ca95b02SDimitry Andric for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
23173ca95b02SDimitry Andric ++FI) {
23187d523365SDimitry Andric MachineBasicBlock *BB = &*FI;
2319ff0cc061SDimitry Andric BlockChain *Chain =
2320ff0cc061SDimitry Andric new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
2321dff0c46cSDimitry Andric // Also, merge any blocks which we cannot reason about and must preserve
2322dff0c46cSDimitry Andric // the exact fallthrough behavior for.
23232cab237bSDimitry Andric while (true) {
2324dff0c46cSDimitry Andric Cond.clear();
232591bc56edSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
23263ca95b02SDimitry Andric if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
2327dff0c46cSDimitry Andric break;
2328dff0c46cSDimitry Andric
23297d523365SDimitry Andric MachineFunction::iterator NextFI = std::next(FI);
23307d523365SDimitry Andric MachineBasicBlock *NextBB = &*NextFI;
2331dff0c46cSDimitry Andric // Ensure that the layout successor is a viable block, as we know that
2332dff0c46cSDimitry Andric // fallthrough is a possibility.
2333dff0c46cSDimitry Andric assert(NextFI != FE && "Can't fallthrough past the last block.");
23344ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2335dff0c46cSDimitry Andric << getBlockName(BB) << " -> " << getBlockName(NextBB)
2336dff0c46cSDimitry Andric << "\n");
233791bc56edSDimitry Andric Chain->merge(NextBB, nullptr);
2338d88c1a5aSDimitry Andric #ifndef NDEBUG
2339d88c1a5aSDimitry Andric BlocksWithUnanalyzableExits.insert(&*BB);
2340d88c1a5aSDimitry Andric #endif
2341dff0c46cSDimitry Andric FI = NextFI;
2342dff0c46cSDimitry Andric BB = NextBB;
2343dff0c46cSDimitry Andric }
2344dff0c46cSDimitry Andric }
2345dff0c46cSDimitry Andric
2346dff0c46cSDimitry Andric // Build any loop-based chains.
2347d88c1a5aSDimitry Andric PreferredLoopExit = nullptr;
2348ff0cc061SDimitry Andric for (MachineLoop *L : *MLI)
23493ca95b02SDimitry Andric buildLoopChains(*L);
2350dff0c46cSDimitry Andric
2351d8866befSDimitry Andric assert(BlockWorkList.empty() &&
2352d8866befSDimitry Andric "BlockWorkList should be empty before building final chain.");
2353d8866befSDimitry Andric assert(EHPadWorkList.empty() &&
2354d8866befSDimitry Andric "EHPadWorkList should be empty before building final chain.");
2355dff0c46cSDimitry Andric
2356dff0c46cSDimitry Andric SmallPtrSet<BlockChain *, 4> UpdatedPreds;
23573ca95b02SDimitry Andric for (MachineBasicBlock &MBB : *F)
23583ca95b02SDimitry Andric fillWorkLists(&MBB, UpdatedPreds);
2359dff0c46cSDimitry Andric
23603ca95b02SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()];
23613ca95b02SDimitry Andric buildChain(&F->front(), FunctionChain);
2362dff0c46cSDimitry Andric
236391bc56edSDimitry Andric #ifndef NDEBUG
23642cab237bSDimitry Andric using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
236591bc56edSDimitry Andric #endif
23664ba319b5SDimitry Andric LLVM_DEBUG({
2367dff0c46cSDimitry Andric // Crash at the end so we get all of the debugging output first.
2368dff0c46cSDimitry Andric bool BadFunc = false;
2369dff0c46cSDimitry Andric FunctionBlockSetType FunctionBlockSet;
23703ca95b02SDimitry Andric for (MachineBasicBlock &MBB : *F)
2371ff0cc061SDimitry Andric FunctionBlockSet.insert(&MBB);
2372dff0c46cSDimitry Andric
2373ff0cc061SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain)
2374ff0cc061SDimitry Andric if (!FunctionBlockSet.erase(ChainBB)) {
2375dff0c46cSDimitry Andric BadFunc = true;
2376dff0c46cSDimitry Andric dbgs() << "Function chain contains a block not in the function!\n"
2377ff0cc061SDimitry Andric << " Bad block: " << getBlockName(ChainBB) << "\n";
2378dff0c46cSDimitry Andric }
2379dff0c46cSDimitry Andric
2380dff0c46cSDimitry Andric if (!FunctionBlockSet.empty()) {
2381dff0c46cSDimitry Andric BadFunc = true;
2382ff0cc061SDimitry Andric for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
2383dff0c46cSDimitry Andric dbgs() << "Function contains blocks never placed into a chain!\n"
2384ff0cc061SDimitry Andric << " Bad block: " << getBlockName(RemainingBB) << "\n";
2385dff0c46cSDimitry Andric }
2386dff0c46cSDimitry Andric assert(!BadFunc && "Detected problems with the block placement.");
2387dff0c46cSDimitry Andric });
2388dff0c46cSDimitry Andric
2389dff0c46cSDimitry Andric // Splice the blocks into place.
23903ca95b02SDimitry Andric MachineFunction::iterator InsertPos = F->begin();
23914ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n");
2392ff0cc061SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) {
23934ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2394dff0c46cSDimitry Andric : " ... ")
2395ff0cc061SDimitry Andric << getBlockName(ChainBB) << "\n");
2396ff0cc061SDimitry Andric if (InsertPos != MachineFunction::iterator(ChainBB))
23973ca95b02SDimitry Andric F->splice(InsertPos, ChainBB);
2398dff0c46cSDimitry Andric else
2399dff0c46cSDimitry Andric ++InsertPos;
2400dff0c46cSDimitry Andric
2401dff0c46cSDimitry Andric // Update the terminator of the previous block.
2402ff0cc061SDimitry Andric if (ChainBB == *FunctionChain.begin())
2403dff0c46cSDimitry Andric continue;
24047d523365SDimitry Andric MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
2405dff0c46cSDimitry Andric
2406dff0c46cSDimitry Andric // FIXME: It would be awesome of updateTerminator would just return rather
2407dff0c46cSDimitry Andric // than assert when the branch cannot be analyzed in order to remove this
2408dff0c46cSDimitry Andric // boiler plate.
2409dff0c46cSDimitry Andric Cond.clear();
241091bc56edSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
24113ca95b02SDimitry Andric
2412d88c1a5aSDimitry Andric #ifndef NDEBUG
2413d88c1a5aSDimitry Andric if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2414d88c1a5aSDimitry Andric // Given the exact block placement we chose, we may actually not _need_ to
2415d88c1a5aSDimitry Andric // be able to edit PrevBB's terminator sequence, but not being _able_ to
2416d88c1a5aSDimitry Andric // do that at this point is a bug.
2417d88c1a5aSDimitry Andric assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2418d88c1a5aSDimitry Andric !PrevBB->canFallThrough()) &&
2419d88c1a5aSDimitry Andric "Unexpected block with un-analyzable fallthrough!");
2420d88c1a5aSDimitry Andric Cond.clear();
2421d88c1a5aSDimitry Andric TBB = FBB = nullptr;
2422d88c1a5aSDimitry Andric }
2423d88c1a5aSDimitry Andric #endif
2424d88c1a5aSDimitry Andric
2425f785676fSDimitry Andric // The "PrevBB" is not yet updated to reflect current code layout, so,
24263ca95b02SDimitry Andric // o. it may fall-through to a block without explicit "goto" instruction
2427f785676fSDimitry Andric // before layout, and no longer fall-through it after layout; or
2428f785676fSDimitry Andric // o. just opposite.
2429f785676fSDimitry Andric //
24303ca95b02SDimitry Andric // analyzeBranch() may return erroneous value for FBB when these two
24313ca95b02SDimitry Andric // situations take place. For the first scenario FBB is mistakenly set NULL;
24323ca95b02SDimitry Andric // for the 2nd scenario, the FBB, which is expected to be NULL, is
24333ca95b02SDimitry Andric // mistakenly pointing to "*BI".
24343ca95b02SDimitry Andric // Thus, if the future change needs to use FBB before the layout is set, it
24353ca95b02SDimitry Andric // has to correct FBB first by using the code similar to the following:
2436f785676fSDimitry Andric //
24373ca95b02SDimitry Andric // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
24383ca95b02SDimitry Andric // PrevBB->updateTerminator();
24393ca95b02SDimitry Andric // Cond.clear();
24403ca95b02SDimitry Andric // TBB = FBB = nullptr;
24413ca95b02SDimitry Andric // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
24423ca95b02SDimitry Andric // // FIXME: This should never take place.
24433ca95b02SDimitry Andric // TBB = FBB = nullptr;
24443ca95b02SDimitry Andric // }
24453ca95b02SDimitry Andric // }
24463ca95b02SDimitry Andric if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
2447f785676fSDimitry Andric PrevBB->updateTerminator();
24487ae0e2c9SDimitry Andric }
2449dff0c46cSDimitry Andric
2450dff0c46cSDimitry Andric // Fixup the last block.
2451dff0c46cSDimitry Andric Cond.clear();
245291bc56edSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
24533ca95b02SDimitry Andric if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
24543ca95b02SDimitry Andric F->back().updateTerminator();
2455dff0c46cSDimitry Andric
24563ca95b02SDimitry Andric BlockWorkList.clear();
24573ca95b02SDimitry Andric EHPadWorkList.clear();
24583ca95b02SDimitry Andric }
24593ca95b02SDimitry Andric
optimizeBranches()24603ca95b02SDimitry Andric void MachineBlockPlacement::optimizeBranches() {
24613ca95b02SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()];
24623ca95b02SDimitry Andric SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
24633ca95b02SDimitry Andric
24643ca95b02SDimitry Andric // Now that all the basic blocks in the chain have the proper layout,
24653ca95b02SDimitry Andric // make a final call to AnalyzeBranch with AllowModify set.
24663ca95b02SDimitry Andric // Indeed, the target may be able to optimize the branches in a way we
24673ca95b02SDimitry Andric // cannot because all branches may not be analyzable.
24683ca95b02SDimitry Andric // E.g., the target may be able to remove an unconditional branch to
24693ca95b02SDimitry Andric // a fallthrough when it occurs after predicated terminators.
24703ca95b02SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) {
24713ca95b02SDimitry Andric Cond.clear();
24723ca95b02SDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
24733ca95b02SDimitry Andric if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
24743ca95b02SDimitry Andric // If PrevBB has a two-way branch, try to re-order the branches
24753ca95b02SDimitry Andric // such that we branch to the successor with higher probability first.
24763ca95b02SDimitry Andric if (TBB && !Cond.empty() && FBB &&
24773ca95b02SDimitry Andric MBPI->getEdgeProbability(ChainBB, FBB) >
24783ca95b02SDimitry Andric MBPI->getEdgeProbability(ChainBB, TBB) &&
2479d88c1a5aSDimitry Andric !TII->reverseBranchCondition(Cond)) {
24804ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Reverse order of the two branches: "
24813ca95b02SDimitry Andric << getBlockName(ChainBB) << "\n");
24824ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Edge probability: "
24833ca95b02SDimitry Andric << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
24843ca95b02SDimitry Andric << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
24853ca95b02SDimitry Andric DebugLoc dl; // FIXME: this is nowhere
2486d88c1a5aSDimitry Andric TII->removeBranch(*ChainBB);
2487d88c1a5aSDimitry Andric TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
24883ca95b02SDimitry Andric ChainBB->updateTerminator();
24893ca95b02SDimitry Andric }
24903ca95b02SDimitry Andric }
24913ca95b02SDimitry Andric }
24923ca95b02SDimitry Andric }
24933ca95b02SDimitry Andric
alignBlocks()24943ca95b02SDimitry Andric void MachineBlockPlacement::alignBlocks() {
2495cb4dff85SDimitry Andric // Walk through the backedges of the function now that we have fully laid out
2496cb4dff85SDimitry Andric // the basic blocks and align the destination of each backedge. We don't rely
24977ae0e2c9SDimitry Andric // exclusively on the loop info here so that we can align backedges in
24987ae0e2c9SDimitry Andric // unnatural CFGs and backedges that were introduced purely because of the
24997ae0e2c9SDimitry Andric // loop rotations done during this layout pass.
2500*b5893f02SDimitry Andric if (F->getFunction().optForMinSize() ||
2501*b5893f02SDimitry Andric (F->getFunction().optForSize() && !TLI->alignLoopsWithOptSize()))
2502dff0c46cSDimitry Andric return;
25033ca95b02SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()];
25047ae0e2c9SDimitry Andric if (FunctionChain.begin() == FunctionChain.end())
25057ae0e2c9SDimitry Andric return; // Empty chain.
2506dff0c46cSDimitry Andric
25077ae0e2c9SDimitry Andric const BranchProbability ColdProb(1, 5); // 20%
25083ca95b02SDimitry Andric BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
25097ae0e2c9SDimitry Andric BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
2510ff0cc061SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) {
2511ff0cc061SDimitry Andric if (ChainBB == *FunctionChain.begin())
2512ff0cc061SDimitry Andric continue;
2513ff0cc061SDimitry Andric
25147ae0e2c9SDimitry Andric // Don't align non-looping basic blocks. These are unlikely to execute
25157ae0e2c9SDimitry Andric // enough times to matter in practice. Note that we'll still handle
25167ae0e2c9SDimitry Andric // unnatural CFGs inside of a natural outer loop (the common case) and
25177ae0e2c9SDimitry Andric // rotated loops.
2518ff0cc061SDimitry Andric MachineLoop *L = MLI->getLoopFor(ChainBB);
25197ae0e2c9SDimitry Andric if (!L)
25207ae0e2c9SDimitry Andric continue;
25217ae0e2c9SDimitry Andric
252239d628a0SDimitry Andric unsigned Align = TLI->getPrefLoopAlignment(L);
252339d628a0SDimitry Andric if (!Align)
252439d628a0SDimitry Andric continue; // Don't care about loop alignment.
252539d628a0SDimitry Andric
25267ae0e2c9SDimitry Andric // If the block is cold relative to the function entry don't waste space
25277ae0e2c9SDimitry Andric // aligning it.
2528ff0cc061SDimitry Andric BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
25297ae0e2c9SDimitry Andric if (Freq < WeightedEntryFreq)
25307ae0e2c9SDimitry Andric continue;
25317ae0e2c9SDimitry Andric
25327ae0e2c9SDimitry Andric // If the block is cold relative to its loop header, don't align it
25337ae0e2c9SDimitry Andric // regardless of what edges into the block exist.
25347ae0e2c9SDimitry Andric MachineBasicBlock *LoopHeader = L->getHeader();
25357ae0e2c9SDimitry Andric BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
25367ae0e2c9SDimitry Andric if (Freq < (LoopHeaderFreq * ColdProb))
25377ae0e2c9SDimitry Andric continue;
25387ae0e2c9SDimitry Andric
25397ae0e2c9SDimitry Andric // Check for the existence of a non-layout predecessor which would benefit
25407ae0e2c9SDimitry Andric // from aligning this block.
2541ff0cc061SDimitry Andric MachineBasicBlock *LayoutPred =
2542ff0cc061SDimitry Andric &*std::prev(MachineFunction::iterator(ChainBB));
25437ae0e2c9SDimitry Andric
25447ae0e2c9SDimitry Andric // Force alignment if all the predecessors are jumps. We already checked
25457ae0e2c9SDimitry Andric // that the block isn't cold above.
2546ff0cc061SDimitry Andric if (!LayoutPred->isSuccessor(ChainBB)) {
2547ff0cc061SDimitry Andric ChainBB->setAlignment(Align);
25487ae0e2c9SDimitry Andric continue;
25497ae0e2c9SDimitry Andric }
25507ae0e2c9SDimitry Andric
25517ae0e2c9SDimitry Andric // Align this block if the layout predecessor's edge into this block is
2552139f7f9bSDimitry Andric // cold relative to the block. When this is true, other predecessors make up
25537ae0e2c9SDimitry Andric // all of the hot entries into the block and thus alignment is likely to be
25547ae0e2c9SDimitry Andric // important.
2555ff0cc061SDimitry Andric BranchProbability LayoutProb =
2556ff0cc061SDimitry Andric MBPI->getEdgeProbability(LayoutPred, ChainBB);
25577ae0e2c9SDimitry Andric BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
25587ae0e2c9SDimitry Andric if (LayoutEdgeFreq <= (Freq * ColdProb))
2559ff0cc061SDimitry Andric ChainBB->setAlignment(Align);
2560cb4dff85SDimitry Andric }
2561dff0c46cSDimitry Andric }
2562dff0c46cSDimitry Andric
2563d88c1a5aSDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2564d88c1a5aSDimitry Andric /// it was duplicated into its chain predecessor and removed.
2565d88c1a5aSDimitry Andric /// \p BB - Basic block that may be duplicated.
2566d88c1a5aSDimitry Andric ///
2567d88c1a5aSDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB.
2568d88c1a5aSDimitry Andric /// Updated to be the chain end if LPred is removed.
2569d88c1a5aSDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2570d88c1a5aSDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2571d88c1a5aSDimitry Andric /// Used to identify which blocks to update predecessor
2572d88c1a5aSDimitry Andric /// counts.
2573d88c1a5aSDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2574d88c1a5aSDimitry Andric /// chosen in the given order due to unnatural CFG
2575d88c1a5aSDimitry Andric /// only needed if \p BB is removed and
2576d88c1a5aSDimitry Andric /// \p PrevUnplacedBlockIt pointed to \p BB.
2577d88c1a5aSDimitry Andric /// @return true if \p BB was removed.
repeatedlyTailDuplicateBlock(MachineBasicBlock * BB,MachineBasicBlock * & LPred,const MachineBasicBlock * LoopHeaderBB,BlockChain & Chain,BlockFilterSet * BlockFilter,MachineFunction::iterator & PrevUnplacedBlockIt)2578d88c1a5aSDimitry Andric bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2579d88c1a5aSDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *&LPred,
25807a7e6055SDimitry Andric const MachineBasicBlock *LoopHeaderBB,
2581d88c1a5aSDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter,
2582d88c1a5aSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt) {
2583d88c1a5aSDimitry Andric bool Removed, DuplicatedToLPred;
2584d88c1a5aSDimitry Andric bool DuplicatedToOriginalLPred;
2585d88c1a5aSDimitry Andric Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2586d88c1a5aSDimitry Andric PrevUnplacedBlockIt,
2587d88c1a5aSDimitry Andric DuplicatedToLPred);
2588d88c1a5aSDimitry Andric if (!Removed)
2589d88c1a5aSDimitry Andric return false;
2590d88c1a5aSDimitry Andric DuplicatedToOriginalLPred = DuplicatedToLPred;
2591d88c1a5aSDimitry Andric // Iteratively try to duplicate again. It can happen that a block that is
2592d88c1a5aSDimitry Andric // duplicated into is still small enough to be duplicated again.
2593d88c1a5aSDimitry Andric // No need to call markBlockSuccessors in this case, as the blocks being
2594d88c1a5aSDimitry Andric // duplicated from here on are already scheduled.
2595d88c1a5aSDimitry Andric // Note that DuplicatedToLPred always implies Removed.
2596d88c1a5aSDimitry Andric while (DuplicatedToLPred) {
2597d88c1a5aSDimitry Andric assert(Removed && "Block must have been removed to be duplicated into its "
2598d88c1a5aSDimitry Andric "layout predecessor.");
2599d88c1a5aSDimitry Andric MachineBasicBlock *DupBB, *DupPred;
2600d88c1a5aSDimitry Andric // The removal callback causes Chain.end() to be updated when a block is
2601d88c1a5aSDimitry Andric // removed. On the first pass through the loop, the chain end should be the
2602d88c1a5aSDimitry Andric // same as it was on function entry. On subsequent passes, because we are
2603d88c1a5aSDimitry Andric // duplicating the block at the end of the chain, if it is removed the
2604d88c1a5aSDimitry Andric // chain will have shrunk by one block.
2605d88c1a5aSDimitry Andric BlockChain::iterator ChainEnd = Chain.end();
2606d88c1a5aSDimitry Andric DupBB = *(--ChainEnd);
2607d88c1a5aSDimitry Andric // Now try to duplicate again.
2608d88c1a5aSDimitry Andric if (ChainEnd == Chain.begin())
2609d88c1a5aSDimitry Andric break;
2610d88c1a5aSDimitry Andric DupPred = *std::prev(ChainEnd);
2611d88c1a5aSDimitry Andric Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2612d88c1a5aSDimitry Andric PrevUnplacedBlockIt,
2613d88c1a5aSDimitry Andric DuplicatedToLPred);
2614d88c1a5aSDimitry Andric }
2615d88c1a5aSDimitry Andric // If BB was duplicated into LPred, it is now scheduled. But because it was
2616d88c1a5aSDimitry Andric // removed, markChainSuccessors won't be called for its chain. Instead we
2617d88c1a5aSDimitry Andric // call markBlockSuccessors for LPred to achieve the same effect. This must go
2618d88c1a5aSDimitry Andric // at the end because repeating the tail duplication can increase the number
2619d88c1a5aSDimitry Andric // of unscheduled predecessors.
2620d88c1a5aSDimitry Andric LPred = *std::prev(Chain.end());
2621d88c1a5aSDimitry Andric if (DuplicatedToOriginalLPred)
2622d88c1a5aSDimitry Andric markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2623d88c1a5aSDimitry Andric return true;
2624d88c1a5aSDimitry Andric }
2625d88c1a5aSDimitry Andric
2626d88c1a5aSDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable.
2627d88c1a5aSDimitry Andric /// \p BB - Basic block that may be duplicated
2628d88c1a5aSDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB
2629d88c1a5aSDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2630d88c1a5aSDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2631d88c1a5aSDimitry Andric /// Used to identify which blocks to update predecessor
2632d88c1a5aSDimitry Andric /// counts.
2633d88c1a5aSDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2634d88c1a5aSDimitry Andric /// chosen in the given order due to unnatural CFG
2635d88c1a5aSDimitry Andric /// only needed if \p BB is removed and
2636d88c1a5aSDimitry Andric /// \p PrevUnplacedBlockIt pointed to \p BB.
2637d88c1a5aSDimitry Andric /// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
2638d88c1a5aSDimitry Andric /// only be true if the block was removed.
2639d88c1a5aSDimitry 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,bool & DuplicatedToLPred)2640d88c1a5aSDimitry Andric bool MachineBlockPlacement::maybeTailDuplicateBlock(
2641d88c1a5aSDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *LPred,
26427a7e6055SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter,
2643d88c1a5aSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt,
2644d88c1a5aSDimitry Andric bool &DuplicatedToLPred) {
2645d88c1a5aSDimitry Andric DuplicatedToLPred = false;
26467a7e6055SDimitry Andric if (!shouldTailDuplicate(BB))
26477a7e6055SDimitry Andric return false;
26487a7e6055SDimitry Andric
26494ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber()
26504ba319b5SDimitry Andric << "\n");
26517a7e6055SDimitry Andric
2652d88c1a5aSDimitry Andric // This has to be a callback because none of it can be done after
2653d88c1a5aSDimitry Andric // BB is deleted.
2654d88c1a5aSDimitry Andric bool Removed = false;
2655d88c1a5aSDimitry Andric auto RemovalCallback =
2656d88c1a5aSDimitry Andric [&](MachineBasicBlock *RemBB) {
2657d88c1a5aSDimitry Andric // Signal to outer function
2658d88c1a5aSDimitry Andric Removed = true;
2659d88c1a5aSDimitry Andric
2660d88c1a5aSDimitry Andric // Conservative default.
2661d88c1a5aSDimitry Andric bool InWorkList = true;
2662d88c1a5aSDimitry Andric // Remove from the Chain and Chain Map
2663d88c1a5aSDimitry Andric if (BlockToChain.count(RemBB)) {
2664d88c1a5aSDimitry Andric BlockChain *Chain = BlockToChain[RemBB];
2665d88c1a5aSDimitry Andric InWorkList = Chain->UnscheduledPredecessors == 0;
2666d88c1a5aSDimitry Andric Chain->remove(RemBB);
2667d88c1a5aSDimitry Andric BlockToChain.erase(RemBB);
2668d88c1a5aSDimitry Andric }
2669d88c1a5aSDimitry Andric
2670d88c1a5aSDimitry Andric // Handle the unplaced block iterator
2671d88c1a5aSDimitry Andric if (&(*PrevUnplacedBlockIt) == RemBB) {
2672d88c1a5aSDimitry Andric PrevUnplacedBlockIt++;
2673d88c1a5aSDimitry Andric }
2674d88c1a5aSDimitry Andric
2675d88c1a5aSDimitry Andric // Handle the Work Lists
2676d88c1a5aSDimitry Andric if (InWorkList) {
2677d88c1a5aSDimitry Andric SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
2678d88c1a5aSDimitry Andric if (RemBB->isEHPad())
2679d88c1a5aSDimitry Andric RemoveList = EHPadWorkList;
2680d88c1a5aSDimitry Andric RemoveList.erase(
26812cab237bSDimitry Andric llvm::remove_if(RemoveList,
26822cab237bSDimitry Andric [RemBB](MachineBasicBlock *BB) {
26832cab237bSDimitry Andric return BB == RemBB;
26842cab237bSDimitry Andric }),
2685d88c1a5aSDimitry Andric RemoveList.end());
2686d88c1a5aSDimitry Andric }
2687d88c1a5aSDimitry Andric
2688d88c1a5aSDimitry Andric // Handle the filter set
2689d88c1a5aSDimitry Andric if (BlockFilter) {
2690d88c1a5aSDimitry Andric BlockFilter->remove(RemBB);
2691d88c1a5aSDimitry Andric }
2692d88c1a5aSDimitry Andric
2693d88c1a5aSDimitry Andric // Remove the block from loop info.
2694d88c1a5aSDimitry Andric MLI->removeBlock(RemBB);
2695d88c1a5aSDimitry Andric if (RemBB == PreferredLoopExit)
2696d88c1a5aSDimitry Andric PreferredLoopExit = nullptr;
2697d88c1a5aSDimitry Andric
26984ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: "
2699d88c1a5aSDimitry Andric << getBlockName(RemBB) << "\n");
2700d88c1a5aSDimitry Andric };
2701d88c1a5aSDimitry Andric auto RemovalCallbackRef =
27022cab237bSDimitry Andric function_ref<void(MachineBasicBlock*)>(RemovalCallback);
2703d88c1a5aSDimitry Andric
2704d88c1a5aSDimitry Andric SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
27057a7e6055SDimitry Andric bool IsSimple = TailDup.isSimpleBB(BB);
2706d88c1a5aSDimitry Andric TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
2707d88c1a5aSDimitry Andric &DuplicatedPreds, &RemovalCallbackRef);
2708d88c1a5aSDimitry Andric
2709d88c1a5aSDimitry Andric // Update UnscheduledPredecessors to reflect tail-duplication.
2710d88c1a5aSDimitry Andric DuplicatedToLPred = false;
2711d88c1a5aSDimitry Andric for (MachineBasicBlock *Pred : DuplicatedPreds) {
2712d88c1a5aSDimitry Andric // We're only looking for unscheduled predecessors that match the filter.
2713d88c1a5aSDimitry Andric BlockChain* PredChain = BlockToChain[Pred];
2714d88c1a5aSDimitry Andric if (Pred == LPred)
2715d88c1a5aSDimitry Andric DuplicatedToLPred = true;
2716d88c1a5aSDimitry Andric if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
2717d88c1a5aSDimitry Andric || PredChain == &Chain)
2718d88c1a5aSDimitry Andric continue;
2719d88c1a5aSDimitry Andric for (MachineBasicBlock *NewSucc : Pred->successors()) {
2720d88c1a5aSDimitry Andric if (BlockFilter && !BlockFilter->count(NewSucc))
2721d88c1a5aSDimitry Andric continue;
2722d88c1a5aSDimitry Andric BlockChain *NewChain = BlockToChain[NewSucc];
2723d88c1a5aSDimitry Andric if (NewChain != &Chain && NewChain != PredChain)
2724d88c1a5aSDimitry Andric NewChain->UnscheduledPredecessors++;
2725d88c1a5aSDimitry Andric }
2726d88c1a5aSDimitry Andric }
2727d88c1a5aSDimitry Andric return Removed;
2728d88c1a5aSDimitry Andric }
2729d88c1a5aSDimitry Andric
runOnMachineFunction(MachineFunction & MF)27303ca95b02SDimitry Andric bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
27312cab237bSDimitry Andric if (skipFunction(MF.getFunction()))
27323ca95b02SDimitry Andric return false;
27333ca95b02SDimitry Andric
2734dff0c46cSDimitry Andric // Check for single-block functions and skip them.
27353ca95b02SDimitry Andric if (std::next(MF.begin()) == MF.end())
273691bc56edSDimitry Andric return false;
273791bc56edSDimitry Andric
27383ca95b02SDimitry Andric F = &MF;
2739dff0c46cSDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
27403ca95b02SDimitry Andric MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
27413ca95b02SDimitry Andric getAnalysis<MachineBlockFrequencyInfo>());
2742dff0c46cSDimitry Andric MLI = &getAnalysis<MachineLoopInfo>();
27433ca95b02SDimitry Andric TII = MF.getSubtarget().getInstrInfo();
27443ca95b02SDimitry Andric TLI = MF.getSubtarget().getTargetLowering();
27457a7e6055SDimitry Andric MPDT = nullptr;
2746d88c1a5aSDimitry Andric
2747d88c1a5aSDimitry Andric // Initialize PreferredLoopExit to nullptr here since it may never be set if
2748d88c1a5aSDimitry Andric // there are no MachineLoops.
2749d88c1a5aSDimitry Andric PreferredLoopExit = nullptr;
2750d88c1a5aSDimitry Andric
2751d8866befSDimitry Andric assert(BlockToChain.empty() &&
2752d8866befSDimitry Andric "BlockToChain map should be empty before starting placement.");
2753d8866befSDimitry Andric assert(ComputedEdges.empty() &&
2754d8866befSDimitry Andric "Computed Edge map should be empty before starting placement.");
27557a7e6055SDimitry Andric
27565517e702SDimitry Andric unsigned TailDupSize = TailDupPlacementThreshold;
27575517e702SDimitry Andric // If only the aggressive threshold is explicitly set, use it.
27585517e702SDimitry Andric if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
27595517e702SDimitry Andric TailDupPlacementThreshold.getNumOccurrences() == 0)
27605517e702SDimitry Andric TailDupSize = TailDupPlacementAggressiveThreshold;
27615517e702SDimitry Andric
27625517e702SDimitry Andric TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
27634ba319b5SDimitry Andric // For aggressive optimization, we can adjust some thresholds to be less
27645517e702SDimitry Andric // conservative.
27655517e702SDimitry Andric if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) {
27665517e702SDimitry Andric // At O3 we should be more willing to copy blocks for tail duplication. This
27675517e702SDimitry Andric // increases size pressure, so we only do it at O3
27685517e702SDimitry Andric // Do this unless only the regular threshold is explicitly set.
27695517e702SDimitry Andric if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
27705517e702SDimitry Andric TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
27715517e702SDimitry Andric TailDupSize = TailDupPlacementAggressiveThreshold;
27725517e702SDimitry Andric }
27735517e702SDimitry Andric
27746ccc06f6SDimitry Andric if (allowTailDupPlacement()) {
27757a7e6055SDimitry Andric MPDT = &getAnalysis<MachinePostDominatorTree>();
27762cab237bSDimitry Andric if (MF.getFunction().optForSize())
2777d88c1a5aSDimitry Andric TailDupSize = 1;
27782cab237bSDimitry Andric bool PreRegAlloc = false;
27792cab237bSDimitry Andric TailDup.initMF(MF, PreRegAlloc, MBPI, /* LayoutMode */ true, TailDupSize);
27807a7e6055SDimitry Andric precomputeTriangleChains();
2781d88c1a5aSDimitry Andric }
2782d88c1a5aSDimitry Andric
27833ca95b02SDimitry Andric buildCFGChains();
27843ca95b02SDimitry Andric
27853ca95b02SDimitry Andric // Changing the layout can create new tail merging opportunities.
27863ca95b02SDimitry Andric // TailMerge can create jump into if branches that make CFG irreducible for
27873ca95b02SDimitry Andric // HW that requires structured CFG.
27883ca95b02SDimitry Andric bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
27893ca95b02SDimitry Andric PassConfig->getEnableTailMerge() &&
27903ca95b02SDimitry Andric BranchFoldPlacement;
27913ca95b02SDimitry Andric // No tail merging opportunities if the block number is less than four.
27923ca95b02SDimitry Andric if (MF.size() > 3 && EnableTailMerge) {
27935517e702SDimitry Andric unsigned TailMergeSize = TailDupSize + 1;
27943ca95b02SDimitry Andric BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
2795d88c1a5aSDimitry Andric *MBPI, TailMergeSize);
27963ca95b02SDimitry Andric
27973ca95b02SDimitry Andric if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
27983ca95b02SDimitry Andric getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
27993ca95b02SDimitry Andric /*AfterBlockPlacement=*/true)) {
28003ca95b02SDimitry Andric // Redo the layout if tail merging creates/removes/moves blocks.
28013ca95b02SDimitry Andric BlockToChain.clear();
28027a7e6055SDimitry Andric ComputedEdges.clear();
28037a7e6055SDimitry Andric // Must redo the post-dominator tree if blocks were changed.
28047a7e6055SDimitry Andric if (MPDT)
28057a7e6055SDimitry Andric MPDT->runOnMachineFunction(MF);
28063ca95b02SDimitry Andric ChainAllocator.DestroyAll();
28073ca95b02SDimitry Andric buildCFGChains();
28083ca95b02SDimitry Andric }
28093ca95b02SDimitry Andric }
28103ca95b02SDimitry Andric
28113ca95b02SDimitry Andric optimizeBranches();
28123ca95b02SDimitry Andric alignBlocks();
2813dff0c46cSDimitry Andric
2814dff0c46cSDimitry Andric BlockToChain.clear();
28157a7e6055SDimitry Andric ComputedEdges.clear();
2816dff0c46cSDimitry Andric ChainAllocator.DestroyAll();
2817dff0c46cSDimitry Andric
2818284c1978SDimitry Andric if (AlignAllBlock)
2819284c1978SDimitry Andric // Align all of the blocks in the function to a specific alignment.
28203ca95b02SDimitry Andric for (MachineBasicBlock &MBB : MF)
2821ff0cc061SDimitry Andric MBB.setAlignment(AlignAllBlock);
28223ca95b02SDimitry Andric else if (AlignAllNonFallThruBlocks) {
28233ca95b02SDimitry Andric // Align all of the blocks that have no fall-through predecessors to a
28243ca95b02SDimitry Andric // specific alignment.
28253ca95b02SDimitry Andric for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
28263ca95b02SDimitry Andric auto LayoutPred = std::prev(MBI);
28273ca95b02SDimitry Andric if (!LayoutPred->isSuccessor(&*MBI))
28283ca95b02SDimitry Andric MBI->setAlignment(AlignAllNonFallThruBlocks);
28293ca95b02SDimitry Andric }
28303ca95b02SDimitry Andric }
28317a7e6055SDimitry Andric if (ViewBlockLayoutWithBFI != GVDT_None &&
28327a7e6055SDimitry Andric (ViewBlockFreqFuncName.empty() ||
28332cab237bSDimitry Andric F->getFunction().getName().equals(ViewBlockFreqFuncName))) {
28347a7e6055SDimitry Andric MBFI->view("MBP." + MF.getName(), false);
28357a7e6055SDimitry Andric }
28367a7e6055SDimitry Andric
2837284c1978SDimitry Andric
2838dff0c46cSDimitry Andric // We always return true as we have no way to track whether the final order
2839dff0c46cSDimitry Andric // differs from the original order.
2840dff0c46cSDimitry Andric return true;
2841dff0c46cSDimitry Andric }
2842dff0c46cSDimitry Andric
2843dff0c46cSDimitry Andric namespace {
28442cab237bSDimitry Andric
28454ba319b5SDimitry Andric /// A pass to compute block placement statistics.
2846dff0c46cSDimitry Andric ///
2847dff0c46cSDimitry Andric /// A separate pass to compute interesting statistics for evaluating block
2848dff0c46cSDimitry Andric /// placement. This is separate from the actual placement pass so that they can
28497ae0e2c9SDimitry Andric /// be computed in the absence of any placement transformations or when using
2850dff0c46cSDimitry Andric /// alternative placement strategies.
2851dff0c46cSDimitry Andric class MachineBlockPlacementStats : public MachineFunctionPass {
28524ba319b5SDimitry Andric /// A handle to the branch probability pass.
2853dff0c46cSDimitry Andric const MachineBranchProbabilityInfo *MBPI;
2854dff0c46cSDimitry Andric
28554ba319b5SDimitry Andric /// A handle to the function-wide block frequency pass.
2856dff0c46cSDimitry Andric const MachineBlockFrequencyInfo *MBFI;
2857dff0c46cSDimitry Andric
2858dff0c46cSDimitry Andric public:
2859dff0c46cSDimitry Andric static char ID; // Pass identification, replacement for typeid
28602cab237bSDimitry Andric
MachineBlockPlacementStats()2861dff0c46cSDimitry Andric MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2862dff0c46cSDimitry Andric initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2863dff0c46cSDimitry Andric }
2864dff0c46cSDimitry Andric
286591bc56edSDimitry Andric bool runOnMachineFunction(MachineFunction &F) override;
2866dff0c46cSDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const286791bc56edSDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
2868dff0c46cSDimitry Andric AU.addRequired<MachineBranchProbabilityInfo>();
2869dff0c46cSDimitry Andric AU.addRequired<MachineBlockFrequencyInfo>();
2870dff0c46cSDimitry Andric AU.setPreservesAll();
2871dff0c46cSDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
2872dff0c46cSDimitry Andric }
2873dff0c46cSDimitry Andric };
28742cab237bSDimitry Andric
28752cab237bSDimitry Andric } // end anonymous namespace
2876dff0c46cSDimitry Andric
2877dff0c46cSDimitry Andric char MachineBlockPlacementStats::ID = 0;
28782cab237bSDimitry Andric
2879dff0c46cSDimitry Andric char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
28802cab237bSDimitry Andric
2881dff0c46cSDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2882dff0c46cSDimitry Andric "Basic Block Placement Stats", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)2883dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2884dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2885dff0c46cSDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2886dff0c46cSDimitry Andric "Basic Block Placement Stats", false, false)
2887dff0c46cSDimitry Andric
2888dff0c46cSDimitry Andric bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2889dff0c46cSDimitry Andric // Check for single-block functions and skip them.
289091bc56edSDimitry Andric if (std::next(F.begin()) == F.end())
2891dff0c46cSDimitry Andric return false;
2892dff0c46cSDimitry Andric
2893dff0c46cSDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2894dff0c46cSDimitry Andric MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2895dff0c46cSDimitry Andric
2896ff0cc061SDimitry Andric for (MachineBasicBlock &MBB : F) {
2897ff0cc061SDimitry Andric BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
2898ff0cc061SDimitry Andric Statistic &NumBranches =
2899ff0cc061SDimitry Andric (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
2900ff0cc061SDimitry Andric Statistic &BranchTakenFreq =
2901ff0cc061SDimitry Andric (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2902ff0cc061SDimitry Andric for (MachineBasicBlock *Succ : MBB.successors()) {
2903dff0c46cSDimitry Andric // Skip if this successor is a fallthrough.
2904ff0cc061SDimitry Andric if (MBB.isLayoutSuccessor(Succ))
2905dff0c46cSDimitry Andric continue;
2906dff0c46cSDimitry Andric
2907ff0cc061SDimitry Andric BlockFrequency EdgeFreq =
2908ff0cc061SDimitry Andric BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
2909dff0c46cSDimitry Andric ++NumBranches;
2910dff0c46cSDimitry Andric BranchTakenFreq += EdgeFreq.getFrequency();
2911dff0c46cSDimitry Andric }
2912dff0c46cSDimitry Andric }
2913dff0c46cSDimitry Andric
2914dff0c46cSDimitry Andric return false;
2915dff0c46cSDimitry Andric }
2916