blob: 787afc32dfbf24a6563d9f1241a4260cbab04bfd [file] [log] [blame]
Justin Bogner61ba2e32014-12-08 18:02:35 +00001//===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
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//
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000010// This pass lowers instrprof_* intrinsics emitted by a frontend for profiling.
11// It also builds the data structures and initialization code needed for
12// updating execution counts and emitting the profile at runtime.
Justin Bogner61ba2e32014-12-08 18:02:35 +000013//
14//===----------------------------------------------------------------------===//
15
Xinliang David Li69a00f02016-06-21 02:39:08 +000016#include "llvm/Transforms/InstrProfiling.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000017#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000020#include "llvm/ADT/Triple.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000021#include "llvm/ADT/Twine.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000022#include "llvm/Analysis/LoopInfo.h"
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000024#include "llvm/IR/Attributes.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/Constant.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DerivedTypes.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000029#include "llvm/IR/Dominators.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalValue.h"
32#include "llvm/IR/GlobalVariable.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000033#include "llvm/IR/IRBuilder.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000034#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Instructions.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000036#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/Module.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000038#include "llvm/IR/Type.h"
39#include "llvm/Pass.h"
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000040#include "llvm/ProfileData/InstrProf.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000041#include "llvm/Support/Casting.h"
42#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/Error.h"
44#include "llvm/Support/ErrorHandling.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/LoopSimplify.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000047#include "llvm/Transforms/Utils/ModuleUtils.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000048#include "llvm/Transforms/Utils/SSAUpdater.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000049#include <algorithm>
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <string>
Justin Bogner61ba2e32014-12-08 18:02:35 +000054
55using namespace llvm;
56
57#define DEBUG_TYPE "instrprof"
58
Rong Xu48596b62017-04-04 16:42:20 +000059// The start and end values of precise value profile range for memory
60// intrinsic sizes
61cl::opt<std::string> MemOPSizeRange(
62 "memop-size-range",
63 cl::desc("Set the range of size in memory intrinsic calls to be profiled "
64 "precisely, in a format of <start_val>:<end_val>"),
65 cl::init(""));
66
67// The value that considered to be large value in memory intrinsic.
68cl::opt<unsigned> MemOPSizeLarge(
69 "memop-size-large",
70 cl::desc("Set large value thresthold in memory intrinsic size profiling. "
71 "Value of 0 disables the large value profiling."),
72 cl::init(8192));
73
Justin Bogner61ba2e32014-12-08 18:02:35 +000074namespace {
75
Xinliang David Lia82d6c02016-02-08 18:13:49 +000076cl::opt<bool> DoNameCompression("enable-name-compression",
77 cl::desc("Enable name string compression"),
78 cl::init(true));
79
Rong Xu20f5df12017-01-11 20:19:41 +000080cl::opt<bool> DoHashBasedCounterSplit(
81 "hash-based-counter-split",
82 cl::desc("Rename counter variable of a comdat function based on cfg hash"),
83 cl::init(true));
84
Xinliang David Lib628dd32016-05-21 22:55:34 +000085cl::opt<bool> ValueProfileStaticAlloc(
86 "vp-static-alloc",
87 cl::desc("Do static counter allocation for value profiler"),
88 cl::init(true));
Eugene Zelenko34c23272017-01-18 00:57:48 +000089
Xinliang David Lib628dd32016-05-21 22:55:34 +000090cl::opt<double> NumCountersPerValueSite(
91 "vp-counters-per-site",
92 cl::desc("The average number of profile counters allocated "
93 "per value profiling site."),
94 // This is set to a very small value because in real programs, only
95 // a very small percentage of value sites have non-zero targets, e.g, 1/30.
96 // For those sites with non-zero profile, the average number of targets
97 // is usually smaller than 2.
98 cl::init(1.0));
99
Xinliang David Lib67530e2017-06-25 00:26:43 +0000100cl::opt<bool> AtomicCounterUpdatePromoted(
101 "atomic-counter-update-promoted", cl::ZeroOrMore,
102 cl::desc("Do counter update using atomic fetch add "
103 " for promoted counters only"),
104 cl::init(false));
105
106// If the option is not specified, the default behavior about whether
107// counter promotion is done depends on how instrumentaiton lowering
108// pipeline is setup, i.e., the default value of true of this option
109// does not mean the promotion will be done by default. Explicitly
110// setting this option can override the default behavior.
111cl::opt<bool> DoCounterPromotion("do-counter-promotion", cl::ZeroOrMore,
112 cl::desc("Do counter register promotion"),
113 cl::init(false));
114cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
Xinliang David Lif564c692017-07-12 23:27:44 +0000115 cl::ZeroOrMore, "max-counter-promotions-per-loop", cl::init(20),
Xinliang David Lib67530e2017-06-25 00:26:43 +0000116 cl::desc("Max number counter promotions per loop to avoid"
117 " increasing register pressure too much"));
118
119// A debug option
120cl::opt<int>
121 MaxNumOfPromotions(cl::ZeroOrMore, "max-counter-promotions", cl::init(-1),
122 cl::desc("Max number of allowed counter promotions"));
123
Xinliang David Lif564c692017-07-12 23:27:44 +0000124cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
125 cl::ZeroOrMore, "speculative-counter-promotion-max-exiting", cl::init(3),
126 cl::desc("The max number of exiting blocks of a loop to allow "
127 " speculative counter promotion"));
128
129cl::opt<bool> SpeculativeCounterPromotionToLoop(
130 cl::ZeroOrMore, "speculative-counter-promotion-to-loop", cl::init(false),
131 cl::desc("When the option is false, if the target block is in a loop, "
132 "the promotion will be disallowed unless the promoted counter "
133 " update can be further/iteratively promoted into an acyclic "
134 " region."));
135
136cl::opt<bool> IterativeCounterPromotion(
137 cl::ZeroOrMore, "iterative-counter-promotion", cl::init(true),
138 cl::desc("Allow counter promotion across the whole loop nest."));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000139
Xinliang David Lie6b89292016-04-18 17:47:38 +0000140class InstrProfilingLegacyPass : public ModulePass {
141 InstrProfiling InstrProf;
142
Justin Bogner61ba2e32014-12-08 18:02:35 +0000143public:
144 static char ID;
Eugene Zelenko34c23272017-01-18 00:57:48 +0000145
146 InstrProfilingLegacyPass() : ModulePass(ID) {}
Xinliang David Lie6b89292016-04-18 17:47:38 +0000147 InstrProfilingLegacyPass(const InstrProfOptions &Options)
148 : ModulePass(ID), InstrProf(Options) {}
Eugene Zelenko34c23272017-01-18 00:57:48 +0000149
Mehdi Amini117296c2016-10-01 02:56:57 +0000150 StringRef getPassName() const override {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000151 return "Frontend instrumentation-based coverage lowering";
152 }
153
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000154 bool runOnModule(Module &M) override {
155 return InstrProf.run(M, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI());
156 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000157
158 void getAnalysisUsage(AnalysisUsage &AU) const override {
159 AU.setPreservesCFG();
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000160 AU.addRequired<TargetLibraryInfoWrapperPass>();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000161 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000162};
163
Xinliang David Lif564c692017-07-12 23:27:44 +0000164///
Xinliang David Lib67530e2017-06-25 00:26:43 +0000165/// A helper class to promote one counter RMW operation in the loop
166/// into register update.
167///
168/// RWM update for the counter will be sinked out of the loop after
169/// the transformation.
170///
171class PGOCounterPromoterHelper : public LoadAndStorePromoter {
172public:
Xinliang David Lif564c692017-07-12 23:27:44 +0000173 PGOCounterPromoterHelper(
174 Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
175 BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
176 ArrayRef<Instruction *> InsertPts,
177 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
178 LoopInfo &LI)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000179 : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
Xinliang David Lif564c692017-07-12 23:27:44 +0000180 InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000181 assert(isa<LoadInst>(L));
182 assert(isa<StoreInst>(S));
183 SSA.AddAvailableValue(PH, Init);
184 }
Xinliang David Lif564c692017-07-12 23:27:44 +0000185
Xinliang David Lib67530e2017-06-25 00:26:43 +0000186 void doExtraRewritesBeforeFinalDeletion() const override {
187 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
188 BasicBlock *ExitBlock = ExitBlocks[i];
189 Instruction *InsertPos = InsertPts[i];
190 // Get LiveIn value into the ExitBlock. If there are multiple
191 // predecessors, the value is defined by a PHI node in this
192 // block.
193 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
194 Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
195 IRBuilder<> Builder(InsertPos);
196 if (AtomicCounterUpdatePromoted)
Xinliang David Lif564c692017-07-12 23:27:44 +0000197 // automic update currently can only be promoted across the current
198 // loop, not the whole loop nest.
Xinliang David Lib67530e2017-06-25 00:26:43 +0000199 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
200 AtomicOrdering::SequentiallyConsistent);
201 else {
202 LoadInst *OldVal = Builder.CreateLoad(Addr, "pgocount.promoted");
203 auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
Xinliang David Lif564c692017-07-12 23:27:44 +0000204 auto *NewStore = Builder.CreateStore(NewVal, Addr);
205
206 // Now update the parent loop's candidate list:
207 if (IterativeCounterPromotion) {
208 auto *TargetLoop = LI.getLoopFor(ExitBlock);
209 if (TargetLoop)
210 LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
211 }
Xinliang David Lib67530e2017-06-25 00:26:43 +0000212 }
213 }
214 }
215
216private:
217 Instruction *Store;
218 ArrayRef<BasicBlock *> ExitBlocks;
219 ArrayRef<Instruction *> InsertPts;
Xinliang David Lif564c692017-07-12 23:27:44 +0000220 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
221 LoopInfo &LI;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000222};
223
224/// A helper class to do register promotion for all profile counter
225/// updates in a loop.
226///
227class PGOCounterPromoter {
228public:
Xinliang David Lif564c692017-07-12 23:27:44 +0000229 PGOCounterPromoter(
230 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
231 Loop &CurLoop, LoopInfo &LI)
232 : LoopToCandidates(LoopToCands), ExitBlocks(), InsertPts(), L(CurLoop),
233 LI(LI) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000234
235 SmallVector<BasicBlock *, 8> LoopExitBlocks;
236 SmallPtrSet<BasicBlock *, 8> BlockSet;
Xinliang David Lif564c692017-07-12 23:27:44 +0000237 L.getExitBlocks(LoopExitBlocks);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000238
239 for (BasicBlock *ExitBlock : LoopExitBlocks) {
240 if (BlockSet.insert(ExitBlock).second) {
241 ExitBlocks.push_back(ExitBlock);
242 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
243 }
244 }
245 }
246
247 bool run(int64_t *NumPromoted) {
Xinliang David Lic23d2c62017-11-30 19:16:25 +0000248 // Skip 'infinite' loops:
249 if (ExitBlocks.size() == 0)
250 return false;
Xinliang David Lif564c692017-07-12 23:27:44 +0000251 unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
252 if (MaxProm == 0)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000253 return false;
254
255 unsigned Promoted = 0;
Xinliang David Lif564c692017-07-12 23:27:44 +0000256 for (auto &Cand : LoopToCandidates[&L]) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000257
258 SmallVector<PHINode *, 4> NewPHIs;
259 SSAUpdater SSA(&NewPHIs);
260 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
Xinliang David Lif564c692017-07-12 23:27:44 +0000261
Xinliang David Lib67530e2017-06-25 00:26:43 +0000262 PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
Xinliang David Lif564c692017-07-12 23:27:44 +0000263 L.getLoopPreheader(), ExitBlocks,
264 InsertPts, LoopToCandidates, LI);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000265 Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
266 Promoted++;
Xinliang David Lif564c692017-07-12 23:27:44 +0000267 if (Promoted >= MaxProm)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000268 break;
Xinliang David Lif564c692017-07-12 23:27:44 +0000269
Xinliang David Lib67530e2017-06-25 00:26:43 +0000270 (*NumPromoted)++;
271 if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
272 break;
273 }
274
275 DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
Xinliang David Lif564c692017-07-12 23:27:44 +0000276 << L.getLoopDepth() << ")\n");
Xinliang David Lib67530e2017-06-25 00:26:43 +0000277 return Promoted != 0;
278 }
279
280private:
Xinliang David Lif564c692017-07-12 23:27:44 +0000281 bool allowSpeculativeCounterPromotion(Loop *LP) {
282 SmallVector<BasicBlock *, 8> ExitingBlocks;
283 L.getExitingBlocks(ExitingBlocks);
284 // Not considierered speculative.
285 if (ExitingBlocks.size() == 1)
286 return true;
287 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
288 return false;
289 return true;
290 }
291
292 // Returns the max number of Counter Promotions for LP.
293 unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
294 // We can't insert into a catchswitch.
295 SmallVector<BasicBlock *, 8> LoopExitBlocks;
296 LP->getExitBlocks(LoopExitBlocks);
297 if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
298 return isa<CatchSwitchInst>(Exit->getTerminator());
299 }))
300 return 0;
301
302 if (!LP->hasDedicatedExits())
303 return 0;
304
305 BasicBlock *PH = LP->getLoopPreheader();
306 if (!PH)
307 return 0;
308
309 SmallVector<BasicBlock *, 8> ExitingBlocks;
310 LP->getExitingBlocks(ExitingBlocks);
311 // Not considierered speculative.
312 if (ExitingBlocks.size() == 1)
313 return MaxNumOfPromotionsPerLoop;
314
315 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
316 return 0;
317
318 // Whether the target block is in a loop does not matter:
319 if (SpeculativeCounterPromotionToLoop)
320 return MaxNumOfPromotionsPerLoop;
321
322 // Now check the target block:
323 unsigned MaxProm = MaxNumOfPromotionsPerLoop;
324 for (auto *TargetBlock : LoopExitBlocks) {
325 auto *TargetLoop = LI.getLoopFor(TargetBlock);
326 if (!TargetLoop)
327 continue;
328 unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
329 unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
330 MaxProm =
331 std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
332 PendingCandsInTarget);
333 }
334 return MaxProm;
335 }
336
337 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000338 SmallVector<BasicBlock *, 8> ExitBlocks;
339 SmallVector<Instruction *, 8> InsertPts;
Xinliang David Lif564c692017-07-12 23:27:44 +0000340 Loop &L;
341 LoopInfo &LI;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000342};
343
Eugene Zelenko34c23272017-01-18 00:57:48 +0000344} // end anonymous namespace
Justin Bogner61ba2e32014-12-08 18:02:35 +0000345
Sean Silvafd03ac62016-08-09 00:28:38 +0000346PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000347 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
348 if (!run(M, TLI))
Xinliang David Lie6b89292016-04-18 17:47:38 +0000349 return PreservedAnalyses::all();
350
351 return PreservedAnalyses::none();
352}
353
354char InstrProfilingLegacyPass::ID = 0;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000355INITIALIZE_PASS_BEGIN(
356 InstrProfilingLegacyPass, "instrprof",
357 "Frontend instrumentation-based coverage lowering.", false, false)
358INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
359INITIALIZE_PASS_END(
360 InstrProfilingLegacyPass, "instrprof",
361 "Frontend instrumentation-based coverage lowering.", false, false)
Justin Bogner61ba2e32014-12-08 18:02:35 +0000362
Xinliang David Li69a00f02016-06-21 02:39:08 +0000363ModulePass *
364llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
Xinliang David Lie6b89292016-04-18 17:47:38 +0000365 return new InstrProfilingLegacyPass(Options);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000366}
367
Xinliang David Li4ca17332016-09-18 18:34:07 +0000368static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
369 InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
370 if (Inc)
371 return Inc;
372 return dyn_cast<InstrProfIncrementInst>(Instr);
373}
374
Xinliang David Lib67530e2017-06-25 00:26:43 +0000375bool InstrProfiling::lowerIntrinsics(Function *F) {
376 bool MadeChange = false;
377 PromotionCandidates.clear();
378 for (BasicBlock &BB : *F) {
379 for (auto I = BB.begin(), E = BB.end(); I != E;) {
380 auto Instr = I++;
381 InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
382 if (Inc) {
383 lowerIncrement(Inc);
384 MadeChange = true;
385 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
386 lowerValueProfileInst(Ind);
387 MadeChange = true;
388 }
389 }
390 }
391
392 if (!MadeChange)
393 return false;
394
395 promoteCounterLoadStores(F);
396 return true;
397}
398
399bool InstrProfiling::isCounterPromotionEnabled() const {
400 if (DoCounterPromotion.getNumOccurrences() > 0)
401 return DoCounterPromotion;
402
403 return Options.DoCounterPromotion;
404}
405
406void InstrProfiling::promoteCounterLoadStores(Function *F) {
407 if (!isCounterPromotionEnabled())
408 return;
409
410 DominatorTree DT(*F);
411 LoopInfo LI(DT);
412 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
413
414 for (const auto &LoadStore : PromotionCandidates) {
415 auto *CounterLoad = LoadStore.first;
416 auto *CounterStore = LoadStore.second;
417 BasicBlock *BB = CounterLoad->getParent();
418 Loop *ParentLoop = LI.getLoopFor(BB);
419 if (!ParentLoop)
420 continue;
421 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
422 }
423
424 SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
425
Xinliang David Lif564c692017-07-12 23:27:44 +0000426 // Do a post-order traversal of the loops so that counter updates can be
427 // iteratively hoisted outside the loop nest.
428 for (auto *Loop : llvm::reverse(Loops)) {
429 PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000430 Promoter.run(&TotalCountersPromoted);
431 }
432}
433
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000434bool InstrProfiling::run(Module &M, const TargetLibraryInfo &TLI) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000435 bool MadeChange = false;
436
437 this->M = &M;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000438 this->TLI = &TLI;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000439 NamesVar = nullptr;
440 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000441 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000442 UsedVars.clear();
Rong Xu48596b62017-04-04 16:42:20 +0000443 getMemOPSizeRangeFromOption(MemOPSizeRange, MemOPSizeRangeStart,
444 MemOPSizeRangeLast);
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000445 TT = Triple(M.getTargetTriple());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000446
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000447 // We did not know how many value sites there would be inside
448 // the instrumented function. This is counting the number of instrumented
449 // target value sites to enter it as field in the profile data variable.
Rong Xu294572f2016-01-19 18:29:54 +0000450 for (Function &F : M) {
451 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000452 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000453 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
454 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000455 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000456 else if (FirstProfIncInst == nullptr)
457 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
458
459 // Value profiling intrinsic lowering requires per-function profile data
460 // variable to be created first.
461 if (FirstProfIncInst != nullptr)
462 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
463 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000464
465 for (Function &F : M)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000466 MadeChange |= lowerIntrinsics(&F);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000467
Xinliang David Li81056072016-01-07 20:05:49 +0000468 if (GlobalVariable *CoverageNamesVar =
Xinliang David Li440cd702016-01-20 00:24:36 +0000469 M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
Xinliang David Li81056072016-01-07 20:05:49 +0000470 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000471 MadeChange = true;
472 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000473
Justin Bogner61ba2e32014-12-08 18:02:35 +0000474 if (!MadeChange)
475 return false;
476
Xinliang David Lib628dd32016-05-21 22:55:34 +0000477 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000478 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000479 emitRegistration();
480 emitRuntimeHook();
481 emitUses();
482 emitInitialization();
483 return true;
484}
485
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000486static Constant *getOrInsertValueProfilingCall(Module &M,
Rong Xu60faea12017-03-16 21:15:48 +0000487 const TargetLibraryInfo &TLI,
488 bool IsRange = false) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000489 LLVMContext &Ctx = M.getContext();
490 auto *ReturnTy = Type::getVoidTy(M.getContext());
Rong Xu60faea12017-03-16 21:15:48 +0000491
492 Constant *Res;
493 if (!IsRange) {
494 Type *ParamTypes[] = {
Xinliang David Lic7673232015-11-22 00:22:07 +0000495#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
496#include "llvm/ProfileData/InstrProfData.inc"
Rong Xu60faea12017-03-16 21:15:48 +0000497 };
498 auto *ValueProfilingCallTy =
499 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
500 Res = M.getOrInsertFunction(getInstrProfValueProfFuncName(),
501 ValueProfilingCallTy);
502 } else {
503 Type *RangeParamTypes[] = {
504#define VALUE_RANGE_PROF 1
505#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
506#include "llvm/ProfileData/InstrProfData.inc"
507#undef VALUE_RANGE_PROF
508 };
509 auto *ValueRangeProfilingCallTy =
510 FunctionType::get(ReturnTy, makeArrayRef(RangeParamTypes), false);
511 Res = M.getOrInsertFunction(getInstrProfValueRangeProfFuncName(),
512 ValueRangeProfilingCallTy);
513 }
514
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000515 if (Function *FunRes = dyn_cast<Function>(Res)) {
516 if (auto AK = TLI.getExtAttrForI32Param(false))
Reid Klecknera0b45f42017-05-03 18:17:31 +0000517 FunRes->addParamAttr(2, AK);
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000518 }
519 return Res;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000520}
521
522void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000523 GlobalVariable *Name = Ind->getName();
524 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
525 uint64_t Index = Ind->getIndex()->getZExtValue();
526 auto It = ProfileDataMap.find(Name);
527 if (It == ProfileDataMap.end()) {
528 PerFunctionProfileData PD;
529 PD.NumValueSites[ValueKind] = Index + 1;
530 ProfileDataMap[Name] = PD;
531 } else if (It->second.NumValueSites[ValueKind] <= Index)
532 It->second.NumValueSites[ValueKind] = Index + 1;
533}
534
535void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000536 GlobalVariable *Name = Ind->getName();
537 auto It = ProfileDataMap.find(Name);
538 assert(It != ProfileDataMap.end() && It->second.DataVar &&
Xinliang David Li69a00f02016-06-21 02:39:08 +0000539 "value profiling detected in function with no counter incerement");
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000540
541 GlobalVariable *DataVar = It->second.DataVar;
542 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
543 uint64_t Index = Ind->getIndex()->getZExtValue();
544 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
545 Index += It->second.NumValueSites[Kind];
546
547 IRBuilder<> Builder(Ind);
Rong Xu60faea12017-03-16 21:15:48 +0000548 bool IsRange = (Ind->getValueKind()->getZExtValue() ==
549 llvm::InstrProfValueKind::IPVK_MemOPSize);
550 CallInst *Call = nullptr;
551 if (!IsRange) {
552 Value *Args[3] = {Ind->getTargetValue(),
553 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
554 Builder.getInt32(Index)};
555 Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args);
556 } else {
Rong Xu48596b62017-04-04 16:42:20 +0000557 Value *Args[6] = {
558 Ind->getTargetValue(),
559 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
560 Builder.getInt32(Index),
561 Builder.getInt64(MemOPSizeRangeStart),
562 Builder.getInt64(MemOPSizeRangeLast),
563 Builder.getInt64(MemOPSizeLarge == 0 ? INT64_MIN : MemOPSizeLarge)};
Rong Xu60faea12017-03-16 21:15:48 +0000564 Call =
565 Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI, true), Args);
566 }
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000567 if (auto AK = TLI->getExtAttrForI32Param(false))
Reid Klecknera0b45f42017-05-03 18:17:31 +0000568 Call->addParamAttr(2, AK);
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000569 Ind->replaceAllUsesWith(Call);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000570 Ind->eraseFromParent();
571}
572
Justin Bogner61ba2e32014-12-08 18:02:35 +0000573void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
574 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
575
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000576 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000577 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000578 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000579 Value *Load = Builder.CreateLoad(Addr, "pgocount");
580 auto *Count = Builder.CreateAdd(Load, Inc->getStep());
581 auto *Store = Builder.CreateStore(Count, Addr);
582 Inc->replaceAllUsesWith(Store);
583 if (isCounterPromotionEnabled())
584 PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000585 Inc->eraseFromParent();
586}
587
Xinliang David Li81056072016-01-07 20:05:49 +0000588void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Xinliang David Li81056072016-01-07 20:05:49 +0000589 ConstantArray *Names =
590 cast<ConstantArray>(CoverageNamesVar->getInitializer());
591 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
592 Constant *NC = Names->getOperand(I);
593 Value *V = NC->stripPointerCasts();
Justin Bognerd24e1852015-02-11 02:52:44 +0000594 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
595 GlobalVariable *Name = cast<GlobalVariable>(V);
596
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000597 Name->setLinkage(GlobalValue::PrivateLinkage);
598 ReferencedNames.push_back(Name);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000599 NC->dropAllReferences();
Justin Bognerd24e1852015-02-11 02:52:44 +0000600 }
Vedant Kumar55891fc2017-02-14 20:03:48 +0000601 CoverageNamesVar->eraseFromParent();
Justin Bognerd24e1852015-02-11 02:52:44 +0000602}
603
Justin Bogner61ba2e32014-12-08 18:02:35 +0000604/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000605static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000606 StringRef NamePrefix = getInstrProfNameVarPrefix();
607 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Rong Xu20f5df12017-01-11 20:19:41 +0000608 Function *F = Inc->getParent()->getParent();
609 Module *M = F->getParent();
610 if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
611 !canRenameComdatFunc(*F))
612 return (Prefix + Name).str();
613 uint64_t FuncHash = Inc->getHash()->getZExtValue();
614 SmallVector<char, 24> HashPostfix;
615 if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
616 return (Prefix + Name).str();
617 return (Prefix + Name + "." + Twine(FuncHash)).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000618}
619
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000620static inline bool shouldRecordFunctionAddr(Function *F) {
621 // Check the linkage
Vedant Kumar9c056c92017-06-13 22:12:35 +0000622 bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000623 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
Vedant Kumar9c056c92017-06-13 22:12:35 +0000624 !HasAvailableExternallyLinkage)
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000625 return true;
Vedant Kumar9c056c92017-06-13 22:12:35 +0000626
627 // A function marked 'alwaysinline' with available_externally linkage can't
628 // have its address taken. Doing so would create an undefined external ref to
629 // the function, which would fail to link.
630 if (HasAvailableExternallyLinkage &&
631 F->hasFnAttribute(Attribute::AlwaysInline))
632 return false;
633
Rong Xuaf5aeba2016-04-27 21:17:30 +0000634 // Prohibit function address recording if the function is both internal and
635 // COMDAT. This avoids the profile data variable referencing internal symbols
636 // in COMDAT.
637 if (F->hasLocalLinkage() && F->hasComdat())
638 return false;
Vedant Kumar9c056c92017-06-13 22:12:35 +0000639
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000640 // Check uses of this function for other than direct calls or invokes to it.
Xinliang David Li7008ce32016-06-02 16:33:41 +0000641 // Inline virtual functions have linkeOnceODR linkage. When a key method
642 // exists, the vtable will only be emitted in the TU where the key method
643 // is defined. In a TU where vtable is not available, the function won't
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000644 // be 'addresstaken'. If its address is not recorded here, the profile data
Xinliang David Li69a00f02016-06-21 02:39:08 +0000645 // with missing address may be picked by the linker leading to missing
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000646 // indirect call target info.
647 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000648}
649
Xinliang David Li985ff202016-02-27 23:11:30 +0000650static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000651 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000652 if (!needsComdatForCounter(F, M))
653 return nullptr;
654
Xinliang David Liab361ef2015-12-21 21:52:27 +0000655 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000656 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000657 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000658 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000659 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000660 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000661 : getInstrProfComdatPrefix());
662 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
663}
664
Xinliang David Lib628dd32016-05-21 22:55:34 +0000665static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
666 // Don't do this for Darwin. compiler-rt uses linker magic.
667 if (Triple(M.getTargetTriple()).isOSDarwin())
668 return false;
669
670 // Use linker script magic to get data/cnts/name start/end.
671 if (Triple(M.getTargetTriple()).isOSLinux() ||
672 Triple(M.getTargetTriple()).isOSFreeBSD() ||
673 Triple(M.getTargetTriple()).isPS4CPU())
674 return false;
675
676 return true;
677}
678
Justin Bogner61ba2e32014-12-08 18:02:35 +0000679GlobalVariable *
680InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000681 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000682 auto It = ProfileDataMap.find(NamePtr);
683 PerFunctionProfileData PD;
684 if (It != ProfileDataMap.end()) {
685 if (It->second.RegionCounters)
686 return It->second.RegionCounters;
687 PD = It->second;
688 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000689
Wei Mi3cc92042015-09-23 22:40:45 +0000690 // Move the name variable to the right section. Place them in a COMDAT group
691 // if the associated function is a COMDAT. This will make sure that
692 // only one copy of counters of the COMDAT function will be emitted after
693 // linking.
Diego Novillodf4837b2015-05-27 19:34:01 +0000694 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000695 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000696 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000697
698 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
699 LLVMContext &Ctx = M->getContext();
700 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
701
702 // Create the counters variable.
Xinliang David Li192c7482015-11-05 00:47:26 +0000703 auto *CounterPtr =
704 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000705 Constant::getNullValue(CounterTy),
706 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000707 CounterPtr->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000708 CounterPtr->setSection(
709 getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000710 CounterPtr->setAlignment(8);
711 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000712
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000713 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000714 // Allocate statically the array of pointers to value profile nodes for
715 // the current function.
716 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
717 if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
Xinliang David Lib628dd32016-05-21 22:55:34 +0000718 uint64_t NS = 0;
719 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
720 NS += PD.NumValueSites[Kind];
721 if (NS) {
722 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
723
724 auto *ValuesVar =
725 new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
726 Constant::getNullValue(ValuesTy),
727 getVarName(Inc, getInstrProfValuesVarPrefix()));
728 ValuesVar->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000729 ValuesVar->setSection(
730 getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000731 ValuesVar->setAlignment(8);
732 ValuesVar->setComdat(ProfileVarsComdat);
733 ValuesPtrExpr =
Eugene Zelenko34c23272017-01-18 00:57:48 +0000734 ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000735 }
736 }
737
738 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000739 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000740 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000741 Type *DataTypes[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000742#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
743#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000744 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000745 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000746
Xinliang David Li69a00f02016-06-21 02:39:08 +0000747 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
748 ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
749 : ConstantPointerNull::get(Int8PtrTy);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000750
Xinliang David Li69a00f02016-06-21 02:39:08 +0000751 Constant *Int16ArrayVals[IPVK_Last + 1];
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000752 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
753 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
754
Justin Bogner61ba2e32014-12-08 18:02:35 +0000755 Constant *DataVals[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000756#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
757#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000758 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000759 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000760 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000761 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000762 Data->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000763 Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000764 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000765 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000766
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000767 PD.RegionCounters = CounterPtr;
768 PD.DataVar = Data;
769 ProfileDataMap[NamePtr] = PD;
770
Justin Bogner61ba2e32014-12-08 18:02:35 +0000771 // Mark the data variable as used so that it isn't stripped out.
772 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000773 // Now that the linkage set by the FE has been passed to the data and counter
774 // variables, reset Name variable's linkage and visibility to private so that
775 // it can be removed later by the compiler.
776 NamePtr->setLinkage(GlobalValue::PrivateLinkage);
777 // Collect the referenced names to be used by emitNameData.
778 ReferencedNames.push_back(NamePtr);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000779
Xinliang David Li192c7482015-11-05 00:47:26 +0000780 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000781}
782
Xinliang David Lib628dd32016-05-21 22:55:34 +0000783void InstrProfiling::emitVNodes() {
784 if (!ValueProfileStaticAlloc)
785 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000786
Xinliang David Lib628dd32016-05-21 22:55:34 +0000787 // For now only support this on platforms that do
788 // not require runtime registration to discover
789 // named section start/end.
790 if (needsRuntimeRegistrationOfSectionRange(*M))
791 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000792
Xinliang David Lib628dd32016-05-21 22:55:34 +0000793 size_t TotalNS = 0;
794 for (auto &PD : ProfileDataMap) {
795 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
796 TotalNS += PD.second.NumValueSites[Kind];
797 }
798
799 if (!TotalNS)
800 return;
801
802 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
Xinliang David Li69a00f02016-06-21 02:39:08 +0000803// Heuristic for small programs with very few total value sites.
804// The default value of vp-counters-per-site is chosen based on
805// the observation that large apps usually have a low percentage
806// of value sites that actually have any profile data, and thus
807// the average number of counters per site is low. For small
808// apps with very few sites, this may not be true. Bump up the
809// number of counters in this case.
Xinliang David Lie4520762016-05-23 19:29:26 +0000810#define INSTR_PROF_MIN_VAL_COUNTS 10
811 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000812 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000813
814 auto &Ctx = M->getContext();
815 Type *VNodeTypes[] = {
816#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
817#include "llvm/ProfileData/InstrProfData.inc"
818 };
819 auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
820
821 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
822 auto *VNodesVar = new GlobalVariable(
Eugene Zelenko34c23272017-01-18 00:57:48 +0000823 *M, VNodesTy, false, GlobalValue::PrivateLinkage,
Xinliang David Lib628dd32016-05-21 22:55:34 +0000824 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000825 VNodesVar->setSection(
826 getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000827 UsedVars.push_back(VNodesVar);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000828}
829
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000830void InstrProfiling::emitNameData() {
831 std::string UncompressedData;
832
833 if (ReferencedNames.empty())
834 return;
835
836 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000837 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000838 DoNameCompression)) {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000839 report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000840 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000841
842 auto &Ctx = M->getContext();
Eugene Zelenko34c23272017-01-18 00:57:48 +0000843 auto *NamesVal = ConstantDataArray::getString(
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000844 Ctx, StringRef(CompressedNameStr), false);
Eugene Zelenko34c23272017-01-18 00:57:48 +0000845 NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
846 GlobalValue::PrivateLinkage, NamesVal,
847 getInstrProfNamesVarName());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000848 NamesSize = CompressedNameStr.size();
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000849 NamesVar->setSection(
850 getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000851 UsedVars.push_back(NamesVar);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000852
853 for (auto *NamePtr : ReferencedNames)
854 NamePtr->eraseFromParent();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000855}
856
Justin Bogner61ba2e32014-12-08 18:02:35 +0000857void InstrProfiling::emitRegistration() {
Xinliang David Li8da773b2016-05-17 20:19:03 +0000858 if (!needsRuntimeRegistrationOfSectionRange(*M))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000859 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000860
Justin Bogner61ba2e32014-12-08 18:02:35 +0000861 // Construct the function.
862 auto *VoidTy = Type::getVoidTy(M->getContext());
863 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000864 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000865 auto *RegisterFTy = FunctionType::get(VoidTy, false);
866 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000867 getInstrProfRegFuncsName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000868 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000869 if (Options.NoRedZone)
870 RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000871
Diego Novillob3029d22015-06-04 11:45:32 +0000872 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000873 auto *RuntimeRegisterF =
874 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000875 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000876
877 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
878 for (Value *Data : UsedVars)
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000879 if (Data != NamesVar)
880 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
881
882 if (NamesVar) {
883 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
884 auto *NamesRegisterTy =
885 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
886 auto *NamesRegisterF =
887 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
888 getInstrProfNamesRegFuncName(), M);
889 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
890 IRB.getInt64(NamesSize)});
891 }
892
Justin Bogner61ba2e32014-12-08 18:02:35 +0000893 IRB.CreateRetVoid();
894}
895
896void InstrProfiling::emitRuntimeHook() {
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000897 // We expect the linker to be invoked with -u<hook_var> flag for linux,
898 // for which case there is no need to emit the user function.
899 if (Triple(M->getTargetTriple()).isOSLinux())
900 return;
901
Justin Bogner61ba2e32014-12-08 18:02:35 +0000902 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li69a00f02016-06-21 02:39:08 +0000903 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
904 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000905
906 // Declare an external variable that will pull in the runtime initialization.
907 auto *Int32Ty = Type::getInt32Ty(M->getContext());
908 auto *Var =
909 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000910 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000911
912 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000913 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
914 GlobalValue::LinkOnceODRLinkage,
915 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000916 User->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000917 if (Options.NoRedZone)
918 User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000919 User->setVisibility(GlobalValue::HiddenVisibility);
Xinliang David Lia2286082016-05-25 17:17:51 +0000920 if (Triple(M->getTargetTriple()).supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +0000921 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000922
923 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
924 auto *Load = IRB.CreateLoad(Var);
925 IRB.CreateRet(Load);
926
927 // Mark the user variable as used so that it isn't stripped out.
928 UsedVars.push_back(User);
929}
930
931void InstrProfiling::emitUses() {
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000932 if (!UsedVars.empty())
933 appendToUsed(*M, UsedVars);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000934}
935
936void InstrProfiling::emitInitialization() {
Vedant Kumarcd32eba2016-07-21 17:50:07 +0000937 StringRef InstrProfileOutput = Options.InstrProfileOutput;
Justin Bognerba1900c2015-04-30 23:49:23 +0000938
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000939 if (!InstrProfileOutput.empty()) {
940 // Create variable for profile name.
941 Constant *ProfileNameConst =
942 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
943 GlobalVariable *ProfileNameVar = new GlobalVariable(
944 *M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
945 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000946 if (TT.supportsCOMDAT()) {
947 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
948 ProfileNameVar->setComdat(M->getOrInsertComdat(
949 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
950 }
951 }
952
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000953 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000954 if (!RegisterF)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000955 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000956
957 // Create the initialization function.
958 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000959 auto *F = Function::Create(FunctionType::get(VoidTy, false),
960 GlobalValue::InternalLinkage,
961 getInstrProfInitFuncName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000962 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000963 F->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000964 if (Options.NoRedZone)
965 F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000966
967 // Add the basic block and the necessary calls.
968 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000969 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000970 IRB.CreateCall(RegisterF, {});
Justin Bogner61ba2e32014-12-08 18:02:35 +0000971 IRB.CreateRetVoid();
972
973 appendToGlobalCtors(*M, F, 0);
974}