blob: db8fa897794793a9194ffc683e409d32eb228665 [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 Lif564c692017-07-12 23:27:44 +0000248 unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
249 if (MaxProm == 0)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000250 return false;
251
252 unsigned Promoted = 0;
Xinliang David Lif564c692017-07-12 23:27:44 +0000253 for (auto &Cand : LoopToCandidates[&L]) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000254
255 SmallVector<PHINode *, 4> NewPHIs;
256 SSAUpdater SSA(&NewPHIs);
257 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
Xinliang David Lif564c692017-07-12 23:27:44 +0000258
Xinliang David Lib67530e2017-06-25 00:26:43 +0000259 PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
Xinliang David Lif564c692017-07-12 23:27:44 +0000260 L.getLoopPreheader(), ExitBlocks,
261 InsertPts, LoopToCandidates, LI);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000262 Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
263 Promoted++;
Xinliang David Lif564c692017-07-12 23:27:44 +0000264 if (Promoted >= MaxProm)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000265 break;
Xinliang David Lif564c692017-07-12 23:27:44 +0000266
Xinliang David Lib67530e2017-06-25 00:26:43 +0000267 (*NumPromoted)++;
268 if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
269 break;
270 }
271
272 DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
Xinliang David Lif564c692017-07-12 23:27:44 +0000273 << L.getLoopDepth() << ")\n");
Xinliang David Lib67530e2017-06-25 00:26:43 +0000274 return Promoted != 0;
275 }
276
277private:
Xinliang David Lif564c692017-07-12 23:27:44 +0000278 bool allowSpeculativeCounterPromotion(Loop *LP) {
279 SmallVector<BasicBlock *, 8> ExitingBlocks;
280 L.getExitingBlocks(ExitingBlocks);
281 // Not considierered speculative.
282 if (ExitingBlocks.size() == 1)
283 return true;
284 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
285 return false;
286 return true;
287 }
288
289 // Returns the max number of Counter Promotions for LP.
290 unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
291 // We can't insert into a catchswitch.
292 SmallVector<BasicBlock *, 8> LoopExitBlocks;
293 LP->getExitBlocks(LoopExitBlocks);
294 if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
295 return isa<CatchSwitchInst>(Exit->getTerminator());
296 }))
297 return 0;
298
299 if (!LP->hasDedicatedExits())
300 return 0;
301
302 BasicBlock *PH = LP->getLoopPreheader();
303 if (!PH)
304 return 0;
305
306 SmallVector<BasicBlock *, 8> ExitingBlocks;
307 LP->getExitingBlocks(ExitingBlocks);
308 // Not considierered speculative.
309 if (ExitingBlocks.size() == 1)
310 return MaxNumOfPromotionsPerLoop;
311
312 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
313 return 0;
314
315 // Whether the target block is in a loop does not matter:
316 if (SpeculativeCounterPromotionToLoop)
317 return MaxNumOfPromotionsPerLoop;
318
319 // Now check the target block:
320 unsigned MaxProm = MaxNumOfPromotionsPerLoop;
321 for (auto *TargetBlock : LoopExitBlocks) {
322 auto *TargetLoop = LI.getLoopFor(TargetBlock);
323 if (!TargetLoop)
324 continue;
325 unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
326 unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
327 MaxProm =
328 std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
329 PendingCandsInTarget);
330 }
331 return MaxProm;
332 }
333
334 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000335 SmallVector<BasicBlock *, 8> ExitBlocks;
336 SmallVector<Instruction *, 8> InsertPts;
Xinliang David Lif564c692017-07-12 23:27:44 +0000337 Loop &L;
338 LoopInfo &LI;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000339};
340
Eugene Zelenko34c23272017-01-18 00:57:48 +0000341} // end anonymous namespace
Justin Bogner61ba2e32014-12-08 18:02:35 +0000342
Sean Silvafd03ac62016-08-09 00:28:38 +0000343PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000344 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
345 if (!run(M, TLI))
Xinliang David Lie6b89292016-04-18 17:47:38 +0000346 return PreservedAnalyses::all();
347
348 return PreservedAnalyses::none();
349}
350
351char InstrProfilingLegacyPass::ID = 0;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000352INITIALIZE_PASS_BEGIN(
353 InstrProfilingLegacyPass, "instrprof",
354 "Frontend instrumentation-based coverage lowering.", false, false)
355INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
356INITIALIZE_PASS_END(
357 InstrProfilingLegacyPass, "instrprof",
358 "Frontend instrumentation-based coverage lowering.", false, false)
Justin Bogner61ba2e32014-12-08 18:02:35 +0000359
Xinliang David Li69a00f02016-06-21 02:39:08 +0000360ModulePass *
361llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
Xinliang David Lie6b89292016-04-18 17:47:38 +0000362 return new InstrProfilingLegacyPass(Options);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000363}
364
Xinliang David Li4ca17332016-09-18 18:34:07 +0000365static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
366 InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
367 if (Inc)
368 return Inc;
369 return dyn_cast<InstrProfIncrementInst>(Instr);
370}
371
Xinliang David Lib67530e2017-06-25 00:26:43 +0000372bool InstrProfiling::lowerIntrinsics(Function *F) {
373 bool MadeChange = false;
374 PromotionCandidates.clear();
375 for (BasicBlock &BB : *F) {
376 for (auto I = BB.begin(), E = BB.end(); I != E;) {
377 auto Instr = I++;
378 InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
379 if (Inc) {
380 lowerIncrement(Inc);
381 MadeChange = true;
382 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
383 lowerValueProfileInst(Ind);
384 MadeChange = true;
385 }
386 }
387 }
388
389 if (!MadeChange)
390 return false;
391
392 promoteCounterLoadStores(F);
393 return true;
394}
395
396bool InstrProfiling::isCounterPromotionEnabled() const {
397 if (DoCounterPromotion.getNumOccurrences() > 0)
398 return DoCounterPromotion;
399
400 return Options.DoCounterPromotion;
401}
402
403void InstrProfiling::promoteCounterLoadStores(Function *F) {
404 if (!isCounterPromotionEnabled())
405 return;
406
407 DominatorTree DT(*F);
408 LoopInfo LI(DT);
409 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
410
411 for (const auto &LoadStore : PromotionCandidates) {
412 auto *CounterLoad = LoadStore.first;
413 auto *CounterStore = LoadStore.second;
414 BasicBlock *BB = CounterLoad->getParent();
415 Loop *ParentLoop = LI.getLoopFor(BB);
416 if (!ParentLoop)
417 continue;
418 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
419 }
420
421 SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
422
Xinliang David Lif564c692017-07-12 23:27:44 +0000423 // Do a post-order traversal of the loops so that counter updates can be
424 // iteratively hoisted outside the loop nest.
425 for (auto *Loop : llvm::reverse(Loops)) {
426 PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000427 Promoter.run(&TotalCountersPromoted);
428 }
429}
430
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000431bool InstrProfiling::run(Module &M, const TargetLibraryInfo &TLI) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000432 bool MadeChange = false;
433
434 this->M = &M;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000435 this->TLI = &TLI;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000436 NamesVar = nullptr;
437 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000438 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000439 UsedVars.clear();
Rong Xu48596b62017-04-04 16:42:20 +0000440 getMemOPSizeRangeFromOption(MemOPSizeRange, MemOPSizeRangeStart,
441 MemOPSizeRangeLast);
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000442 TT = Triple(M.getTargetTriple());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000443
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000444 // We did not know how many value sites there would be inside
445 // the instrumented function. This is counting the number of instrumented
446 // target value sites to enter it as field in the profile data variable.
Rong Xu294572f2016-01-19 18:29:54 +0000447 for (Function &F : M) {
448 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000449 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000450 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
451 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000452 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000453 else if (FirstProfIncInst == nullptr)
454 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
455
456 // Value profiling intrinsic lowering requires per-function profile data
457 // variable to be created first.
458 if (FirstProfIncInst != nullptr)
459 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
460 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000461
462 for (Function &F : M)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000463 MadeChange |= lowerIntrinsics(&F);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000464
Xinliang David Li81056072016-01-07 20:05:49 +0000465 if (GlobalVariable *CoverageNamesVar =
Xinliang David Li440cd702016-01-20 00:24:36 +0000466 M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
Xinliang David Li81056072016-01-07 20:05:49 +0000467 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000468 MadeChange = true;
469 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000470
Justin Bogner61ba2e32014-12-08 18:02:35 +0000471 if (!MadeChange)
472 return false;
473
Xinliang David Lib628dd32016-05-21 22:55:34 +0000474 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000475 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000476 emitRegistration();
477 emitRuntimeHook();
478 emitUses();
479 emitInitialization();
480 return true;
481}
482
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000483static Constant *getOrInsertValueProfilingCall(Module &M,
Rong Xu60faea12017-03-16 21:15:48 +0000484 const TargetLibraryInfo &TLI,
485 bool IsRange = false) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000486 LLVMContext &Ctx = M.getContext();
487 auto *ReturnTy = Type::getVoidTy(M.getContext());
Rong Xu60faea12017-03-16 21:15:48 +0000488
489 Constant *Res;
490 if (!IsRange) {
491 Type *ParamTypes[] = {
Xinliang David Lic7673232015-11-22 00:22:07 +0000492#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
493#include "llvm/ProfileData/InstrProfData.inc"
Rong Xu60faea12017-03-16 21:15:48 +0000494 };
495 auto *ValueProfilingCallTy =
496 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
497 Res = M.getOrInsertFunction(getInstrProfValueProfFuncName(),
498 ValueProfilingCallTy);
499 } else {
500 Type *RangeParamTypes[] = {
501#define VALUE_RANGE_PROF 1
502#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
503#include "llvm/ProfileData/InstrProfData.inc"
504#undef VALUE_RANGE_PROF
505 };
506 auto *ValueRangeProfilingCallTy =
507 FunctionType::get(ReturnTy, makeArrayRef(RangeParamTypes), false);
508 Res = M.getOrInsertFunction(getInstrProfValueRangeProfFuncName(),
509 ValueRangeProfilingCallTy);
510 }
511
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000512 if (Function *FunRes = dyn_cast<Function>(Res)) {
513 if (auto AK = TLI.getExtAttrForI32Param(false))
Reid Klecknera0b45f42017-05-03 18:17:31 +0000514 FunRes->addParamAttr(2, AK);
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000515 }
516 return Res;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000517}
518
519void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000520 GlobalVariable *Name = Ind->getName();
521 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
522 uint64_t Index = Ind->getIndex()->getZExtValue();
523 auto It = ProfileDataMap.find(Name);
524 if (It == ProfileDataMap.end()) {
525 PerFunctionProfileData PD;
526 PD.NumValueSites[ValueKind] = Index + 1;
527 ProfileDataMap[Name] = PD;
528 } else if (It->second.NumValueSites[ValueKind] <= Index)
529 It->second.NumValueSites[ValueKind] = Index + 1;
530}
531
532void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000533 GlobalVariable *Name = Ind->getName();
534 auto It = ProfileDataMap.find(Name);
535 assert(It != ProfileDataMap.end() && It->second.DataVar &&
Xinliang David Li69a00f02016-06-21 02:39:08 +0000536 "value profiling detected in function with no counter incerement");
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000537
538 GlobalVariable *DataVar = It->second.DataVar;
539 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
540 uint64_t Index = Ind->getIndex()->getZExtValue();
541 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
542 Index += It->second.NumValueSites[Kind];
543
544 IRBuilder<> Builder(Ind);
Rong Xu60faea12017-03-16 21:15:48 +0000545 bool IsRange = (Ind->getValueKind()->getZExtValue() ==
546 llvm::InstrProfValueKind::IPVK_MemOPSize);
547 CallInst *Call = nullptr;
548 if (!IsRange) {
549 Value *Args[3] = {Ind->getTargetValue(),
550 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
551 Builder.getInt32(Index)};
552 Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args);
553 } else {
Rong Xu48596b62017-04-04 16:42:20 +0000554 Value *Args[6] = {
555 Ind->getTargetValue(),
556 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
557 Builder.getInt32(Index),
558 Builder.getInt64(MemOPSizeRangeStart),
559 Builder.getInt64(MemOPSizeRangeLast),
560 Builder.getInt64(MemOPSizeLarge == 0 ? INT64_MIN : MemOPSizeLarge)};
Rong Xu60faea12017-03-16 21:15:48 +0000561 Call =
562 Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI, true), Args);
563 }
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000564 if (auto AK = TLI->getExtAttrForI32Param(false))
Reid Klecknera0b45f42017-05-03 18:17:31 +0000565 Call->addParamAttr(2, AK);
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000566 Ind->replaceAllUsesWith(Call);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000567 Ind->eraseFromParent();
568}
569
Justin Bogner61ba2e32014-12-08 18:02:35 +0000570void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
571 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
572
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000573 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000574 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000575 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000576 Value *Load = Builder.CreateLoad(Addr, "pgocount");
577 auto *Count = Builder.CreateAdd(Load, Inc->getStep());
578 auto *Store = Builder.CreateStore(Count, Addr);
579 Inc->replaceAllUsesWith(Store);
580 if (isCounterPromotionEnabled())
581 PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000582 Inc->eraseFromParent();
583}
584
Xinliang David Li81056072016-01-07 20:05:49 +0000585void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Xinliang David Li81056072016-01-07 20:05:49 +0000586 ConstantArray *Names =
587 cast<ConstantArray>(CoverageNamesVar->getInitializer());
588 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
589 Constant *NC = Names->getOperand(I);
590 Value *V = NC->stripPointerCasts();
Justin Bognerd24e1852015-02-11 02:52:44 +0000591 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
592 GlobalVariable *Name = cast<GlobalVariable>(V);
593
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000594 Name->setLinkage(GlobalValue::PrivateLinkage);
595 ReferencedNames.push_back(Name);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000596 NC->dropAllReferences();
Justin Bognerd24e1852015-02-11 02:52:44 +0000597 }
Vedant Kumar55891fc2017-02-14 20:03:48 +0000598 CoverageNamesVar->eraseFromParent();
Justin Bognerd24e1852015-02-11 02:52:44 +0000599}
600
Justin Bogner61ba2e32014-12-08 18:02:35 +0000601/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000602static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000603 StringRef NamePrefix = getInstrProfNameVarPrefix();
604 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Rong Xu20f5df12017-01-11 20:19:41 +0000605 Function *F = Inc->getParent()->getParent();
606 Module *M = F->getParent();
607 if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
608 !canRenameComdatFunc(*F))
609 return (Prefix + Name).str();
610 uint64_t FuncHash = Inc->getHash()->getZExtValue();
611 SmallVector<char, 24> HashPostfix;
612 if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
613 return (Prefix + Name).str();
614 return (Prefix + Name + "." + Twine(FuncHash)).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000615}
616
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000617static inline bool shouldRecordFunctionAddr(Function *F) {
618 // Check the linkage
Vedant Kumar9c056c92017-06-13 22:12:35 +0000619 bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000620 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
Vedant Kumar9c056c92017-06-13 22:12:35 +0000621 !HasAvailableExternallyLinkage)
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000622 return true;
Vedant Kumar9c056c92017-06-13 22:12:35 +0000623
624 // A function marked 'alwaysinline' with available_externally linkage can't
625 // have its address taken. Doing so would create an undefined external ref to
626 // the function, which would fail to link.
627 if (HasAvailableExternallyLinkage &&
628 F->hasFnAttribute(Attribute::AlwaysInline))
629 return false;
630
Rong Xuaf5aeba2016-04-27 21:17:30 +0000631 // Prohibit function address recording if the function is both internal and
632 // COMDAT. This avoids the profile data variable referencing internal symbols
633 // in COMDAT.
634 if (F->hasLocalLinkage() && F->hasComdat())
635 return false;
Vedant Kumar9c056c92017-06-13 22:12:35 +0000636
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000637 // Check uses of this function for other than direct calls or invokes to it.
Xinliang David Li7008ce32016-06-02 16:33:41 +0000638 // Inline virtual functions have linkeOnceODR linkage. When a key method
639 // exists, the vtable will only be emitted in the TU where the key method
640 // is defined. In a TU where vtable is not available, the function won't
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000641 // be 'addresstaken'. If its address is not recorded here, the profile data
Xinliang David Li69a00f02016-06-21 02:39:08 +0000642 // with missing address may be picked by the linker leading to missing
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000643 // indirect call target info.
644 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000645}
646
Xinliang David Li985ff202016-02-27 23:11:30 +0000647static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000648 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000649 if (!needsComdatForCounter(F, M))
650 return nullptr;
651
Xinliang David Liab361ef2015-12-21 21:52:27 +0000652 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000653 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000654 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000655 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000656 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000657 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000658 : getInstrProfComdatPrefix());
659 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
660}
661
Xinliang David Lib628dd32016-05-21 22:55:34 +0000662static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
663 // Don't do this for Darwin. compiler-rt uses linker magic.
664 if (Triple(M.getTargetTriple()).isOSDarwin())
665 return false;
666
667 // Use linker script magic to get data/cnts/name start/end.
668 if (Triple(M.getTargetTriple()).isOSLinux() ||
669 Triple(M.getTargetTriple()).isOSFreeBSD() ||
670 Triple(M.getTargetTriple()).isPS4CPU())
671 return false;
672
673 return true;
674}
675
Justin Bogner61ba2e32014-12-08 18:02:35 +0000676GlobalVariable *
677InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000678 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000679 auto It = ProfileDataMap.find(NamePtr);
680 PerFunctionProfileData PD;
681 if (It != ProfileDataMap.end()) {
682 if (It->second.RegionCounters)
683 return It->second.RegionCounters;
684 PD = It->second;
685 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000686
Wei Mi3cc92042015-09-23 22:40:45 +0000687 // Move the name variable to the right section. Place them in a COMDAT group
688 // if the associated function is a COMDAT. This will make sure that
689 // only one copy of counters of the COMDAT function will be emitted after
690 // linking.
Diego Novillodf4837b2015-05-27 19:34:01 +0000691 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000692 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000693 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000694
695 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
696 LLVMContext &Ctx = M->getContext();
697 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
698
699 // Create the counters variable.
Xinliang David Li192c7482015-11-05 00:47:26 +0000700 auto *CounterPtr =
701 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000702 Constant::getNullValue(CounterTy),
703 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000704 CounterPtr->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000705 CounterPtr->setSection(
706 getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000707 CounterPtr->setAlignment(8);
708 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000709
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000710 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000711 // Allocate statically the array of pointers to value profile nodes for
712 // the current function.
713 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
714 if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
Xinliang David Lib628dd32016-05-21 22:55:34 +0000715 uint64_t NS = 0;
716 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
717 NS += PD.NumValueSites[Kind];
718 if (NS) {
719 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
720
721 auto *ValuesVar =
722 new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
723 Constant::getNullValue(ValuesTy),
724 getVarName(Inc, getInstrProfValuesVarPrefix()));
725 ValuesVar->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000726 ValuesVar->setSection(
727 getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000728 ValuesVar->setAlignment(8);
729 ValuesVar->setComdat(ProfileVarsComdat);
730 ValuesPtrExpr =
Eugene Zelenko34c23272017-01-18 00:57:48 +0000731 ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000732 }
733 }
734
735 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000736 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000737 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000738 Type *DataTypes[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000739#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
740#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000741 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000742 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000743
Xinliang David Li69a00f02016-06-21 02:39:08 +0000744 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
745 ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
746 : ConstantPointerNull::get(Int8PtrTy);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000747
Xinliang David Li69a00f02016-06-21 02:39:08 +0000748 Constant *Int16ArrayVals[IPVK_Last + 1];
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000749 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
750 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
751
Justin Bogner61ba2e32014-12-08 18:02:35 +0000752 Constant *DataVals[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000753#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
754#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000755 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000756 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000757 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000758 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000759 Data->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000760 Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000761 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000762 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000763
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000764 PD.RegionCounters = CounterPtr;
765 PD.DataVar = Data;
766 ProfileDataMap[NamePtr] = PD;
767
Justin Bogner61ba2e32014-12-08 18:02:35 +0000768 // Mark the data variable as used so that it isn't stripped out.
769 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000770 // Now that the linkage set by the FE has been passed to the data and counter
771 // variables, reset Name variable's linkage and visibility to private so that
772 // it can be removed later by the compiler.
773 NamePtr->setLinkage(GlobalValue::PrivateLinkage);
774 // Collect the referenced names to be used by emitNameData.
775 ReferencedNames.push_back(NamePtr);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000776
Xinliang David Li192c7482015-11-05 00:47:26 +0000777 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000778}
779
Xinliang David Lib628dd32016-05-21 22:55:34 +0000780void InstrProfiling::emitVNodes() {
781 if (!ValueProfileStaticAlloc)
782 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000783
Xinliang David Lib628dd32016-05-21 22:55:34 +0000784 // For now only support this on platforms that do
785 // not require runtime registration to discover
786 // named section start/end.
787 if (needsRuntimeRegistrationOfSectionRange(*M))
788 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000789
Xinliang David Lib628dd32016-05-21 22:55:34 +0000790 size_t TotalNS = 0;
791 for (auto &PD : ProfileDataMap) {
792 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
793 TotalNS += PD.second.NumValueSites[Kind];
794 }
795
796 if (!TotalNS)
797 return;
798
799 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
Xinliang David Li69a00f02016-06-21 02:39:08 +0000800// Heuristic for small programs with very few total value sites.
801// The default value of vp-counters-per-site is chosen based on
802// the observation that large apps usually have a low percentage
803// of value sites that actually have any profile data, and thus
804// the average number of counters per site is low. For small
805// apps with very few sites, this may not be true. Bump up the
806// number of counters in this case.
Xinliang David Lie4520762016-05-23 19:29:26 +0000807#define INSTR_PROF_MIN_VAL_COUNTS 10
808 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000809 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000810
811 auto &Ctx = M->getContext();
812 Type *VNodeTypes[] = {
813#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
814#include "llvm/ProfileData/InstrProfData.inc"
815 };
816 auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
817
818 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
819 auto *VNodesVar = new GlobalVariable(
Eugene Zelenko34c23272017-01-18 00:57:48 +0000820 *M, VNodesTy, false, GlobalValue::PrivateLinkage,
Xinliang David Lib628dd32016-05-21 22:55:34 +0000821 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000822 VNodesVar->setSection(
823 getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000824 UsedVars.push_back(VNodesVar);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000825}
826
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000827void InstrProfiling::emitNameData() {
828 std::string UncompressedData;
829
830 if (ReferencedNames.empty())
831 return;
832
833 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000834 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000835 DoNameCompression)) {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000836 report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000837 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000838
839 auto &Ctx = M->getContext();
Eugene Zelenko34c23272017-01-18 00:57:48 +0000840 auto *NamesVal = ConstantDataArray::getString(
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000841 Ctx, StringRef(CompressedNameStr), false);
Eugene Zelenko34c23272017-01-18 00:57:48 +0000842 NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
843 GlobalValue::PrivateLinkage, NamesVal,
844 getInstrProfNamesVarName());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000845 NamesSize = CompressedNameStr.size();
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000846 NamesVar->setSection(
847 getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000848 UsedVars.push_back(NamesVar);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000849
850 for (auto *NamePtr : ReferencedNames)
851 NamePtr->eraseFromParent();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000852}
853
Justin Bogner61ba2e32014-12-08 18:02:35 +0000854void InstrProfiling::emitRegistration() {
Xinliang David Li8da773b2016-05-17 20:19:03 +0000855 if (!needsRuntimeRegistrationOfSectionRange(*M))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000856 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000857
Justin Bogner61ba2e32014-12-08 18:02:35 +0000858 // Construct the function.
859 auto *VoidTy = Type::getVoidTy(M->getContext());
860 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000861 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000862 auto *RegisterFTy = FunctionType::get(VoidTy, false);
863 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000864 getInstrProfRegFuncsName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000865 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000866 if (Options.NoRedZone)
867 RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000868
Diego Novillob3029d22015-06-04 11:45:32 +0000869 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000870 auto *RuntimeRegisterF =
871 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000872 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000873
874 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
875 for (Value *Data : UsedVars)
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000876 if (Data != NamesVar)
877 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
878
879 if (NamesVar) {
880 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
881 auto *NamesRegisterTy =
882 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
883 auto *NamesRegisterF =
884 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
885 getInstrProfNamesRegFuncName(), M);
886 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
887 IRB.getInt64(NamesSize)});
888 }
889
Justin Bogner61ba2e32014-12-08 18:02:35 +0000890 IRB.CreateRetVoid();
891}
892
893void InstrProfiling::emitRuntimeHook() {
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000894 // We expect the linker to be invoked with -u<hook_var> flag for linux,
895 // for which case there is no need to emit the user function.
896 if (Triple(M->getTargetTriple()).isOSLinux())
897 return;
898
Justin Bogner61ba2e32014-12-08 18:02:35 +0000899 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li69a00f02016-06-21 02:39:08 +0000900 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
901 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000902
903 // Declare an external variable that will pull in the runtime initialization.
904 auto *Int32Ty = Type::getInt32Ty(M->getContext());
905 auto *Var =
906 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000907 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000908
909 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000910 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
911 GlobalValue::LinkOnceODRLinkage,
912 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000913 User->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000914 if (Options.NoRedZone)
915 User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000916 User->setVisibility(GlobalValue::HiddenVisibility);
Xinliang David Lia2286082016-05-25 17:17:51 +0000917 if (Triple(M->getTargetTriple()).supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +0000918 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000919
920 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
921 auto *Load = IRB.CreateLoad(Var);
922 IRB.CreateRet(Load);
923
924 // Mark the user variable as used so that it isn't stripped out.
925 UsedVars.push_back(User);
926}
927
928void InstrProfiling::emitUses() {
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000929 if (!UsedVars.empty())
930 appendToUsed(*M, UsedVars);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000931}
932
933void InstrProfiling::emitInitialization() {
Vedant Kumarcd32eba2016-07-21 17:50:07 +0000934 StringRef InstrProfileOutput = Options.InstrProfileOutput;
Justin Bognerba1900c2015-04-30 23:49:23 +0000935
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000936 if (!InstrProfileOutput.empty()) {
937 // Create variable for profile name.
938 Constant *ProfileNameConst =
939 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
940 GlobalVariable *ProfileNameVar = new GlobalVariable(
941 *M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
942 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000943 if (TT.supportsCOMDAT()) {
944 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
945 ProfileNameVar->setComdat(M->getOrInsertComdat(
946 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
947 }
948 }
949
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000950 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000951 if (!RegisterF)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000952 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000953
954 // Create the initialization function.
955 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000956 auto *F = Function::Create(FunctionType::get(VoidTy, false),
957 GlobalValue::InternalLinkage,
958 getInstrProfInitFuncName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000959 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000960 F->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000961 if (Options.NoRedZone)
962 F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000963
964 // Add the basic block and the necessary calls.
965 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000966 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000967 IRB.CreateCall(RegisterF, {});
Justin Bogner61ba2e32014-12-08 18:02:35 +0000968 IRB.CreateRetVoid();
969
970 appendToGlobalCtors(*M, F, 0);
971}