10b57cec5SDimitry Andric //===- HotColdSplitting.cpp -- Outline Cold Regions -------------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric ///
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// The goal of hot/cold splitting is to improve the memory locality of code.
110b57cec5SDimitry Andric /// The splitting pass does this by identifying cold blocks and moving them into
120b57cec5SDimitry Andric /// separate functions.
130b57cec5SDimitry Andric ///
140b57cec5SDimitry Andric /// When the splitting pass finds a cold block (referred to as "the sink"), it
150b57cec5SDimitry Andric /// grows a maximal cold region around that block. The maximal region contains
160b57cec5SDimitry Andric /// all blocks (post-)dominated by the sink [*]. In theory, these blocks are as
170b57cec5SDimitry Andric /// cold as the sink. Once a region is found, it's split out of the original
180b57cec5SDimitry Andric /// function provided it's profitable to do so.
190b57cec5SDimitry Andric ///
200b57cec5SDimitry Andric /// [*] In practice, there is some added complexity because some blocks are not
210b57cec5SDimitry Andric /// safe to extract.
220b57cec5SDimitry Andric ///
230b57cec5SDimitry Andric /// TODO: Use the PM to get domtrees, and preserve BFI/BPI.
240b57cec5SDimitry Andric /// TODO: Reorder outlined functions.
250b57cec5SDimitry Andric ///
260b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
270b57cec5SDimitry Andric
28480093f4SDimitry Andric #include "llvm/Transforms/IPO/HotColdSplitting.h"
290b57cec5SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
300b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
310b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
3281ad6265SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
330b57cec5SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
340b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
350b57cec5SDimitry Andric #include "llvm/Analysis/PostDominators.h"
360b57cec5SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
370b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
380b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
390b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
400b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
410b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
42*0fca6ea1SDimitry Andric #include "llvm/IR/EHPersonalities.h"
430b57cec5SDimitry Andric #include "llvm/IR/Function.h"
440b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
450b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
460b57cec5SDimitry Andric #include "llvm/IR/Module.h"
470b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
485f757f3fSDimitry Andric #include "llvm/IR/ProfDataUtils.h"
490b57cec5SDimitry Andric #include "llvm/IR/User.h"
500b57cec5SDimitry Andric #include "llvm/IR/Value.h"
51480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
520b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
530b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
540b57cec5SDimitry Andric #include "llvm/Transforms/IPO.h"
550b57cec5SDimitry Andric #include "llvm/Transforms/Utils/CodeExtractor.h"
560b57cec5SDimitry Andric #include <algorithm>
570b57cec5SDimitry Andric #include <cassert>
5881ad6265SDimitry Andric #include <limits>
59e8d8bef9SDimitry Andric #include <string>
600b57cec5SDimitry Andric
610b57cec5SDimitry Andric #define DEBUG_TYPE "hotcoldsplit"
620b57cec5SDimitry Andric
630b57cec5SDimitry Andric STATISTIC(NumColdRegionsFound, "Number of cold regions found.");
640b57cec5SDimitry Andric STATISTIC(NumColdRegionsOutlined, "Number of cold regions outlined.");
650b57cec5SDimitry Andric
660b57cec5SDimitry Andric using namespace llvm;
670b57cec5SDimitry Andric
68e8d8bef9SDimitry Andric static cl::opt<bool> EnableStaticAnalysis("hot-cold-static-analysis",
690b57cec5SDimitry Andric cl::init(true), cl::Hidden);
700b57cec5SDimitry Andric
710b57cec5SDimitry Andric static cl::opt<int>
720b57cec5SDimitry Andric SplittingThreshold("hotcoldsplit-threshold", cl::init(2), cl::Hidden,
730b57cec5SDimitry Andric cl::desc("Base penalty for splitting cold code (as a "
740b57cec5SDimitry Andric "multiple of TCC_Basic)"));
750b57cec5SDimitry Andric
76e8d8bef9SDimitry Andric static cl::opt<bool> EnableColdSection(
77e8d8bef9SDimitry Andric "enable-cold-section", cl::init(false), cl::Hidden,
78e8d8bef9SDimitry Andric cl::desc("Enable placement of extracted cold functions"
79e8d8bef9SDimitry Andric " into a separate section after hot-cold splitting."));
80e8d8bef9SDimitry Andric
81e8d8bef9SDimitry Andric static cl::opt<std::string>
82e8d8bef9SDimitry Andric ColdSectionName("hotcoldsplit-cold-section-name", cl::init("__llvm_cold"),
83e8d8bef9SDimitry Andric cl::Hidden,
84e8d8bef9SDimitry Andric cl::desc("Name for the section containing cold functions "
85e8d8bef9SDimitry Andric "extracted by hot-cold splitting."));
86e8d8bef9SDimitry Andric
87e8d8bef9SDimitry Andric static cl::opt<int> MaxParametersForSplit(
88e8d8bef9SDimitry Andric "hotcoldsplit-max-params", cl::init(4), cl::Hidden,
89e8d8bef9SDimitry Andric cl::desc("Maximum number of parameters for a split function"));
90e8d8bef9SDimitry Andric
915f757f3fSDimitry Andric static cl::opt<int> ColdBranchProbDenom(
925f757f3fSDimitry Andric "hotcoldsplit-cold-probability-denom", cl::init(100), cl::Hidden,
935f757f3fSDimitry Andric cl::desc("Divisor of cold branch probability."
945f757f3fSDimitry Andric "BranchProbability = 1/ColdBranchProbDenom"));
955f757f3fSDimitry Andric
960b57cec5SDimitry Andric namespace {
970b57cec5SDimitry Andric // Same as blockEndsInUnreachable in CodeGen/BranchFolding.cpp. Do not modify
980b57cec5SDimitry Andric // this function unless you modify the MBB version as well.
990b57cec5SDimitry Andric //
1000b57cec5SDimitry Andric /// A no successor, non-return block probably ends in unreachable and is cold.
1010b57cec5SDimitry Andric /// Also consider a block that ends in an indirect branch to be a return block,
1020b57cec5SDimitry Andric /// since many targets use plain indirect branches to return.
blockEndsInUnreachable(const BasicBlock & BB)1030b57cec5SDimitry Andric bool blockEndsInUnreachable(const BasicBlock &BB) {
1040b57cec5SDimitry Andric if (!succ_empty(&BB))
1050b57cec5SDimitry Andric return false;
1060b57cec5SDimitry Andric if (BB.empty())
1070b57cec5SDimitry Andric return true;
1080b57cec5SDimitry Andric const Instruction *I = BB.getTerminator();
1090b57cec5SDimitry Andric return !(isa<ReturnInst>(I) || isa<IndirectBrInst>(I));
1100b57cec5SDimitry Andric }
1110b57cec5SDimitry Andric
analyzeProfMetadata(BasicBlock * BB,BranchProbability ColdProbThresh,SmallPtrSetImpl<BasicBlock * > & AnnotatedColdBlocks)1125f757f3fSDimitry Andric void analyzeProfMetadata(BasicBlock *BB,
1135f757f3fSDimitry Andric BranchProbability ColdProbThresh,
1145f757f3fSDimitry Andric SmallPtrSetImpl<BasicBlock *> &AnnotatedColdBlocks) {
1155f757f3fSDimitry Andric // TODO: Handle branches with > 2 successors.
1165f757f3fSDimitry Andric BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
1175f757f3fSDimitry Andric if (!CondBr)
1185f757f3fSDimitry Andric return;
1195f757f3fSDimitry Andric
1205f757f3fSDimitry Andric uint64_t TrueWt, FalseWt;
1215f757f3fSDimitry Andric if (!extractBranchWeights(*CondBr, TrueWt, FalseWt))
1225f757f3fSDimitry Andric return;
1235f757f3fSDimitry Andric
1245f757f3fSDimitry Andric auto SumWt = TrueWt + FalseWt;
1255f757f3fSDimitry Andric if (SumWt == 0)
1265f757f3fSDimitry Andric return;
1275f757f3fSDimitry Andric
1285f757f3fSDimitry Andric auto TrueProb = BranchProbability::getBranchProbability(TrueWt, SumWt);
1295f757f3fSDimitry Andric auto FalseProb = BranchProbability::getBranchProbability(FalseWt, SumWt);
1305f757f3fSDimitry Andric
1315f757f3fSDimitry Andric if (TrueProb <= ColdProbThresh)
1325f757f3fSDimitry Andric AnnotatedColdBlocks.insert(CondBr->getSuccessor(0));
1335f757f3fSDimitry Andric
1345f757f3fSDimitry Andric if (FalseProb <= ColdProbThresh)
1355f757f3fSDimitry Andric AnnotatedColdBlocks.insert(CondBr->getSuccessor(1));
1365f757f3fSDimitry Andric }
1375f757f3fSDimitry Andric
unlikelyExecuted(BasicBlock & BB)1380b57cec5SDimitry Andric bool unlikelyExecuted(BasicBlock &BB) {
1390b57cec5SDimitry Andric // Exception handling blocks are unlikely executed.
1400b57cec5SDimitry Andric if (BB.isEHPad() || isa<ResumeInst>(BB.getTerminator()))
1410b57cec5SDimitry Andric return true;
1420b57cec5SDimitry Andric
1430b57cec5SDimitry Andric // The block is cold if it calls/invokes a cold function. However, do not
1440b57cec5SDimitry Andric // mark sanitizer traps as cold.
1450b57cec5SDimitry Andric for (Instruction &I : BB)
1465ffd83dbSDimitry Andric if (auto *CB = dyn_cast<CallBase>(&I))
14781ad6265SDimitry Andric if (CB->hasFnAttr(Attribute::Cold) &&
14881ad6265SDimitry Andric !CB->getMetadata(LLVMContext::MD_nosanitize))
1490b57cec5SDimitry Andric return true;
1500b57cec5SDimitry Andric
1510b57cec5SDimitry Andric // The block is cold if it has an unreachable terminator, unless it's
1520b57cec5SDimitry Andric // preceded by a call to a (possibly warm) noreturn call (e.g. longjmp).
1530b57cec5SDimitry Andric if (blockEndsInUnreachable(BB)) {
1540b57cec5SDimitry Andric if (auto *CI =
1550b57cec5SDimitry Andric dyn_cast_or_null<CallInst>(BB.getTerminator()->getPrevNode()))
1560b57cec5SDimitry Andric if (CI->hasFnAttr(Attribute::NoReturn))
1570b57cec5SDimitry Andric return false;
1580b57cec5SDimitry Andric return true;
1590b57cec5SDimitry Andric }
1600b57cec5SDimitry Andric
1610b57cec5SDimitry Andric return false;
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric
1640b57cec5SDimitry Andric /// Check whether it's safe to outline \p BB.
mayExtractBlock(const BasicBlock & BB)1650b57cec5SDimitry Andric static bool mayExtractBlock(const BasicBlock &BB) {
1660b57cec5SDimitry Andric // EH pads are unsafe to outline because doing so breaks EH type tables. It
1670b57cec5SDimitry Andric // follows that invoke instructions cannot be extracted, because CodeExtractor
1680b57cec5SDimitry Andric // requires unwind destinations to be within the extraction region.
1690b57cec5SDimitry Andric //
1700b57cec5SDimitry Andric // Resumes that are not reachable from a cleanup landing pad are considered to
1710b57cec5SDimitry Andric // be unreachable. It’s not safe to split them out either.
172*0fca6ea1SDimitry Andric
173fe6060f1SDimitry Andric if (BB.hasAddressTaken() || BB.isEHPad())
174fe6060f1SDimitry Andric return false;
1750b57cec5SDimitry Andric auto Term = BB.getTerminator();
176*0fca6ea1SDimitry Andric if (isa<InvokeInst>(Term) || isa<ResumeInst>(Term))
177*0fca6ea1SDimitry Andric return false;
178*0fca6ea1SDimitry Andric
179*0fca6ea1SDimitry Andric // Do not outline basic blocks that have token type instructions. e.g.,
180*0fca6ea1SDimitry Andric // exception:
181*0fca6ea1SDimitry Andric // %0 = cleanuppad within none []
182*0fca6ea1SDimitry Andric // call void @"?terminate@@YAXXZ"() [ "funclet"(token %0) ]
183*0fca6ea1SDimitry Andric // br label %continue-exception
184*0fca6ea1SDimitry Andric if (llvm::any_of(
185*0fca6ea1SDimitry Andric BB, [](const Instruction &I) { return I.getType()->isTokenTy(); })) {
186*0fca6ea1SDimitry Andric return false;
187*0fca6ea1SDimitry Andric }
188*0fca6ea1SDimitry Andric
189*0fca6ea1SDimitry Andric return true;
1900b57cec5SDimitry Andric }
1910b57cec5SDimitry Andric
1920b57cec5SDimitry Andric /// Mark \p F cold. Based on this assumption, also optimize it for minimum size.
1930b57cec5SDimitry Andric /// If \p UpdateEntryCount is true (set when this is a new split function and
1940b57cec5SDimitry Andric /// module has profile data), set entry count to 0 to ensure treated as cold.
1950b57cec5SDimitry Andric /// Return true if the function is changed.
markFunctionCold(Function & F,bool UpdateEntryCount=false)1960b57cec5SDimitry Andric static bool markFunctionCold(Function &F, bool UpdateEntryCount = false) {
1970b57cec5SDimitry Andric assert(!F.hasOptNone() && "Can't mark this cold");
1980b57cec5SDimitry Andric bool Changed = false;
1990b57cec5SDimitry Andric if (!F.hasFnAttribute(Attribute::Cold)) {
2000b57cec5SDimitry Andric F.addFnAttr(Attribute::Cold);
2010b57cec5SDimitry Andric Changed = true;
2020b57cec5SDimitry Andric }
2030b57cec5SDimitry Andric if (!F.hasFnAttribute(Attribute::MinSize)) {
2040b57cec5SDimitry Andric F.addFnAttr(Attribute::MinSize);
2050b57cec5SDimitry Andric Changed = true;
2060b57cec5SDimitry Andric }
2070b57cec5SDimitry Andric if (UpdateEntryCount) {
2080b57cec5SDimitry Andric // Set the entry count to 0 to ensure it is placed in the unlikely text
2090b57cec5SDimitry Andric // section when function sections are enabled.
2100b57cec5SDimitry Andric F.setEntryCount(0);
2110b57cec5SDimitry Andric Changed = true;
2120b57cec5SDimitry Andric }
2130b57cec5SDimitry Andric
2140b57cec5SDimitry Andric return Changed;
2150b57cec5SDimitry Andric }
2160b57cec5SDimitry Andric
2170b57cec5SDimitry Andric } // end anonymous namespace
2180b57cec5SDimitry Andric
2190b57cec5SDimitry Andric /// Check whether \p F is inherently cold.
isFunctionCold(const Function & F) const2200b57cec5SDimitry Andric bool HotColdSplitting::isFunctionCold(const Function &F) const {
2210b57cec5SDimitry Andric if (F.hasFnAttribute(Attribute::Cold))
2220b57cec5SDimitry Andric return true;
2230b57cec5SDimitry Andric
2240b57cec5SDimitry Andric if (F.getCallingConv() == CallingConv::Cold)
2250b57cec5SDimitry Andric return true;
2260b57cec5SDimitry Andric
2270b57cec5SDimitry Andric if (PSI->isFunctionEntryCold(&F))
2280b57cec5SDimitry Andric return true;
2290b57cec5SDimitry Andric
2300b57cec5SDimitry Andric return false;
2310b57cec5SDimitry Andric }
2320b57cec5SDimitry Andric
isBasicBlockCold(BasicBlock * BB,BranchProbability ColdProbThresh,SmallPtrSetImpl<BasicBlock * > & AnnotatedColdBlocks,BlockFrequencyInfo * BFI) const233*0fca6ea1SDimitry Andric bool HotColdSplitting::isBasicBlockCold(
234*0fca6ea1SDimitry Andric BasicBlock *BB, BranchProbability ColdProbThresh,
2355f757f3fSDimitry Andric SmallPtrSetImpl<BasicBlock *> &AnnotatedColdBlocks,
2365f757f3fSDimitry Andric BlockFrequencyInfo *BFI) const {
2375f757f3fSDimitry Andric if (BFI) {
2385f757f3fSDimitry Andric if (PSI->isColdBlock(BB, BFI))
2395f757f3fSDimitry Andric return true;
2405f757f3fSDimitry Andric } else {
2415f757f3fSDimitry Andric // Find cold blocks of successors of BB during a reverse postorder traversal.
2425f757f3fSDimitry Andric analyzeProfMetadata(BB, ColdProbThresh, AnnotatedColdBlocks);
2435f757f3fSDimitry Andric
2445f757f3fSDimitry Andric // A statically cold BB would be known before it is visited
2455f757f3fSDimitry Andric // because the prof-data of incoming edges are 'analyzed' as part of RPOT.
2465f757f3fSDimitry Andric if (AnnotatedColdBlocks.count(BB))
2475f757f3fSDimitry Andric return true;
2485f757f3fSDimitry Andric }
2495f757f3fSDimitry Andric
2505f757f3fSDimitry Andric if (EnableStaticAnalysis && unlikelyExecuted(*BB))
2515f757f3fSDimitry Andric return true;
2525f757f3fSDimitry Andric
2535f757f3fSDimitry Andric return false;
2545f757f3fSDimitry Andric }
2555f757f3fSDimitry Andric
2560b57cec5SDimitry Andric // Returns false if the function should not be considered for hot-cold split
2570b57cec5SDimitry Andric // optimization.
shouldOutlineFrom(const Function & F) const2580b57cec5SDimitry Andric bool HotColdSplitting::shouldOutlineFrom(const Function &F) const {
2590b57cec5SDimitry Andric if (F.hasFnAttribute(Attribute::AlwaysInline))
2600b57cec5SDimitry Andric return false;
2610b57cec5SDimitry Andric
2620b57cec5SDimitry Andric if (F.hasFnAttribute(Attribute::NoInline))
2630b57cec5SDimitry Andric return false;
2640b57cec5SDimitry Andric
265480093f4SDimitry Andric // A function marked `noreturn` may contain unreachable terminators: these
266480093f4SDimitry Andric // should not be considered cold, as the function may be a trampoline.
267480093f4SDimitry Andric if (F.hasFnAttribute(Attribute::NoReturn))
268480093f4SDimitry Andric return false;
269480093f4SDimitry Andric
2700b57cec5SDimitry Andric if (F.hasFnAttribute(Attribute::SanitizeAddress) ||
2710b57cec5SDimitry Andric F.hasFnAttribute(Attribute::SanitizeHWAddress) ||
2720b57cec5SDimitry Andric F.hasFnAttribute(Attribute::SanitizeThread) ||
2730b57cec5SDimitry Andric F.hasFnAttribute(Attribute::SanitizeMemory))
2740b57cec5SDimitry Andric return false;
2750b57cec5SDimitry Andric
276*0fca6ea1SDimitry Andric // Do not outline scoped EH personality functions.
277*0fca6ea1SDimitry Andric if (F.hasPersonalityFn())
278*0fca6ea1SDimitry Andric if (isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
279*0fca6ea1SDimitry Andric return false;
280*0fca6ea1SDimitry Andric
2810b57cec5SDimitry Andric return true;
2820b57cec5SDimitry Andric }
2830b57cec5SDimitry Andric
2840b57cec5SDimitry Andric /// Get the benefit score of outlining \p Region.
getOutliningBenefit(ArrayRef<BasicBlock * > Region,TargetTransformInfo & TTI)285e8d8bef9SDimitry Andric static InstructionCost getOutliningBenefit(ArrayRef<BasicBlock *> Region,
2860b57cec5SDimitry Andric TargetTransformInfo &TTI) {
2870b57cec5SDimitry Andric // Sum up the code size costs of non-terminator instructions. Tight coupling
2880b57cec5SDimitry Andric // with \ref getOutliningPenalty is needed to model the costs of terminators.
289e8d8bef9SDimitry Andric InstructionCost Benefit = 0;
2900b57cec5SDimitry Andric for (BasicBlock *BB : Region)
2910b57cec5SDimitry Andric for (Instruction &I : BB->instructionsWithoutDebug())
2920b57cec5SDimitry Andric if (&I != BB->getTerminator())
2930b57cec5SDimitry Andric Benefit +=
2940b57cec5SDimitry Andric TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
2950b57cec5SDimitry Andric
2960b57cec5SDimitry Andric return Benefit;
2970b57cec5SDimitry Andric }
2980b57cec5SDimitry Andric
2990b57cec5SDimitry Andric /// Get the penalty score for outlining \p Region.
getOutliningPenalty(ArrayRef<BasicBlock * > Region,unsigned NumInputs,unsigned NumOutputs)3000b57cec5SDimitry Andric static int getOutliningPenalty(ArrayRef<BasicBlock *> Region,
3010b57cec5SDimitry Andric unsigned NumInputs, unsigned NumOutputs) {
3020b57cec5SDimitry Andric int Penalty = SplittingThreshold;
3030b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Applying penalty for splitting: " << Penalty << "\n");
3040b57cec5SDimitry Andric
3050b57cec5SDimitry Andric // If the splitting threshold is set at or below zero, skip the usual
3060b57cec5SDimitry Andric // profitability check.
3070b57cec5SDimitry Andric if (SplittingThreshold <= 0)
3080b57cec5SDimitry Andric return Penalty;
3090b57cec5SDimitry Andric
3100b57cec5SDimitry Andric // Find the number of distinct exit blocks for the region. Use a conservative
3110b57cec5SDimitry Andric // check to determine whether control returns from the region.
3120b57cec5SDimitry Andric bool NoBlocksReturn = true;
3130b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 2> SuccsOutsideRegion;
3140b57cec5SDimitry Andric for (BasicBlock *BB : Region) {
3150b57cec5SDimitry Andric // If a block has no successors, only assume it does not return if it's
3160b57cec5SDimitry Andric // unreachable.
3170b57cec5SDimitry Andric if (succ_empty(BB)) {
3180b57cec5SDimitry Andric NoBlocksReturn &= isa<UnreachableInst>(BB->getTerminator());
3190b57cec5SDimitry Andric continue;
3200b57cec5SDimitry Andric }
3210b57cec5SDimitry Andric
3220b57cec5SDimitry Andric for (BasicBlock *SuccBB : successors(BB)) {
323e8d8bef9SDimitry Andric if (!is_contained(Region, SuccBB)) {
3240b57cec5SDimitry Andric NoBlocksReturn = false;
3250b57cec5SDimitry Andric SuccsOutsideRegion.insert(SuccBB);
3260b57cec5SDimitry Andric }
3270b57cec5SDimitry Andric }
3280b57cec5SDimitry Andric }
3290b57cec5SDimitry Andric
330e8d8bef9SDimitry Andric // Count the number of phis in exit blocks with >= 2 incoming values from the
331e8d8bef9SDimitry Andric // outlining region. These phis are split (\ref severSplitPHINodesOfExits),
332e8d8bef9SDimitry Andric // and new outputs are created to supply the split phis. CodeExtractor can't
333e8d8bef9SDimitry Andric // report these new outputs until extraction begins, but it's important to
334e8d8bef9SDimitry Andric // factor the cost of the outputs into the cost calculation.
335e8d8bef9SDimitry Andric unsigned NumSplitExitPhis = 0;
336e8d8bef9SDimitry Andric for (BasicBlock *ExitBB : SuccsOutsideRegion) {
337e8d8bef9SDimitry Andric for (PHINode &PN : ExitBB->phis()) {
338e8d8bef9SDimitry Andric // Find all incoming values from the outlining region.
339e8d8bef9SDimitry Andric int NumIncomingVals = 0;
340e8d8bef9SDimitry Andric for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
3410eae32dcSDimitry Andric if (llvm::is_contained(Region, PN.getIncomingBlock(i))) {
342e8d8bef9SDimitry Andric ++NumIncomingVals;
343e8d8bef9SDimitry Andric if (NumIncomingVals > 1) {
344e8d8bef9SDimitry Andric ++NumSplitExitPhis;
345e8d8bef9SDimitry Andric break;
346e8d8bef9SDimitry Andric }
347e8d8bef9SDimitry Andric }
348e8d8bef9SDimitry Andric }
349e8d8bef9SDimitry Andric }
350e8d8bef9SDimitry Andric
351e8d8bef9SDimitry Andric // Apply a penalty for calling the split function. Factor in the cost of
352e8d8bef9SDimitry Andric // materializing all of the parameters.
353e8d8bef9SDimitry Andric int NumOutputsAndSplitPhis = NumOutputs + NumSplitExitPhis;
354e8d8bef9SDimitry Andric int NumParams = NumInputs + NumOutputsAndSplitPhis;
355e8d8bef9SDimitry Andric if (NumParams > MaxParametersForSplit) {
356e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << NumInputs << " inputs and " << NumOutputsAndSplitPhis
357e8d8bef9SDimitry Andric << " outputs exceeds parameter limit ("
358e8d8bef9SDimitry Andric << MaxParametersForSplit << ")\n");
359e8d8bef9SDimitry Andric return std::numeric_limits<int>::max();
360e8d8bef9SDimitry Andric }
361e8d8bef9SDimitry Andric const int CostForArgMaterialization = 2 * TargetTransformInfo::TCC_Basic;
362e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Applying penalty for: " << NumParams << " params\n");
363e8d8bef9SDimitry Andric Penalty += CostForArgMaterialization * NumParams;
364e8d8bef9SDimitry Andric
365e8d8bef9SDimitry Andric // Apply the typical code size cost for an output alloca and its associated
366e8d8bef9SDimitry Andric // reload in the caller. Also penalize the associated store in the callee.
367e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Applying penalty for: " << NumOutputsAndSplitPhis
368e8d8bef9SDimitry Andric << " outputs/split phis\n");
369e8d8bef9SDimitry Andric const int CostForRegionOutput = 3 * TargetTransformInfo::TCC_Basic;
370e8d8bef9SDimitry Andric Penalty += CostForRegionOutput * NumOutputsAndSplitPhis;
371e8d8bef9SDimitry Andric
3720b57cec5SDimitry Andric // Apply a `noreturn` bonus.
3730b57cec5SDimitry Andric if (NoBlocksReturn) {
3740b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Applying bonus for: " << Region.size()
3750b57cec5SDimitry Andric << " non-returning terminators\n");
3760b57cec5SDimitry Andric Penalty -= Region.size();
3770b57cec5SDimitry Andric }
3780b57cec5SDimitry Andric
3790b57cec5SDimitry Andric // Apply a penalty for having more than one successor outside of the region.
3800b57cec5SDimitry Andric // This penalty accounts for the switch needed in the caller.
381e8d8bef9SDimitry Andric if (SuccsOutsideRegion.size() > 1) {
3820b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Applying penalty for: " << SuccsOutsideRegion.size()
3830b57cec5SDimitry Andric << " non-region successors\n");
3840b57cec5SDimitry Andric Penalty += (SuccsOutsideRegion.size() - 1) * TargetTransformInfo::TCC_Basic;
3850b57cec5SDimitry Andric }
3860b57cec5SDimitry Andric
3870b57cec5SDimitry Andric return Penalty;
3880b57cec5SDimitry Andric }
3890b57cec5SDimitry Andric
390*0fca6ea1SDimitry Andric // Determine if it is beneficial to split the \p Region.
isSplittingBeneficial(CodeExtractor & CE,const BlockSequence & Region,TargetTransformInfo & TTI)391*0fca6ea1SDimitry Andric bool HotColdSplitting::isSplittingBeneficial(CodeExtractor &CE,
392*0fca6ea1SDimitry Andric const BlockSequence &Region,
393*0fca6ea1SDimitry Andric TargetTransformInfo &TTI) {
3940b57cec5SDimitry Andric assert(!Region.empty());
3950b57cec5SDimitry Andric
3960b57cec5SDimitry Andric // Perform a simple cost/benefit analysis to decide whether or not to permit
3970b57cec5SDimitry Andric // splitting.
3980b57cec5SDimitry Andric SetVector<Value *> Inputs, Outputs, Sinks;
3990b57cec5SDimitry Andric CE.findInputsOutputs(Inputs, Outputs, Sinks);
400e8d8bef9SDimitry Andric InstructionCost OutliningBenefit = getOutliningBenefit(Region, TTI);
4010b57cec5SDimitry Andric int OutliningPenalty =
4020b57cec5SDimitry Andric getOutliningPenalty(Region, Inputs.size(), Outputs.size());
4030b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Split profitability: benefit = " << OutliningBenefit
4040b57cec5SDimitry Andric << ", penalty = " << OutliningPenalty << "\n");
405e8d8bef9SDimitry Andric if (!OutliningBenefit.isValid() || OutliningBenefit <= OutliningPenalty)
406*0fca6ea1SDimitry Andric return false;
4070b57cec5SDimitry Andric
408*0fca6ea1SDimitry Andric return true;
409*0fca6ea1SDimitry Andric }
410*0fca6ea1SDimitry Andric
411*0fca6ea1SDimitry Andric // Split the single \p EntryPoint cold region. \p CE is the region code
412*0fca6ea1SDimitry Andric // extractor.
extractColdRegion(BasicBlock & EntryPoint,CodeExtractor & CE,const CodeExtractorAnalysisCache & CEAC,BlockFrequencyInfo * BFI,TargetTransformInfo & TTI,OptimizationRemarkEmitter & ORE)413*0fca6ea1SDimitry Andric Function *HotColdSplitting::extractColdRegion(
414*0fca6ea1SDimitry Andric BasicBlock &EntryPoint, CodeExtractor &CE,
415*0fca6ea1SDimitry Andric const CodeExtractorAnalysisCache &CEAC, BlockFrequencyInfo *BFI,
416*0fca6ea1SDimitry Andric TargetTransformInfo &TTI, OptimizationRemarkEmitter &ORE) {
417*0fca6ea1SDimitry Andric Function *OrigF = EntryPoint.getParent();
4188bcb0991SDimitry Andric if (Function *OutF = CE.extractCodeRegion(CEAC)) {
4190b57cec5SDimitry Andric User *U = *OutF->user_begin();
4200b57cec5SDimitry Andric CallInst *CI = cast<CallInst>(U);
4210b57cec5SDimitry Andric NumColdRegionsOutlined++;
4220b57cec5SDimitry Andric if (TTI.useColdCCForColdCall(*OutF)) {
4230b57cec5SDimitry Andric OutF->setCallingConv(CallingConv::Cold);
4245ffd83dbSDimitry Andric CI->setCallingConv(CallingConv::Cold);
4250b57cec5SDimitry Andric }
4260b57cec5SDimitry Andric CI->setIsNoInline();
4270b57cec5SDimitry Andric
428e8d8bef9SDimitry Andric if (EnableColdSection)
429e8d8bef9SDimitry Andric OutF->setSection(ColdSectionName);
430e8d8bef9SDimitry Andric else {
431480093f4SDimitry Andric if (OrigF->hasSection())
432480093f4SDimitry Andric OutF->setSection(OrigF->getSection());
433e8d8bef9SDimitry Andric }
434480093f4SDimitry Andric
4350b57cec5SDimitry Andric markFunctionCold(*OutF, BFI != nullptr);
4360b57cec5SDimitry Andric
4370b57cec5SDimitry Andric LLVM_DEBUG(llvm::dbgs() << "Outlined Region: " << *OutF);
4380b57cec5SDimitry Andric ORE.emit([&]() {
4390b57cec5SDimitry Andric return OptimizationRemark(DEBUG_TYPE, "HotColdSplit",
440*0fca6ea1SDimitry Andric &*EntryPoint.begin())
4410b57cec5SDimitry Andric << ore::NV("Original", OrigF) << " split cold code into "
4420b57cec5SDimitry Andric << ore::NV("Split", OutF);
4430b57cec5SDimitry Andric });
4440b57cec5SDimitry Andric return OutF;
4450b57cec5SDimitry Andric }
4460b57cec5SDimitry Andric
4470b57cec5SDimitry Andric ORE.emit([&]() {
4480b57cec5SDimitry Andric return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed",
449*0fca6ea1SDimitry Andric &*EntryPoint.begin())
4500b57cec5SDimitry Andric << "Failed to extract region at block "
451*0fca6ea1SDimitry Andric << ore::NV("Block", &EntryPoint);
4520b57cec5SDimitry Andric });
4530b57cec5SDimitry Andric return nullptr;
4540b57cec5SDimitry Andric }
4550b57cec5SDimitry Andric
4560b57cec5SDimitry Andric /// A pair of (basic block, score).
4570b57cec5SDimitry Andric using BlockTy = std::pair<BasicBlock *, unsigned>;
4580b57cec5SDimitry Andric
4590b57cec5SDimitry Andric namespace {
4600b57cec5SDimitry Andric /// A maximal outlining region. This contains all blocks post-dominated by a
4610b57cec5SDimitry Andric /// sink block, the sink block itself, and all blocks dominated by the sink.
4620b57cec5SDimitry Andric /// If sink-predecessors and sink-successors cannot be extracted in one region,
4630b57cec5SDimitry Andric /// the static constructor returns a list of suitable extraction regions.
4640b57cec5SDimitry Andric class OutliningRegion {
4650b57cec5SDimitry Andric /// A list of (block, score) pairs. A block's score is non-zero iff it's a
4660b57cec5SDimitry Andric /// viable sub-region entry point. Blocks with higher scores are better entry
4670b57cec5SDimitry Andric /// points (i.e. they are more distant ancestors of the sink block).
4680b57cec5SDimitry Andric SmallVector<BlockTy, 0> Blocks = {};
4690b57cec5SDimitry Andric
4700b57cec5SDimitry Andric /// The suggested entry point into the region. If the region has multiple
4710b57cec5SDimitry Andric /// entry points, all blocks within the region may not be reachable from this
4720b57cec5SDimitry Andric /// entry point.
4730b57cec5SDimitry Andric BasicBlock *SuggestedEntryPoint = nullptr;
4740b57cec5SDimitry Andric
4750b57cec5SDimitry Andric /// Whether the entire function is cold.
4760b57cec5SDimitry Andric bool EntireFunctionCold = false;
4770b57cec5SDimitry Andric
4780b57cec5SDimitry Andric /// If \p BB is a viable entry point, return \p Score. Return 0 otherwise.
getEntryPointScore(BasicBlock & BB,unsigned Score)4790b57cec5SDimitry Andric static unsigned getEntryPointScore(BasicBlock &BB, unsigned Score) {
4800b57cec5SDimitry Andric return mayExtractBlock(BB) ? Score : 0;
4810b57cec5SDimitry Andric }
4820b57cec5SDimitry Andric
4830b57cec5SDimitry Andric /// These scores should be lower than the score for predecessor blocks,
4840b57cec5SDimitry Andric /// because regions starting at predecessor blocks are typically larger.
4850b57cec5SDimitry Andric static constexpr unsigned ScoreForSuccBlock = 1;
4860b57cec5SDimitry Andric static constexpr unsigned ScoreForSinkBlock = 1;
4870b57cec5SDimitry Andric
4880b57cec5SDimitry Andric OutliningRegion(const OutliningRegion &) = delete;
4890b57cec5SDimitry Andric OutliningRegion &operator=(const OutliningRegion &) = delete;
4900b57cec5SDimitry Andric
4910b57cec5SDimitry Andric public:
4920b57cec5SDimitry Andric OutliningRegion() = default;
4930b57cec5SDimitry Andric OutliningRegion(OutliningRegion &&) = default;
4940b57cec5SDimitry Andric OutliningRegion &operator=(OutliningRegion &&) = default;
4950b57cec5SDimitry Andric
create(BasicBlock & SinkBB,const DominatorTree & DT,const PostDominatorTree & PDT)4960b57cec5SDimitry Andric static std::vector<OutliningRegion> create(BasicBlock &SinkBB,
4970b57cec5SDimitry Andric const DominatorTree &DT,
4980b57cec5SDimitry Andric const PostDominatorTree &PDT) {
4990b57cec5SDimitry Andric std::vector<OutliningRegion> Regions;
5000b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 4> RegionBlocks;
5010b57cec5SDimitry Andric
5020b57cec5SDimitry Andric Regions.emplace_back();
5030b57cec5SDimitry Andric OutliningRegion *ColdRegion = &Regions.back();
5040b57cec5SDimitry Andric
5050b57cec5SDimitry Andric auto addBlockToRegion = [&](BasicBlock *BB, unsigned Score) {
5060b57cec5SDimitry Andric RegionBlocks.insert(BB);
5070b57cec5SDimitry Andric ColdRegion->Blocks.emplace_back(BB, Score);
5080b57cec5SDimitry Andric };
5090b57cec5SDimitry Andric
5100b57cec5SDimitry Andric // The ancestor farthest-away from SinkBB, and also post-dominated by it.
5110b57cec5SDimitry Andric unsigned SinkScore = getEntryPointScore(SinkBB, ScoreForSinkBlock);
5120b57cec5SDimitry Andric ColdRegion->SuggestedEntryPoint = (SinkScore > 0) ? &SinkBB : nullptr;
5130b57cec5SDimitry Andric unsigned BestScore = SinkScore;
5140b57cec5SDimitry Andric
5150b57cec5SDimitry Andric // Visit SinkBB's ancestors using inverse DFS.
5160b57cec5SDimitry Andric auto PredIt = ++idf_begin(&SinkBB);
5170b57cec5SDimitry Andric auto PredEnd = idf_end(&SinkBB);
5180b57cec5SDimitry Andric while (PredIt != PredEnd) {
5190b57cec5SDimitry Andric BasicBlock &PredBB = **PredIt;
5200b57cec5SDimitry Andric bool SinkPostDom = PDT.dominates(&SinkBB, &PredBB);
5210b57cec5SDimitry Andric
5220b57cec5SDimitry Andric // If the predecessor is cold and has no predecessors, the entire
5230b57cec5SDimitry Andric // function must be cold.
5240b57cec5SDimitry Andric if (SinkPostDom && pred_empty(&PredBB)) {
5250b57cec5SDimitry Andric ColdRegion->EntireFunctionCold = true;
5260b57cec5SDimitry Andric return Regions;
5270b57cec5SDimitry Andric }
5280b57cec5SDimitry Andric
5290b57cec5SDimitry Andric // If SinkBB does not post-dominate a predecessor, do not mark the
5300b57cec5SDimitry Andric // predecessor (or any of its predecessors) cold.
5310b57cec5SDimitry Andric if (!SinkPostDom || !mayExtractBlock(PredBB)) {
5320b57cec5SDimitry Andric PredIt.skipChildren();
5330b57cec5SDimitry Andric continue;
5340b57cec5SDimitry Andric }
5350b57cec5SDimitry Andric
5360b57cec5SDimitry Andric // Keep track of the post-dominated ancestor farthest away from the sink.
5370b57cec5SDimitry Andric // The path length is always >= 2, ensuring that predecessor blocks are
5380b57cec5SDimitry Andric // considered as entry points before the sink block.
5390b57cec5SDimitry Andric unsigned PredScore = getEntryPointScore(PredBB, PredIt.getPathLength());
5400b57cec5SDimitry Andric if (PredScore > BestScore) {
5410b57cec5SDimitry Andric ColdRegion->SuggestedEntryPoint = &PredBB;
5420b57cec5SDimitry Andric BestScore = PredScore;
5430b57cec5SDimitry Andric }
5440b57cec5SDimitry Andric
5450b57cec5SDimitry Andric addBlockToRegion(&PredBB, PredScore);
5460b57cec5SDimitry Andric ++PredIt;
5470b57cec5SDimitry Andric }
5480b57cec5SDimitry Andric
5490b57cec5SDimitry Andric // If the sink can be added to the cold region, do so. It's considered as
5500b57cec5SDimitry Andric // an entry point before any sink-successor blocks.
5510b57cec5SDimitry Andric //
5520b57cec5SDimitry Andric // Otherwise, split cold sink-successor blocks using a separate region.
5530b57cec5SDimitry Andric // This satisfies the requirement that all extraction blocks other than the
5540b57cec5SDimitry Andric // first have predecessors within the extraction region.
5550b57cec5SDimitry Andric if (mayExtractBlock(SinkBB)) {
5560b57cec5SDimitry Andric addBlockToRegion(&SinkBB, SinkScore);
5575ffd83dbSDimitry Andric if (pred_empty(&SinkBB)) {
5585ffd83dbSDimitry Andric ColdRegion->EntireFunctionCold = true;
5595ffd83dbSDimitry Andric return Regions;
5605ffd83dbSDimitry Andric }
5610b57cec5SDimitry Andric } else {
5620b57cec5SDimitry Andric Regions.emplace_back();
5630b57cec5SDimitry Andric ColdRegion = &Regions.back();
5640b57cec5SDimitry Andric BestScore = 0;
5650b57cec5SDimitry Andric }
5660b57cec5SDimitry Andric
5670b57cec5SDimitry Andric // Find all successors of SinkBB dominated by SinkBB using DFS.
5680b57cec5SDimitry Andric auto SuccIt = ++df_begin(&SinkBB);
5690b57cec5SDimitry Andric auto SuccEnd = df_end(&SinkBB);
5700b57cec5SDimitry Andric while (SuccIt != SuccEnd) {
5710b57cec5SDimitry Andric BasicBlock &SuccBB = **SuccIt;
5720b57cec5SDimitry Andric bool SinkDom = DT.dominates(&SinkBB, &SuccBB);
5730b57cec5SDimitry Andric
5740b57cec5SDimitry Andric // Don't allow the backwards & forwards DFSes to mark the same block.
5750b57cec5SDimitry Andric bool DuplicateBlock = RegionBlocks.count(&SuccBB);
5760b57cec5SDimitry Andric
5770b57cec5SDimitry Andric // If SinkBB does not dominate a successor, do not mark the successor (or
5780b57cec5SDimitry Andric // any of its successors) cold.
5790b57cec5SDimitry Andric if (DuplicateBlock || !SinkDom || !mayExtractBlock(SuccBB)) {
5800b57cec5SDimitry Andric SuccIt.skipChildren();
5810b57cec5SDimitry Andric continue;
5820b57cec5SDimitry Andric }
5830b57cec5SDimitry Andric
5840b57cec5SDimitry Andric unsigned SuccScore = getEntryPointScore(SuccBB, ScoreForSuccBlock);
5850b57cec5SDimitry Andric if (SuccScore > BestScore) {
5860b57cec5SDimitry Andric ColdRegion->SuggestedEntryPoint = &SuccBB;
5870b57cec5SDimitry Andric BestScore = SuccScore;
5880b57cec5SDimitry Andric }
5890b57cec5SDimitry Andric
5900b57cec5SDimitry Andric addBlockToRegion(&SuccBB, SuccScore);
5910b57cec5SDimitry Andric ++SuccIt;
5920b57cec5SDimitry Andric }
5930b57cec5SDimitry Andric
5940b57cec5SDimitry Andric return Regions;
5950b57cec5SDimitry Andric }
5960b57cec5SDimitry Andric
5970b57cec5SDimitry Andric /// Whether this region has nothing to extract.
empty() const5980b57cec5SDimitry Andric bool empty() const { return !SuggestedEntryPoint; }
5990b57cec5SDimitry Andric
6000b57cec5SDimitry Andric /// The blocks in this region.
blocks() const6010b57cec5SDimitry Andric ArrayRef<std::pair<BasicBlock *, unsigned>> blocks() const { return Blocks; }
6020b57cec5SDimitry Andric
6030b57cec5SDimitry Andric /// Whether the entire function containing this region is cold.
isEntireFunctionCold() const6040b57cec5SDimitry Andric bool isEntireFunctionCold() const { return EntireFunctionCold; }
6050b57cec5SDimitry Andric
6060b57cec5SDimitry Andric /// Remove a sub-region from this region and return it as a block sequence.
takeSingleEntrySubRegion(DominatorTree & DT)6070b57cec5SDimitry Andric BlockSequence takeSingleEntrySubRegion(DominatorTree &DT) {
6080b57cec5SDimitry Andric assert(!empty() && !isEntireFunctionCold() && "Nothing to extract");
6090b57cec5SDimitry Andric
6100b57cec5SDimitry Andric // Remove blocks dominated by the suggested entry point from this region.
6110b57cec5SDimitry Andric // During the removal, identify the next best entry point into the region.
6120b57cec5SDimitry Andric // Ensure that the first extracted block is the suggested entry point.
6130b57cec5SDimitry Andric BlockSequence SubRegion = {SuggestedEntryPoint};
6140b57cec5SDimitry Andric BasicBlock *NextEntryPoint = nullptr;
6150b57cec5SDimitry Andric unsigned NextScore = 0;
6160b57cec5SDimitry Andric auto RegionEndIt = Blocks.end();
6170b57cec5SDimitry Andric auto RegionStartIt = remove_if(Blocks, [&](const BlockTy &Block) {
6180b57cec5SDimitry Andric BasicBlock *BB = Block.first;
6190b57cec5SDimitry Andric unsigned Score = Block.second;
6200b57cec5SDimitry Andric bool InSubRegion =
6210b57cec5SDimitry Andric BB == SuggestedEntryPoint || DT.dominates(SuggestedEntryPoint, BB);
6220b57cec5SDimitry Andric if (!InSubRegion && Score > NextScore) {
6230b57cec5SDimitry Andric NextEntryPoint = BB;
6240b57cec5SDimitry Andric NextScore = Score;
6250b57cec5SDimitry Andric }
6260b57cec5SDimitry Andric if (InSubRegion && BB != SuggestedEntryPoint)
6270b57cec5SDimitry Andric SubRegion.push_back(BB);
6280b57cec5SDimitry Andric return InSubRegion;
6290b57cec5SDimitry Andric });
6300b57cec5SDimitry Andric Blocks.erase(RegionStartIt, RegionEndIt);
6310b57cec5SDimitry Andric
6320b57cec5SDimitry Andric // Update the suggested entry point.
6330b57cec5SDimitry Andric SuggestedEntryPoint = NextEntryPoint;
6340b57cec5SDimitry Andric
6350b57cec5SDimitry Andric return SubRegion;
6360b57cec5SDimitry Andric }
6370b57cec5SDimitry Andric };
6380b57cec5SDimitry Andric } // namespace
6390b57cec5SDimitry Andric
outlineColdRegions(Function & F,bool HasProfileSummary)6400b57cec5SDimitry Andric bool HotColdSplitting::outlineColdRegions(Function &F, bool HasProfileSummary) {
641*0fca6ea1SDimitry Andric // The set of cold blocks outlined.
6420b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 4> ColdBlocks;
6430b57cec5SDimitry Andric
644*0fca6ea1SDimitry Andric // The set of cold blocks cannot be outlined.
645*0fca6ea1SDimitry Andric SmallPtrSet<BasicBlock *, 4> CannotBeOutlinedColdBlocks;
646*0fca6ea1SDimitry Andric
6475f757f3fSDimitry Andric // Set of cold blocks obtained with RPOT.
6485f757f3fSDimitry Andric SmallPtrSet<BasicBlock *, 4> AnnotatedColdBlocks;
6495f757f3fSDimitry Andric
650*0fca6ea1SDimitry Andric // The worklist of non-intersecting regions left to outline. The first member
651*0fca6ea1SDimitry Andric // of the pair is the entry point into the region to be outlined.
652*0fca6ea1SDimitry Andric SmallVector<std::pair<BasicBlock *, CodeExtractor>, 2> OutliningWorklist;
6530b57cec5SDimitry Andric
6540b57cec5SDimitry Andric // Set up an RPO traversal. Experimentally, this performs better (outlines
6550b57cec5SDimitry Andric // more) than a PO traversal, because we prevent region overlap by keeping
6560b57cec5SDimitry Andric // the first region to contain a block.
6570b57cec5SDimitry Andric ReversePostOrderTraversal<Function *> RPOT(&F);
6580b57cec5SDimitry Andric
6590b57cec5SDimitry Andric // Calculate domtrees lazily. This reduces compile-time significantly.
6600b57cec5SDimitry Andric std::unique_ptr<DominatorTree> DT;
6610b57cec5SDimitry Andric std::unique_ptr<PostDominatorTree> PDT;
6620b57cec5SDimitry Andric
6630b57cec5SDimitry Andric // Calculate BFI lazily (it's only used to query ProfileSummaryInfo). This
6640b57cec5SDimitry Andric // reduces compile-time significantly. TODO: When we *do* use BFI, we should
6650b57cec5SDimitry Andric // be able to salvage its domtrees instead of recomputing them.
6660b57cec5SDimitry Andric BlockFrequencyInfo *BFI = nullptr;
6670b57cec5SDimitry Andric if (HasProfileSummary)
6680b57cec5SDimitry Andric BFI = GetBFI(F);
6690b57cec5SDimitry Andric
6700b57cec5SDimitry Andric TargetTransformInfo &TTI = GetTTI(F);
6710b57cec5SDimitry Andric OptimizationRemarkEmitter &ORE = (*GetORE)(F);
6720b57cec5SDimitry Andric AssumptionCache *AC = LookupAC(F);
6735f757f3fSDimitry Andric auto ColdProbThresh = TTI.getPredictableBranchThreshold().getCompl();
6745f757f3fSDimitry Andric
6755f757f3fSDimitry Andric if (ColdBranchProbDenom.getNumOccurrences())
6765f757f3fSDimitry Andric ColdProbThresh = BranchProbability(1, ColdBranchProbDenom.getValue());
6770b57cec5SDimitry Andric
678*0fca6ea1SDimitry Andric unsigned OutlinedFunctionID = 1;
6790b57cec5SDimitry Andric // Find all cold regions.
6800b57cec5SDimitry Andric for (BasicBlock *BB : RPOT) {
681*0fca6ea1SDimitry Andric // This block is already part of some outlining region.
682*0fca6ea1SDimitry Andric if (ColdBlocks.count(BB))
683*0fca6ea1SDimitry Andric continue;
684*0fca6ea1SDimitry Andric
685*0fca6ea1SDimitry Andric // This block is already part of some region cannot be outlined.
686*0fca6ea1SDimitry Andric if (CannotBeOutlinedColdBlocks.count(BB))
687*0fca6ea1SDimitry Andric continue;
688*0fca6ea1SDimitry Andric
689*0fca6ea1SDimitry Andric if (!isBasicBlockCold(BB, ColdProbThresh, AnnotatedColdBlocks, BFI))
6900b57cec5SDimitry Andric continue;
6910b57cec5SDimitry Andric
6920b57cec5SDimitry Andric LLVM_DEBUG({
6930b57cec5SDimitry Andric dbgs() << "Found a cold block:\n";
6940b57cec5SDimitry Andric BB->dump();
6950b57cec5SDimitry Andric });
6960b57cec5SDimitry Andric
6970b57cec5SDimitry Andric if (!DT)
6988bcb0991SDimitry Andric DT = std::make_unique<DominatorTree>(F);
6990b57cec5SDimitry Andric if (!PDT)
7008bcb0991SDimitry Andric PDT = std::make_unique<PostDominatorTree>(F);
7010b57cec5SDimitry Andric
7020b57cec5SDimitry Andric auto Regions = OutliningRegion::create(*BB, *DT, *PDT);
7030b57cec5SDimitry Andric for (OutliningRegion &Region : Regions) {
7040b57cec5SDimitry Andric if (Region.empty())
7050b57cec5SDimitry Andric continue;
7060b57cec5SDimitry Andric
7070b57cec5SDimitry Andric if (Region.isEntireFunctionCold()) {
7080b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Entire function is cold\n");
7090b57cec5SDimitry Andric return markFunctionCold(F);
7100b57cec5SDimitry Andric }
7110b57cec5SDimitry Andric
7120b57cec5SDimitry Andric do {
7130b57cec5SDimitry Andric BlockSequence SubRegion = Region.takeSingleEntrySubRegion(*DT);
7140b57cec5SDimitry Andric LLVM_DEBUG({
7150b57cec5SDimitry Andric dbgs() << "Hot/cold splitting attempting to outline these blocks:\n";
7160b57cec5SDimitry Andric for (BasicBlock *BB : SubRegion)
7170b57cec5SDimitry Andric BB->dump();
7180b57cec5SDimitry Andric });
7190b57cec5SDimitry Andric
720*0fca6ea1SDimitry Andric // TODO: Pass BFI and BPI to update profile information.
721*0fca6ea1SDimitry Andric CodeExtractor CE(
722*0fca6ea1SDimitry Andric SubRegion, &*DT, /* AggregateArgs */ false, /* BFI */ nullptr,
723*0fca6ea1SDimitry Andric /* BPI */ nullptr, AC, /* AllowVarArgs */ false,
724*0fca6ea1SDimitry Andric /* AllowAlloca */ false, /* AllocaBlock */ nullptr,
725*0fca6ea1SDimitry Andric /* Suffix */ "cold." + std::to_string(OutlinedFunctionID));
726*0fca6ea1SDimitry Andric
727*0fca6ea1SDimitry Andric if (CE.isEligible() && isSplittingBeneficial(CE, SubRegion, TTI) &&
728*0fca6ea1SDimitry Andric // If this outlining region intersects with another, drop the new
729*0fca6ea1SDimitry Andric // region.
730*0fca6ea1SDimitry Andric //
731*0fca6ea1SDimitry Andric // TODO: It's theoretically possible to outline more by only keeping
732*0fca6ea1SDimitry Andric // the largest region which contains a block, but the extra
733*0fca6ea1SDimitry Andric // bookkeeping to do this is tricky/expensive.
734*0fca6ea1SDimitry Andric none_of(SubRegion, [&](BasicBlock *Block) {
735*0fca6ea1SDimitry Andric return ColdBlocks.contains(Block);
736*0fca6ea1SDimitry Andric })) {
737*0fca6ea1SDimitry Andric ColdBlocks.insert(SubRegion.begin(), SubRegion.end());
738*0fca6ea1SDimitry Andric
739*0fca6ea1SDimitry Andric LLVM_DEBUG({
740*0fca6ea1SDimitry Andric for (auto *Block : SubRegion)
741*0fca6ea1SDimitry Andric dbgs() << " contains cold block:" << Block->getName() << "\n";
742*0fca6ea1SDimitry Andric });
743*0fca6ea1SDimitry Andric
744*0fca6ea1SDimitry Andric OutliningWorklist.emplace_back(
745*0fca6ea1SDimitry Andric std::make_pair(SubRegion[0], std::move(CE)));
7460b57cec5SDimitry Andric ++OutlinedFunctionID;
747*0fca6ea1SDimitry Andric } else {
748*0fca6ea1SDimitry Andric // The cold block region cannot be outlined.
749*0fca6ea1SDimitry Andric for (auto *Block : SubRegion)
750*0fca6ea1SDimitry Andric if ((DT->dominates(BB, Block) && PDT->dominates(Block, BB)) ||
751*0fca6ea1SDimitry Andric (PDT->dominates(BB, Block) && DT->dominates(Block, BB)))
752*0fca6ea1SDimitry Andric // Will skip this cold block in the loop to save the compile time
753*0fca6ea1SDimitry Andric CannotBeOutlinedColdBlocks.insert(Block);
7540b57cec5SDimitry Andric }
7550b57cec5SDimitry Andric } while (!Region.empty());
7560b57cec5SDimitry Andric
757*0fca6ea1SDimitry Andric ++NumColdRegionsFound;
758*0fca6ea1SDimitry Andric }
759*0fca6ea1SDimitry Andric }
760*0fca6ea1SDimitry Andric
761*0fca6ea1SDimitry Andric if (OutliningWorklist.empty())
762*0fca6ea1SDimitry Andric return false;
763*0fca6ea1SDimitry Andric
764*0fca6ea1SDimitry Andric // Outline single-entry cold regions, splitting up larger regions as needed.
765*0fca6ea1SDimitry Andric // Cache and recycle the CodeExtractor analysis to avoid O(n^2) compile-time.
766*0fca6ea1SDimitry Andric CodeExtractorAnalysisCache CEAC(F);
767*0fca6ea1SDimitry Andric for (auto &BCE : OutliningWorklist) {
768*0fca6ea1SDimitry Andric Function *Outlined =
769*0fca6ea1SDimitry Andric extractColdRegion(*BCE.first, BCE.second, CEAC, BFI, TTI, ORE);
770*0fca6ea1SDimitry Andric assert(Outlined && "Should be outlined");
771*0fca6ea1SDimitry Andric (void)Outlined;
772*0fca6ea1SDimitry Andric }
773*0fca6ea1SDimitry Andric
774*0fca6ea1SDimitry Andric return true;
7750b57cec5SDimitry Andric }
7760b57cec5SDimitry Andric
run(Module & M)7770b57cec5SDimitry Andric bool HotColdSplitting::run(Module &M) {
7780b57cec5SDimitry Andric bool Changed = false;
7790b57cec5SDimitry Andric bool HasProfileSummary = (M.getProfileSummary(/* IsCS */ false) != nullptr);
780fe6060f1SDimitry Andric for (Function &F : M) {
7810b57cec5SDimitry Andric // Do not touch declarations.
7820b57cec5SDimitry Andric if (F.isDeclaration())
7830b57cec5SDimitry Andric continue;
7840b57cec5SDimitry Andric
7850b57cec5SDimitry Andric // Do not modify `optnone` functions.
7860b57cec5SDimitry Andric if (F.hasOptNone())
7870b57cec5SDimitry Andric continue;
7880b57cec5SDimitry Andric
7890b57cec5SDimitry Andric // Detect inherently cold functions and mark them as such.
7900b57cec5SDimitry Andric if (isFunctionCold(F)) {
7910b57cec5SDimitry Andric Changed |= markFunctionCold(F);
7920b57cec5SDimitry Andric continue;
7930b57cec5SDimitry Andric }
7940b57cec5SDimitry Andric
7950b57cec5SDimitry Andric if (!shouldOutlineFrom(F)) {
7960b57cec5SDimitry Andric LLVM_DEBUG(llvm::dbgs() << "Skipping " << F.getName() << "\n");
7970b57cec5SDimitry Andric continue;
7980b57cec5SDimitry Andric }
7990b57cec5SDimitry Andric
8000b57cec5SDimitry Andric LLVM_DEBUG(llvm::dbgs() << "Outlining in " << F.getName() << "\n");
8010b57cec5SDimitry Andric Changed |= outlineColdRegions(F, HasProfileSummary);
8020b57cec5SDimitry Andric }
8030b57cec5SDimitry Andric return Changed;
8040b57cec5SDimitry Andric }
8050b57cec5SDimitry Andric
8060b57cec5SDimitry Andric PreservedAnalyses
run(Module & M,ModuleAnalysisManager & AM)8070b57cec5SDimitry Andric HotColdSplittingPass::run(Module &M, ModuleAnalysisManager &AM) {
8080b57cec5SDimitry Andric auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
8090b57cec5SDimitry Andric
8100b57cec5SDimitry Andric auto LookupAC = [&FAM](Function &F) -> AssumptionCache * {
8110b57cec5SDimitry Andric return FAM.getCachedResult<AssumptionAnalysis>(F);
8120b57cec5SDimitry Andric };
8130b57cec5SDimitry Andric
8140b57cec5SDimitry Andric auto GBFI = [&FAM](Function &F) {
8150b57cec5SDimitry Andric return &FAM.getResult<BlockFrequencyAnalysis>(F);
8160b57cec5SDimitry Andric };
8170b57cec5SDimitry Andric
8180b57cec5SDimitry Andric std::function<TargetTransformInfo &(Function &)> GTTI =
8190b57cec5SDimitry Andric [&FAM](Function &F) -> TargetTransformInfo & {
8200b57cec5SDimitry Andric return FAM.getResult<TargetIRAnalysis>(F);
8210b57cec5SDimitry Andric };
8220b57cec5SDimitry Andric
8230b57cec5SDimitry Andric std::unique_ptr<OptimizationRemarkEmitter> ORE;
8240b57cec5SDimitry Andric std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
8250b57cec5SDimitry Andric [&ORE](Function &F) -> OptimizationRemarkEmitter & {
8260b57cec5SDimitry Andric ORE.reset(new OptimizationRemarkEmitter(&F));
82781ad6265SDimitry Andric return *ORE;
8280b57cec5SDimitry Andric };
8290b57cec5SDimitry Andric
8300b57cec5SDimitry Andric ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
8310b57cec5SDimitry Andric
8320b57cec5SDimitry Andric if (HotColdSplitting(PSI, GBFI, GTTI, &GetORE, LookupAC).run(M))
8330b57cec5SDimitry Andric return PreservedAnalyses::none();
8340b57cec5SDimitry Andric return PreservedAnalyses::all();
8350b57cec5SDimitry Andric }
836