blob: 7c6bf14724194427dd84693b70b7301ade3f49d4 [file] [log] [blame]
Aditya Kumar801394a2018-09-07 15:03:49 +00001//===- HotColdSplitting.cpp -- Outline Cold Regions -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Outline cold regions to a separate function.
11// TODO: Update BFI and BPI
12// TODO: Add all the outlined functions to a separate section.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/Statistic.h"
18#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Analysis/BlockFrequencyInfo.h"
20#include "llvm/Analysis/BranchProbabilityInfo.h"
21#include "llvm/Analysis/CFG.h"
22#include "llvm/Analysis/OptimizationRemarkEmitter.h"
23#include "llvm/Analysis/PostDominators.h"
24#include "llvm/Analysis/ProfileSummaryInfo.h"
Sebastian Popa1f20fc2018-09-10 15:08:02 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Aditya Kumar801394a2018-09-07 15:03:49 +000026#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/CFG.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DiagnosticInfo.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/Instruction.h"
33#include "llvm/IR/Instructions.h"
Vedant Kumardd4be532018-10-29 19:15:39 +000034#include "llvm/IR/IntrinsicInst.h"
Aditya Kumar801394a2018-09-07 15:03:49 +000035#include "llvm/IR/Metadata.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/PassManager.h"
38#include "llvm/IR/Type.h"
39#include "llvm/IR/Use.h"
40#include "llvm/IR/User.h"
41#include "llvm/IR/Value.h"
42#include "llvm/Pass.h"
43#include "llvm/Support/BlockFrequency.h"
44#include "llvm/Support/BranchProbability.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Support/raw_ostream.h"
47#include "llvm/Transforms/IPO.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000048#include "llvm/Transforms/IPO/HotColdSplitting.h"
Aditya Kumar801394a2018-09-07 15:03:49 +000049#include "llvm/Transforms/Scalar.h"
50#include "llvm/Transforms/Utils/BasicBlockUtils.h"
51#include "llvm/Transforms/Utils/Cloning.h"
52#include "llvm/Transforms/Utils/CodeExtractor.h"
53#include "llvm/Transforms/Utils/Local.h"
54#include "llvm/Transforms/Utils/SSAUpdater.h"
55#include "llvm/Transforms/Utils/ValueMapper.h"
56#include <algorithm>
57#include <cassert>
58
59#define DEBUG_TYPE "hotcoldsplit"
60
Vedant Kumarc2990062018-10-24 22:15:41 +000061STATISTIC(NumColdRegionsFound, "Number of cold regions found.");
62STATISTIC(NumColdRegionsOutlined, "Number of cold regions outlined.");
Aditya Kumar801394a2018-09-07 15:03:49 +000063
64using namespace llvm;
65
66static cl::opt<bool> EnableStaticAnalyis("hot-cold-static-analysis",
67 cl::init(true), cl::Hidden);
68
Vedant Kumard2a895a2018-11-04 23:11:57 +000069static cl::opt<int>
70 MinOutliningThreshold("min-outlining-thresh", cl::init(3), cl::Hidden,
71 cl::desc("Code size threshold for outlining within a "
72 "single BB (as a multiple of TCC_Basic)"));
Aditya Kumar801394a2018-09-07 15:03:49 +000073
74namespace {
75
76struct PostDomTree : PostDomTreeBase<BasicBlock> {
77 PostDomTree(Function &F) { recalculate(F); }
78};
79
Vedant Kumarc2990062018-10-24 22:15:41 +000080/// A sequence of basic blocks.
81///
82/// A 0-sized SmallVector is slightly cheaper to move than a std::vector.
83using BlockSequence = SmallVector<BasicBlock *, 0>;
Aditya Kumar801394a2018-09-07 15:03:49 +000084
Sebastian Pop542e5222018-10-15 21:43:11 +000085// Same as blockEndsInUnreachable in CodeGen/BranchFolding.cpp. Do not modify
86// this function unless you modify the MBB version as well.
87//
88/// A no successor, non-return block probably ends in unreachable and is cold.
89/// Also consider a block that ends in an indirect branch to be a return block,
90/// since many targets use plain indirect branches to return.
Aditya Kumar801394a2018-09-07 15:03:49 +000091bool blockEndsInUnreachable(const BasicBlock &BB) {
Sebastian Pop542e5222018-10-15 21:43:11 +000092 if (!succ_empty(&BB))
93 return false;
Aditya Kumar801394a2018-09-07 15:03:49 +000094 if (BB.empty())
95 return true;
Chandler Carruthedb12a82018-10-15 10:04:59 +000096 const Instruction *I = BB.getTerminator();
Sebastian Pop542e5222018-10-15 21:43:11 +000097 return !(isa<ReturnInst>(I) || isa<IndirectBrInst>(I));
Aditya Kumar801394a2018-09-07 15:03:49 +000098}
99
Aditya Kumara27014b2018-10-03 06:21:05 +0000100static bool exceptionHandlingFunctions(const CallInst *CI) {
101 auto F = CI->getCalledFunction();
102 if (!F)
103 return false;
104 auto FName = F->getName();
105 return FName == "__cxa_begin_catch" ||
106 FName == "__cxa_free_exception" ||
107 FName == "__cxa_allocate_exception" ||
108 FName == "__cxa_begin_catch" ||
109 FName == "__cxa_end_catch";
110}
111
Sebastian Pop542e5222018-10-15 21:43:11 +0000112static bool unlikelyExecuted(const BasicBlock &BB) {
Aditya Kumar801394a2018-09-07 15:03:49 +0000113 if (blockEndsInUnreachable(BB))
114 return true;
115 // Exception handling blocks are unlikely executed.
116 if (BB.isEHPad())
117 return true;
118 for (const Instruction &I : BB)
119 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
120 // The block is cold if it calls functions tagged as cold or noreturn.
121 if (CI->hasFnAttr(Attribute::Cold) ||
Aditya Kumara27014b2018-10-03 06:21:05 +0000122 CI->hasFnAttr(Attribute::NoReturn) ||
123 exceptionHandlingFunctions(CI))
Aditya Kumar801394a2018-09-07 15:03:49 +0000124 return true;
125
126 // Assume that inline assembly is hot code.
127 if (isa<InlineAsm>(CI->getCalledValue()))
128 return false;
129 }
130 return false;
131}
132
Vedant Kumarc2990062018-10-24 22:15:41 +0000133/// Check whether it's safe to outline \p BB.
134static bool mayExtractBlock(const BasicBlock &BB) {
135 return !BB.hasAddressTaken();
Sebastian Pop542e5222018-10-15 21:43:11 +0000136}
137
Vedant Kumard2a895a2018-11-04 23:11:57 +0000138/// Check whether \p BB is profitable to outline (i.e. its code size cost meets
139/// the threshold set in \p MinOutliningThreshold).
140static bool isProfitableToOutline(const BasicBlock &BB,
141 TargetTransformInfo &TTI) {
142 int Cost = 0;
Vedant Kumardd4be532018-10-29 19:15:39 +0000143 for (const Instruction &I : BB) {
144 if (isa<DbgInfoIntrinsic>(&I) || &I == BB.getTerminator())
145 continue;
Vedant Kumard2a895a2018-11-04 23:11:57 +0000146
147 Cost += TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
148
149 if (Cost >= (MinOutliningThreshold * TargetTransformInfo::TCC_Basic))
Vedant Kumardd4be532018-10-29 19:15:39 +0000150 return true;
151 }
152 return false;
153}
154
Vedant Kumarc2990062018-10-24 22:15:41 +0000155/// Identify the maximal region of cold blocks which includes \p SinkBB.
156///
157/// Include all blocks post-dominated by \p SinkBB, \p SinkBB itself, and all
158/// blocks dominated by \p SinkBB. Exclude all other blocks, and blocks which
159/// cannot be outlined.
160///
161/// Return an empty sequence if the cold region is too small to outline, or if
162/// the cold region has no warm predecessors.
Vedant Kumard2a895a2018-11-04 23:11:57 +0000163static BlockSequence findMaximalColdRegion(BasicBlock &SinkBB,
164 TargetTransformInfo &TTI,
165 DominatorTree &DT,
166 PostDomTree &PDT) {
Vedant Kumarc2990062018-10-24 22:15:41 +0000167 // The maximal cold region.
168 BlockSequence ColdRegion = {};
Sebastian Pop12171602018-09-14 20:36:10 +0000169
Vedant Kumarc2990062018-10-24 22:15:41 +0000170 // The ancestor farthest-away from SinkBB, and also post-dominated by it.
171 BasicBlock *MaxAncestor = &SinkBB;
172 unsigned MaxAncestorHeight = 0;
173
174 // Visit SinkBB's ancestors using inverse DFS.
175 auto PredIt = ++idf_begin(&SinkBB);
176 auto PredEnd = idf_end(&SinkBB);
177 while (PredIt != PredEnd) {
178 BasicBlock &PredBB = **PredIt;
179 bool SinkPostDom = PDT.dominates(&SinkBB, &PredBB);
180
181 // If SinkBB does not post-dominate a predecessor, do not mark the
182 // predecessor (or any of its predecessors) cold.
183 if (!SinkPostDom || !mayExtractBlock(PredBB)) {
184 PredIt.skipChildren();
185 continue;
Sebastian Pop542e5222018-10-15 21:43:11 +0000186 }
Sebastian Pop12171602018-09-14 20:36:10 +0000187
Vedant Kumarc2990062018-10-24 22:15:41 +0000188 // Keep track of the post-dominated ancestor farthest away from the sink.
189 unsigned AncestorHeight = PredIt.getPathLength();
190 if (AncestorHeight > MaxAncestorHeight) {
191 MaxAncestor = &PredBB;
192 MaxAncestorHeight = AncestorHeight;
Aditya Kumar801394a2018-09-07 15:03:49 +0000193 }
Vedant Kumarc2990062018-10-24 22:15:41 +0000194
195 ColdRegion.push_back(&PredBB);
196 ++PredIt;
Aditya Kumar801394a2018-09-07 15:03:49 +0000197 }
198
Vedant Kumarc2990062018-10-24 22:15:41 +0000199 // CodeExtractor requires that all blocks to be extracted must be dominated
200 // by the first block to be extracted.
201 //
202 // To avoid spurious or repeated outlining, require that the max ancestor
203 // has a predecessor. By construction this predecessor is not in the cold
204 // region, i.e. its existence implies we don't outline the whole function.
205 //
206 // TODO: If MaxAncestor has no predecessors, we may be able to outline the
207 // second largest cold region that has a predecessor.
208 if (pred_empty(MaxAncestor) ||
209 MaxAncestor->getSinglePredecessor() == MaxAncestor)
210 return {};
Sebastian Pop12171602018-09-14 20:36:10 +0000211
Vedant Kumarc2990062018-10-24 22:15:41 +0000212 // Filter out predecessors not dominated by the max ancestor.
213 //
214 // TODO: Blocks not dominated by the max ancestor could be extracted as
215 // other cold regions. Marking outlined calls as noreturn when appropriate
216 // and outlining more than once per function could achieve most of the win.
217 auto EraseIt = remove_if(ColdRegion, [&](BasicBlock *PredBB) {
218 return PredBB != MaxAncestor && !DT.dominates(MaxAncestor, PredBB);
219 });
220 ColdRegion.erase(EraseIt, ColdRegion.end());
Sebastian Pop12171602018-09-14 20:36:10 +0000221
Vedant Kumarc2990062018-10-24 22:15:41 +0000222 // Add SinkBB to the cold region.
223 ColdRegion.push_back(&SinkBB);
224
225 // Ensure that the first extracted block is the max ancestor.
226 if (ColdRegion[0] != MaxAncestor) {
227 auto AncestorIt = find(ColdRegion, MaxAncestor);
228 *AncestorIt = ColdRegion[0];
229 ColdRegion[0] = MaxAncestor;
Sebastian Pop12171602018-09-14 20:36:10 +0000230 }
231
Vedant Kumarc2990062018-10-24 22:15:41 +0000232 // Find all successors of SinkBB dominated by SinkBB using DFS.
233 auto SuccIt = ++df_begin(&SinkBB);
234 auto SuccEnd = df_end(&SinkBB);
235 while (SuccIt != SuccEnd) {
236 BasicBlock &SuccBB = **SuccIt;
237 bool SinkDom = DT.dominates(&SinkBB, &SuccBB);
238
239 // If SinkBB does not dominate a successor, do not mark the successor (or
240 // any of its successors) cold.
241 if (!SinkDom || !mayExtractBlock(SuccBB)) {
242 SuccIt.skipChildren();
243 continue;
244 }
245
246 ColdRegion.push_back(&SuccBB);
247 ++SuccIt;
248 }
249
Vedant Kumard2a895a2018-11-04 23:11:57 +0000250 if (ColdRegion.size() == 1 && !isProfitableToOutline(*ColdRegion[0], TTI))
Vedant Kumarc2990062018-10-24 22:15:41 +0000251 return {};
252
253 return ColdRegion;
254}
255
256/// Get the largest cold region in \p F.
257static BlockSequence getLargestColdRegion(Function &F, ProfileSummaryInfo &PSI,
258 BlockFrequencyInfo *BFI,
Vedant Kumard2a895a2018-11-04 23:11:57 +0000259 TargetTransformInfo &TTI,
Vedant Kumarc2990062018-10-24 22:15:41 +0000260 DominatorTree &DT, PostDomTree &PDT) {
261 // Keep track of the largest cold region.
262 BlockSequence LargestColdRegion = {};
263
264 for (BasicBlock &BB : F) {
265 // Identify cold blocks.
266 if (!mayExtractBlock(BB))
267 continue;
268 bool Cold =
Vedant Kumare7b789b2018-11-19 05:23:16 +0000269 PSI.isColdBlock(&BB, BFI) || (EnableStaticAnalyis && unlikelyExecuted(BB));
Vedant Kumarc2990062018-10-24 22:15:41 +0000270 if (!Cold)
Sebastian Pop12171602018-09-14 20:36:10 +0000271 continue;
272
Vedant Kumarc2990062018-10-24 22:15:41 +0000273 LLVM_DEBUG({
274 dbgs() << "Found cold block:\n";
275 BB.dump();
276 });
277
278 // Find a maximal cold region we can outline.
Vedant Kumard2a895a2018-11-04 23:11:57 +0000279 BlockSequence ColdRegion = findMaximalColdRegion(BB, TTI, DT, PDT);
Vedant Kumarc2990062018-10-24 22:15:41 +0000280 if (ColdRegion.empty()) {
281 LLVM_DEBUG(dbgs() << " Skipping (block not profitable to extract)\n");
Sebastian Pop542e5222018-10-15 21:43:11 +0000282 continue;
Sebastian Pop12171602018-09-14 20:36:10 +0000283 }
Vedant Kumarc2990062018-10-24 22:15:41 +0000284
285 ++NumColdRegionsFound;
286
287 LLVM_DEBUG({
288 llvm::dbgs() << "Identified cold region with " << ColdRegion.size()
289 << " blocks:\n";
290 for (BasicBlock *BB : ColdRegion)
291 BB->dump();
292 });
293
294 // TODO: Outline more than one region.
295 if (ColdRegion.size() > LargestColdRegion.size())
296 LargestColdRegion = std::move(ColdRegion);
Sebastian Pop12171602018-09-14 20:36:10 +0000297 }
298
Vedant Kumarc2990062018-10-24 22:15:41 +0000299 return LargestColdRegion;
Aditya Kumar801394a2018-09-07 15:03:49 +0000300}
301
302class HotColdSplitting {
303public:
304 HotColdSplitting(ProfileSummaryInfo *ProfSI,
305 function_ref<BlockFrequencyInfo *(Function &)> GBFI,
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000306 function_ref<TargetTransformInfo &(Function &)> GTTI,
Aditya Kumar801394a2018-09-07 15:03:49 +0000307 std::function<OptimizationRemarkEmitter &(Function &)> *GORE)
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000308 : PSI(ProfSI), GetBFI(GBFI), GetTTI(GTTI), GetORE(GORE) {}
Aditya Kumar801394a2018-09-07 15:03:49 +0000309 bool run(Module &M);
310
311private:
312 bool shouldOutlineFrom(const Function &F) const;
Vedant Kumarc2990062018-10-24 22:15:41 +0000313 Function *extractColdRegion(const BlockSequence &Region, DominatorTree &DT,
Vedant Kumard2a895a2018-11-04 23:11:57 +0000314 BlockFrequencyInfo *BFI, TargetTransformInfo &TTI,
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000315 OptimizationRemarkEmitter &ORE, unsigned Count);
Aditya Kumar801394a2018-09-07 15:03:49 +0000316 SmallPtrSet<const Function *, 2> OutlinedFunctions;
317 ProfileSummaryInfo *PSI;
318 function_ref<BlockFrequencyInfo *(Function &)> GetBFI;
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000319 function_ref<TargetTransformInfo &(Function &)> GetTTI;
Aditya Kumar801394a2018-09-07 15:03:49 +0000320 std::function<OptimizationRemarkEmitter &(Function &)> *GetORE;
321};
322
323class HotColdSplittingLegacyPass : public ModulePass {
324public:
325 static char ID;
326 HotColdSplittingLegacyPass() : ModulePass(ID) {
327 initializeHotColdSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
328 }
329
330 void getAnalysisUsage(AnalysisUsage &AU) const override {
331 AU.addRequired<AssumptionCacheTracker>();
332 AU.addRequired<BlockFrequencyInfoWrapperPass>();
333 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000334 AU.addRequired<TargetTransformInfoWrapperPass>();
Aditya Kumar801394a2018-09-07 15:03:49 +0000335 }
336
337 bool runOnModule(Module &M) override;
338};
339
340} // end anonymous namespace
341
342// Returns false if the function should not be considered for hot-cold split
Sebastian Pop0f30f082018-09-14 20:36:19 +0000343// optimization.
Aditya Kumar801394a2018-09-07 15:03:49 +0000344bool HotColdSplitting::shouldOutlineFrom(const Function &F) const {
Sebastian Pop0f30f082018-09-14 20:36:19 +0000345 // Do not try to outline again from an already outlined cold function.
346 if (OutlinedFunctions.count(&F))
347 return false;
348
Aditya Kumar801394a2018-09-07 15:03:49 +0000349 if (F.size() <= 2)
350 return false;
351
Vedant Kumarc2990062018-10-24 22:15:41 +0000352 // TODO: Consider only skipping functions marked `optnone` or `cold`.
353
Aditya Kumar801394a2018-09-07 15:03:49 +0000354 if (F.hasAddressTaken())
355 return false;
356
357 if (F.hasFnAttribute(Attribute::AlwaysInline))
358 return false;
359
360 if (F.hasFnAttribute(Attribute::NoInline))
361 return false;
362
363 if (F.getCallingConv() == CallingConv::Cold)
364 return false;
365
366 if (PSI->isFunctionEntryCold(&F))
367 return false;
368 return true;
369}
370
Vedant Kumarc2990062018-10-24 22:15:41 +0000371Function *HotColdSplitting::extractColdRegion(const BlockSequence &Region,
372 DominatorTree &DT,
373 BlockFrequencyInfo *BFI,
Vedant Kumard2a895a2018-11-04 23:11:57 +0000374 TargetTransformInfo &TTI,
Vedant Kumarc2990062018-10-24 22:15:41 +0000375 OptimizationRemarkEmitter &ORE,
376 unsigned Count) {
Teresa Johnsonf431a2f2018-10-22 19:06:42 +0000377 assert(!Region.empty());
Aditya Kumar801394a2018-09-07 15:03:49 +0000378 LLVM_DEBUG(for (auto *BB : Region)
379 llvm::dbgs() << "\nExtracting: " << *BB;);
Sebastian Pop12171602018-09-14 20:36:10 +0000380
Aditya Kumar801394a2018-09-07 15:03:49 +0000381 // TODO: Pass BFI and BPI to update profile information.
Vedant Kumarc2990062018-10-24 22:15:41 +0000382 CodeExtractor CE(Region, &DT, /* AggregateArgs */ false, /* BFI */ nullptr,
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000383 /* BPI */ nullptr, /* AllowVarArgs */ false,
384 /* AllowAlloca */ false,
385 /* Suffix */ "cold." + std::to_string(Count));
Aditya Kumar801394a2018-09-07 15:03:49 +0000386
387 SetVector<Value *> Inputs, Outputs, Sinks;
388 CE.findInputsOutputs(Inputs, Outputs, Sinks);
389
390 // Do not extract regions that have live exit variables.
Vedant Kumarc2990062018-10-24 22:15:41 +0000391 if (Outputs.size() > 0) {
392 LLVM_DEBUG(llvm::dbgs() << "Not outlining; live outputs\n");
Aditya Kumar801394a2018-09-07 15:03:49 +0000393 return nullptr;
Vedant Kumarc2990062018-10-24 22:15:41 +0000394 }
Aditya Kumar801394a2018-09-07 15:03:49 +0000395
Vedant Kumarc2990062018-10-24 22:15:41 +0000396 // TODO: Run MergeBasicBlockIntoOnlyPred on the outlined function.
Teresa Johnsonf431a2f2018-10-22 19:06:42 +0000397 Function *OrigF = Region[0]->getParent();
Aditya Kumar801394a2018-09-07 15:03:49 +0000398 if (Function *OutF = CE.extractCodeRegion()) {
399 User *U = *OutF->user_begin();
400 CallInst *CI = cast<CallInst>(U);
401 CallSite CS(CI);
Vedant Kumarc2990062018-10-24 22:15:41 +0000402 NumColdRegionsOutlined++;
Vedant Kumard2a895a2018-11-04 23:11:57 +0000403 if (TTI.useColdCCForColdCall(*OutF)) {
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000404 OutF->setCallingConv(CallingConv::Cold);
405 CS.setCallingConv(CallingConv::Cold);
406 }
Aditya Kumar801394a2018-09-07 15:03:49 +0000407 CI->setIsNoInline();
Vedant Kumar50315462018-10-23 19:41:12 +0000408
409 // Try to make the outlined code as small as possible on the assumption
410 // that it's cold.
411 assert(!OutF->hasFnAttribute(Attribute::OptimizeNone) &&
412 "An outlined function should never be marked optnone");
413 OutF->addFnAttr(Attribute::MinSize);
414
Sebastian Pop0f30f082018-09-14 20:36:19 +0000415 LLVM_DEBUG(llvm::dbgs() << "Outlined Region: " << *OutF);
Teresa Johnsonf431a2f2018-10-22 19:06:42 +0000416 ORE.emit([&]() {
417 return OptimizationRemark(DEBUG_TYPE, "HotColdSplit",
418 &*Region[0]->begin())
419 << ore::NV("Original", OrigF) << " split cold code into "
420 << ore::NV("Split", OutF);
421 });
Aditya Kumar801394a2018-09-07 15:03:49 +0000422 return OutF;
423 }
424
425 ORE.emit([&]() {
426 return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed",
427 &*Region[0]->begin())
428 << "Failed to extract region at block "
429 << ore::NV("Block", Region.front());
430 });
431 return nullptr;
432}
433
Aditya Kumar801394a2018-09-07 15:03:49 +0000434bool HotColdSplitting::run(Module &M) {
Vedant Kumarc2990062018-10-24 22:15:41 +0000435 bool Changed = false;
Aditya Kumar801394a2018-09-07 15:03:49 +0000436 for (auto &F : M) {
Vedant Kumarc2990062018-10-24 22:15:41 +0000437 if (!shouldOutlineFrom(F)) {
438 LLVM_DEBUG(llvm::dbgs() << "Not outlining in " << F.getName() << "\n");
Aditya Kumar801394a2018-09-07 15:03:49 +0000439 continue;
Vedant Kumarc2990062018-10-24 22:15:41 +0000440 }
441
442 LLVM_DEBUG(llvm::dbgs() << "Outlining in " << F.getName() << "\n");
Aditya Kumar801394a2018-09-07 15:03:49 +0000443 DominatorTree DT(F);
444 PostDomTree PDT(F);
445 PDT.recalculate(F);
Vedant Kumarc2990062018-10-24 22:15:41 +0000446 BlockFrequencyInfo *BFI = GetBFI(F);
Vedant Kumard2a895a2018-11-04 23:11:57 +0000447 TargetTransformInfo &TTI = GetTTI(F);
Aditya Kumar801394a2018-09-07 15:03:49 +0000448
Vedant Kumard2a895a2018-11-04 23:11:57 +0000449 BlockSequence ColdRegion = getLargestColdRegion(F, *PSI, BFI, TTI, DT, PDT);
Vedant Kumarc2990062018-10-24 22:15:41 +0000450 if (ColdRegion.empty())
451 continue;
452
453 OptimizationRemarkEmitter &ORE = (*GetORE)(F);
454 Function *Outlined =
Vedant Kumard2a895a2018-11-04 23:11:57 +0000455 extractColdRegion(ColdRegion, DT, BFI, TTI, ORE, /*Count=*/1);
Vedant Kumarc2990062018-10-24 22:15:41 +0000456 if (Outlined) {
Aditya Kumar801394a2018-09-07 15:03:49 +0000457 OutlinedFunctions.insert(Outlined);
Vedant Kumarc2990062018-10-24 22:15:41 +0000458 Changed = true;
459 }
Aditya Kumar801394a2018-09-07 15:03:49 +0000460 }
Vedant Kumarc2990062018-10-24 22:15:41 +0000461 return Changed;
Aditya Kumar801394a2018-09-07 15:03:49 +0000462}
463
464bool HotColdSplittingLegacyPass::runOnModule(Module &M) {
465 if (skipModule(M))
466 return false;
467 ProfileSummaryInfo *PSI =
Vedant Kumare7b789b2018-11-19 05:23:16 +0000468 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000469 auto GTTI = [this](Function &F) -> TargetTransformInfo & {
470 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
471 };
Aditya Kumar801394a2018-09-07 15:03:49 +0000472 auto GBFI = [this](Function &F) {
473 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
474 };
475 std::unique_ptr<OptimizationRemarkEmitter> ORE;
476 std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
477 [&ORE](Function &F) -> OptimizationRemarkEmitter & {
478 ORE.reset(new OptimizationRemarkEmitter(&F));
479 return *ORE.get();
480 };
481
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000482 return HotColdSplitting(PSI, GBFI, GTTI, &GetORE).run(M);
Aditya Kumar801394a2018-09-07 15:03:49 +0000483}
484
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000485PreservedAnalyses
486HotColdSplittingPass::run(Module &M, ModuleAnalysisManager &AM) {
487 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
488
489 std::function<AssumptionCache &(Function &)> GetAssumptionCache =
490 [&FAM](Function &F) -> AssumptionCache & {
491 return FAM.getResult<AssumptionAnalysis>(F);
492 };
493
494 auto GBFI = [&FAM](Function &F) {
495 return &FAM.getResult<BlockFrequencyAnalysis>(F);
496 };
497
498 std::function<TargetTransformInfo &(Function &)> GTTI =
499 [&FAM](Function &F) -> TargetTransformInfo & {
500 return FAM.getResult<TargetIRAnalysis>(F);
501 };
502
503 std::unique_ptr<OptimizationRemarkEmitter> ORE;
504 std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
505 [&ORE](Function &F) -> OptimizationRemarkEmitter & {
506 ORE.reset(new OptimizationRemarkEmitter(&F));
507 return *ORE.get();
508 };
509
510 ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
511
512 if (HotColdSplitting(PSI, GBFI, GTTI, &GetORE).run(M))
513 return PreservedAnalyses::none();
514 return PreservedAnalyses::all();
515}
516
Aditya Kumar801394a2018-09-07 15:03:49 +0000517char HotColdSplittingLegacyPass::ID = 0;
518INITIALIZE_PASS_BEGIN(HotColdSplittingLegacyPass, "hotcoldsplit",
519 "Hot Cold Splitting", false, false)
520INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
521INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
522INITIALIZE_PASS_END(HotColdSplittingLegacyPass, "hotcoldsplit",
523 "Hot Cold Splitting", false, false)
524
525ModulePass *llvm::createHotColdSplittingPass() {
526 return new HotColdSplittingLegacyPass();
527}