1*0b57cec5SDimitry Andric //===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This pass lowers instrprof_* intrinsics emitted by a frontend for profiling.
10*0b57cec5SDimitry Andric // It also builds the data structures and initialization code needed for
11*0b57cec5SDimitry Andric // updating execution counts and emitting the profile at runtime.
12*0b57cec5SDimitry Andric //
13*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
14*0b57cec5SDimitry Andric 
15*0b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
16*0b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
18*0b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
20*0b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
21*0b57cec5SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
22*0b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
23*0b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
24*0b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
25*0b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
26*0b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
27*0b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
28*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
290eae32dcSDimitry Andric #include "llvm/IR/DIBuilder.h"
30*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
310eae32dcSDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
32*0b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
33*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
34*0b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
35*0b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
36*0b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
37*0b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
38*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
39*0b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
40*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
41*0b57cec5SDimitry Andric #include "llvm/IR/Type.h"
42480093f4SDimitry Andric #include "llvm/InitializePasses.h"
43*0b57cec5SDimitry Andric #include "llvm/Pass.h"
44*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProf.h"
450eae32dcSDimitry Andric #include "llvm/ProfileData/InstrProfCorrelator.h"
46*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
47*0b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
48*0b57cec5SDimitry Andric #include "llvm/Support/Error.h"
49*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
50*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
51*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h"
52*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdater.h"
53*0b57cec5SDimitry Andric #include <algorithm>
54*0b57cec5SDimitry Andric #include <cassert>
55*0b57cec5SDimitry Andric #include <cstddef>
56*0b57cec5SDimitry Andric #include <cstdint>
57*0b57cec5SDimitry Andric #include <string>
58*0b57cec5SDimitry Andric 
59*0b57cec5SDimitry Andric using namespace llvm;
60*0b57cec5SDimitry Andric 
61*0b57cec5SDimitry Andric #define DEBUG_TYPE "instrprof"
62*0b57cec5SDimitry Andric 
630eae32dcSDimitry Andric namespace llvm {
640eae32dcSDimitry Andric cl::opt<bool>
650eae32dcSDimitry Andric     DebugInfoCorrelate("debug-info-correlate", cl::ZeroOrMore,
660eae32dcSDimitry Andric                        cl::desc("Use debug info to correlate profiles."),
670eae32dcSDimitry Andric                        cl::init(false));
680eae32dcSDimitry Andric } // namespace llvm
690eae32dcSDimitry Andric 
70*0b57cec5SDimitry Andric namespace {
71*0b57cec5SDimitry Andric 
72*0b57cec5SDimitry Andric cl::opt<bool> DoHashBasedCounterSplit(
73*0b57cec5SDimitry Andric     "hash-based-counter-split",
74*0b57cec5SDimitry Andric     cl::desc("Rename counter variable of a comdat function based on cfg hash"),
75*0b57cec5SDimitry Andric     cl::init(true));
76*0b57cec5SDimitry Andric 
774824e7fdSDimitry Andric cl::opt<bool>
784824e7fdSDimitry Andric     RuntimeCounterRelocation("runtime-counter-relocation",
795ffd83dbSDimitry Andric                              cl::desc("Enable relocating counters at runtime."),
805ffd83dbSDimitry Andric                              cl::init(false));
815ffd83dbSDimitry Andric 
82*0b57cec5SDimitry Andric cl::opt<bool> ValueProfileStaticAlloc(
83*0b57cec5SDimitry Andric     "vp-static-alloc",
84*0b57cec5SDimitry Andric     cl::desc("Do static counter allocation for value profiler"),
85*0b57cec5SDimitry Andric     cl::init(true));
86*0b57cec5SDimitry Andric 
87*0b57cec5SDimitry Andric cl::opt<double> NumCountersPerValueSite(
88*0b57cec5SDimitry Andric     "vp-counters-per-site",
89*0b57cec5SDimitry Andric     cl::desc("The average number of profile counters allocated "
90*0b57cec5SDimitry Andric              "per value profiling site."),
91*0b57cec5SDimitry Andric     // This is set to a very small value because in real programs, only
92*0b57cec5SDimitry Andric     // a very small percentage of value sites have non-zero targets, e.g, 1/30.
93*0b57cec5SDimitry Andric     // For those sites with non-zero profile, the average number of targets
94*0b57cec5SDimitry Andric     // is usually smaller than 2.
95*0b57cec5SDimitry Andric     cl::init(1.0));
96*0b57cec5SDimitry Andric 
97*0b57cec5SDimitry Andric cl::opt<bool> AtomicCounterUpdateAll(
98*0b57cec5SDimitry Andric     "instrprof-atomic-counter-update-all", cl::ZeroOrMore,
99*0b57cec5SDimitry Andric     cl::desc("Make all profile counter updates atomic (for testing only)"),
100*0b57cec5SDimitry Andric     cl::init(false));
101*0b57cec5SDimitry Andric 
102*0b57cec5SDimitry Andric cl::opt<bool> AtomicCounterUpdatePromoted(
103*0b57cec5SDimitry Andric     "atomic-counter-update-promoted", cl::ZeroOrMore,
104*0b57cec5SDimitry Andric     cl::desc("Do counter update using atomic fetch add "
105*0b57cec5SDimitry Andric              " for promoted counters only"),
106*0b57cec5SDimitry Andric     cl::init(false));
107*0b57cec5SDimitry Andric 
1085ffd83dbSDimitry Andric cl::opt<bool> AtomicFirstCounter(
1095ffd83dbSDimitry Andric     "atomic-first-counter", cl::ZeroOrMore,
1105ffd83dbSDimitry Andric     cl::desc("Use atomic fetch add for first counter in a function (usually "
1115ffd83dbSDimitry Andric              "the entry counter)"),
1125ffd83dbSDimitry Andric     cl::init(false));
1135ffd83dbSDimitry Andric 
114*0b57cec5SDimitry Andric // If the option is not specified, the default behavior about whether
115*0b57cec5SDimitry Andric // counter promotion is done depends on how instrumentaiton lowering
116*0b57cec5SDimitry Andric // pipeline is setup, i.e., the default value of true of this option
117*0b57cec5SDimitry Andric // does not mean the promotion will be done by default. Explicitly
118*0b57cec5SDimitry Andric // setting this option can override the default behavior.
119*0b57cec5SDimitry Andric cl::opt<bool> DoCounterPromotion("do-counter-promotion", cl::ZeroOrMore,
120*0b57cec5SDimitry Andric                                  cl::desc("Do counter register promotion"),
121*0b57cec5SDimitry Andric                                  cl::init(false));
122*0b57cec5SDimitry Andric cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
123*0b57cec5SDimitry Andric     cl::ZeroOrMore, "max-counter-promotions-per-loop", cl::init(20),
124*0b57cec5SDimitry Andric     cl::desc("Max number counter promotions per loop to avoid"
125*0b57cec5SDimitry Andric              " increasing register pressure too much"));
126*0b57cec5SDimitry Andric 
127*0b57cec5SDimitry Andric // A debug option
128*0b57cec5SDimitry Andric cl::opt<int>
129*0b57cec5SDimitry Andric     MaxNumOfPromotions(cl::ZeroOrMore, "max-counter-promotions", cl::init(-1),
130*0b57cec5SDimitry Andric                        cl::desc("Max number of allowed counter promotions"));
131*0b57cec5SDimitry Andric 
132*0b57cec5SDimitry Andric cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
133*0b57cec5SDimitry Andric     cl::ZeroOrMore, "speculative-counter-promotion-max-exiting", cl::init(3),
134*0b57cec5SDimitry Andric     cl::desc("The max number of exiting blocks of a loop to allow "
135*0b57cec5SDimitry Andric              " speculative counter promotion"));
136*0b57cec5SDimitry Andric 
137*0b57cec5SDimitry Andric cl::opt<bool> SpeculativeCounterPromotionToLoop(
138*0b57cec5SDimitry Andric     cl::ZeroOrMore, "speculative-counter-promotion-to-loop", cl::init(false),
139*0b57cec5SDimitry Andric     cl::desc("When the option is false, if the target block is in a loop, "
140*0b57cec5SDimitry Andric              "the promotion will be disallowed unless the promoted counter "
141*0b57cec5SDimitry Andric              " update can be further/iteratively promoted into an acyclic "
142*0b57cec5SDimitry Andric              " region."));
143*0b57cec5SDimitry Andric 
144*0b57cec5SDimitry Andric cl::opt<bool> IterativeCounterPromotion(
145*0b57cec5SDimitry Andric     cl::ZeroOrMore, "iterative-counter-promotion", cl::init(true),
146*0b57cec5SDimitry Andric     cl::desc("Allow counter promotion across the whole loop nest."));
147*0b57cec5SDimitry Andric 
148e8d8bef9SDimitry Andric cl::opt<bool> SkipRetExitBlock(
149e8d8bef9SDimitry Andric     cl::ZeroOrMore, "skip-ret-exit-block", cl::init(true),
150e8d8bef9SDimitry Andric     cl::desc("Suppress counter promotion if exit blocks contain ret."));
151e8d8bef9SDimitry Andric 
152*0b57cec5SDimitry Andric class InstrProfilingLegacyPass : public ModulePass {
153*0b57cec5SDimitry Andric   InstrProfiling InstrProf;
154*0b57cec5SDimitry Andric 
155*0b57cec5SDimitry Andric public:
156*0b57cec5SDimitry Andric   static char ID;
157*0b57cec5SDimitry Andric 
158*0b57cec5SDimitry Andric   InstrProfilingLegacyPass() : ModulePass(ID) {}
159*0b57cec5SDimitry Andric   InstrProfilingLegacyPass(const InstrProfOptions &Options, bool IsCS = false)
1605ffd83dbSDimitry Andric       : ModulePass(ID), InstrProf(Options, IsCS) {
1615ffd83dbSDimitry Andric     initializeInstrProfilingLegacyPassPass(*PassRegistry::getPassRegistry());
1625ffd83dbSDimitry Andric   }
163*0b57cec5SDimitry Andric 
164*0b57cec5SDimitry Andric   StringRef getPassName() const override {
165*0b57cec5SDimitry Andric     return "Frontend instrumentation-based coverage lowering";
166*0b57cec5SDimitry Andric   }
167*0b57cec5SDimitry Andric 
168*0b57cec5SDimitry Andric   bool runOnModule(Module &M) override {
1698bcb0991SDimitry Andric     auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
1708bcb0991SDimitry Andric       return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1718bcb0991SDimitry Andric     };
1728bcb0991SDimitry Andric     return InstrProf.run(M, GetTLI);
173*0b57cec5SDimitry Andric   }
174*0b57cec5SDimitry Andric 
175*0b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
176*0b57cec5SDimitry Andric     AU.setPreservesCFG();
177*0b57cec5SDimitry Andric     AU.addRequired<TargetLibraryInfoWrapperPass>();
178*0b57cec5SDimitry Andric   }
179*0b57cec5SDimitry Andric };
180*0b57cec5SDimitry Andric 
181*0b57cec5SDimitry Andric ///
182*0b57cec5SDimitry Andric /// A helper class to promote one counter RMW operation in the loop
183*0b57cec5SDimitry Andric /// into register update.
184*0b57cec5SDimitry Andric ///
185*0b57cec5SDimitry Andric /// RWM update for the counter will be sinked out of the loop after
186*0b57cec5SDimitry Andric /// the transformation.
187*0b57cec5SDimitry Andric ///
188*0b57cec5SDimitry Andric class PGOCounterPromoterHelper : public LoadAndStorePromoter {
189*0b57cec5SDimitry Andric public:
190*0b57cec5SDimitry Andric   PGOCounterPromoterHelper(
191*0b57cec5SDimitry Andric       Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
192*0b57cec5SDimitry Andric       BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
193*0b57cec5SDimitry Andric       ArrayRef<Instruction *> InsertPts,
194*0b57cec5SDimitry Andric       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
195*0b57cec5SDimitry Andric       LoopInfo &LI)
196*0b57cec5SDimitry Andric       : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
197*0b57cec5SDimitry Andric         InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
198*0b57cec5SDimitry Andric     assert(isa<LoadInst>(L));
199*0b57cec5SDimitry Andric     assert(isa<StoreInst>(S));
200*0b57cec5SDimitry Andric     SSA.AddAvailableValue(PH, Init);
201*0b57cec5SDimitry Andric   }
202*0b57cec5SDimitry Andric 
203*0b57cec5SDimitry Andric   void doExtraRewritesBeforeFinalDeletion() override {
204*0b57cec5SDimitry Andric     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
205*0b57cec5SDimitry Andric       BasicBlock *ExitBlock = ExitBlocks[i];
206*0b57cec5SDimitry Andric       Instruction *InsertPos = InsertPts[i];
207*0b57cec5SDimitry Andric       // Get LiveIn value into the ExitBlock. If there are multiple
208*0b57cec5SDimitry Andric       // predecessors, the value is defined by a PHI node in this
209*0b57cec5SDimitry Andric       // block.
210*0b57cec5SDimitry Andric       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
211*0b57cec5SDimitry Andric       Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
212*0b57cec5SDimitry Andric       Type *Ty = LiveInValue->getType();
213*0b57cec5SDimitry Andric       IRBuilder<> Builder(InsertPos);
214*0b57cec5SDimitry Andric       if (AtomicCounterUpdatePromoted)
215*0b57cec5SDimitry Andric         // automic update currently can only be promoted across the current
216*0b57cec5SDimitry Andric         // loop, not the whole loop nest.
217*0b57cec5SDimitry Andric         Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
218fe6060f1SDimitry Andric                                 MaybeAlign(),
219*0b57cec5SDimitry Andric                                 AtomicOrdering::SequentiallyConsistent);
220*0b57cec5SDimitry Andric       else {
221*0b57cec5SDimitry Andric         LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
222*0b57cec5SDimitry Andric         auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
223*0b57cec5SDimitry Andric         auto *NewStore = Builder.CreateStore(NewVal, Addr);
224*0b57cec5SDimitry Andric 
225*0b57cec5SDimitry Andric         // Now update the parent loop's candidate list:
226*0b57cec5SDimitry Andric         if (IterativeCounterPromotion) {
227*0b57cec5SDimitry Andric           auto *TargetLoop = LI.getLoopFor(ExitBlock);
228*0b57cec5SDimitry Andric           if (TargetLoop)
229*0b57cec5SDimitry Andric             LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
230*0b57cec5SDimitry Andric         }
231*0b57cec5SDimitry Andric       }
232*0b57cec5SDimitry Andric     }
233*0b57cec5SDimitry Andric   }
234*0b57cec5SDimitry Andric 
235*0b57cec5SDimitry Andric private:
236*0b57cec5SDimitry Andric   Instruction *Store;
237*0b57cec5SDimitry Andric   ArrayRef<BasicBlock *> ExitBlocks;
238*0b57cec5SDimitry Andric   ArrayRef<Instruction *> InsertPts;
239*0b57cec5SDimitry Andric   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
240*0b57cec5SDimitry Andric   LoopInfo &LI;
241*0b57cec5SDimitry Andric };
242*0b57cec5SDimitry Andric 
243*0b57cec5SDimitry Andric /// A helper class to do register promotion for all profile counter
244*0b57cec5SDimitry Andric /// updates in a loop.
245*0b57cec5SDimitry Andric ///
246*0b57cec5SDimitry Andric class PGOCounterPromoter {
247*0b57cec5SDimitry Andric public:
248*0b57cec5SDimitry Andric   PGOCounterPromoter(
249*0b57cec5SDimitry Andric       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
250*0b57cec5SDimitry Andric       Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI)
25104eeddc0SDimitry Andric       : LoopToCandidates(LoopToCands), L(CurLoop), LI(LI), BFI(BFI) {
252*0b57cec5SDimitry Andric 
2535ffd83dbSDimitry Andric     // Skip collection of ExitBlocks and InsertPts for loops that will not be
2545ffd83dbSDimitry Andric     // able to have counters promoted.
255*0b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> LoopExitBlocks;
256*0b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 8> BlockSet;
2575ffd83dbSDimitry Andric 
258*0b57cec5SDimitry Andric     L.getExitBlocks(LoopExitBlocks);
2595ffd83dbSDimitry Andric     if (!isPromotionPossible(&L, LoopExitBlocks))
2605ffd83dbSDimitry Andric       return;
261*0b57cec5SDimitry Andric 
262*0b57cec5SDimitry Andric     for (BasicBlock *ExitBlock : LoopExitBlocks) {
263*0b57cec5SDimitry Andric       if (BlockSet.insert(ExitBlock).second) {
264*0b57cec5SDimitry Andric         ExitBlocks.push_back(ExitBlock);
265*0b57cec5SDimitry Andric         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
266*0b57cec5SDimitry Andric       }
267*0b57cec5SDimitry Andric     }
268*0b57cec5SDimitry Andric   }
269*0b57cec5SDimitry Andric 
270*0b57cec5SDimitry Andric   bool run(int64_t *NumPromoted) {
271*0b57cec5SDimitry Andric     // Skip 'infinite' loops:
272*0b57cec5SDimitry Andric     if (ExitBlocks.size() == 0)
273*0b57cec5SDimitry Andric       return false;
274e8d8bef9SDimitry Andric 
275e8d8bef9SDimitry Andric     // Skip if any of the ExitBlocks contains a ret instruction.
276e8d8bef9SDimitry Andric     // This is to prevent dumping of incomplete profile -- if the
277e8d8bef9SDimitry Andric     // the loop is a long running loop and dump is called in the middle
278e8d8bef9SDimitry Andric     // of the loop, the result profile is incomplete.
279e8d8bef9SDimitry Andric     // FIXME: add other heuristics to detect long running loops.
280e8d8bef9SDimitry Andric     if (SkipRetExitBlock) {
281e8d8bef9SDimitry Andric       for (auto BB : ExitBlocks)
282e8d8bef9SDimitry Andric         if (isa<ReturnInst>(BB->getTerminator()))
283e8d8bef9SDimitry Andric           return false;
284e8d8bef9SDimitry Andric     }
285e8d8bef9SDimitry Andric 
286*0b57cec5SDimitry Andric     unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
287*0b57cec5SDimitry Andric     if (MaxProm == 0)
288*0b57cec5SDimitry Andric       return false;
289*0b57cec5SDimitry Andric 
290*0b57cec5SDimitry Andric     unsigned Promoted = 0;
291*0b57cec5SDimitry Andric     for (auto &Cand : LoopToCandidates[&L]) {
292*0b57cec5SDimitry Andric 
293*0b57cec5SDimitry Andric       SmallVector<PHINode *, 4> NewPHIs;
294*0b57cec5SDimitry Andric       SSAUpdater SSA(&NewPHIs);
295*0b57cec5SDimitry Andric       Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
296*0b57cec5SDimitry Andric 
297*0b57cec5SDimitry Andric       // If BFI is set, we will use it to guide the promotions.
298*0b57cec5SDimitry Andric       if (BFI) {
299*0b57cec5SDimitry Andric         auto *BB = Cand.first->getParent();
300*0b57cec5SDimitry Andric         auto InstrCount = BFI->getBlockProfileCount(BB);
301*0b57cec5SDimitry Andric         if (!InstrCount)
302*0b57cec5SDimitry Andric           continue;
303*0b57cec5SDimitry Andric         auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
304*0b57cec5SDimitry Andric         // If the average loop trip count is not greater than 1.5, we skip
305*0b57cec5SDimitry Andric         // promotion.
306*0b57cec5SDimitry Andric         if (PreheaderCount &&
307*0b57cec5SDimitry Andric             (PreheaderCount.getValue() * 3) >= (InstrCount.getValue() * 2))
308*0b57cec5SDimitry Andric           continue;
309*0b57cec5SDimitry Andric       }
310*0b57cec5SDimitry Andric 
311*0b57cec5SDimitry Andric       PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
312*0b57cec5SDimitry Andric                                         L.getLoopPreheader(), ExitBlocks,
313*0b57cec5SDimitry Andric                                         InsertPts, LoopToCandidates, LI);
314*0b57cec5SDimitry Andric       Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
315*0b57cec5SDimitry Andric       Promoted++;
316*0b57cec5SDimitry Andric       if (Promoted >= MaxProm)
317*0b57cec5SDimitry Andric         break;
318*0b57cec5SDimitry Andric 
319*0b57cec5SDimitry Andric       (*NumPromoted)++;
320*0b57cec5SDimitry Andric       if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
321*0b57cec5SDimitry Andric         break;
322*0b57cec5SDimitry Andric     }
323*0b57cec5SDimitry Andric 
324*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
325*0b57cec5SDimitry Andric                       << L.getLoopDepth() << ")\n");
326*0b57cec5SDimitry Andric     return Promoted != 0;
327*0b57cec5SDimitry Andric   }
328*0b57cec5SDimitry Andric 
329*0b57cec5SDimitry Andric private:
330*0b57cec5SDimitry Andric   bool allowSpeculativeCounterPromotion(Loop *LP) {
331*0b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> ExitingBlocks;
332*0b57cec5SDimitry Andric     L.getExitingBlocks(ExitingBlocks);
333*0b57cec5SDimitry Andric     // Not considierered speculative.
334*0b57cec5SDimitry Andric     if (ExitingBlocks.size() == 1)
335*0b57cec5SDimitry Andric       return true;
336*0b57cec5SDimitry Andric     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
337*0b57cec5SDimitry Andric       return false;
338*0b57cec5SDimitry Andric     return true;
339*0b57cec5SDimitry Andric   }
340*0b57cec5SDimitry Andric 
3415ffd83dbSDimitry Andric   // Check whether the loop satisfies the basic conditions needed to perform
3425ffd83dbSDimitry Andric   // Counter Promotions.
3434824e7fdSDimitry Andric   bool
3444824e7fdSDimitry Andric   isPromotionPossible(Loop *LP,
3455ffd83dbSDimitry Andric                       const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
346*0b57cec5SDimitry Andric     // We can't insert into a catchswitch.
347*0b57cec5SDimitry Andric     if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
348*0b57cec5SDimitry Andric           return isa<CatchSwitchInst>(Exit->getTerminator());
349*0b57cec5SDimitry Andric         }))
3505ffd83dbSDimitry Andric       return false;
351*0b57cec5SDimitry Andric 
352*0b57cec5SDimitry Andric     if (!LP->hasDedicatedExits())
3535ffd83dbSDimitry Andric       return false;
354*0b57cec5SDimitry Andric 
355*0b57cec5SDimitry Andric     BasicBlock *PH = LP->getLoopPreheader();
356*0b57cec5SDimitry Andric     if (!PH)
3575ffd83dbSDimitry Andric       return false;
3585ffd83dbSDimitry Andric 
3595ffd83dbSDimitry Andric     return true;
3605ffd83dbSDimitry Andric   }
3615ffd83dbSDimitry Andric 
3625ffd83dbSDimitry Andric   // Returns the max number of Counter Promotions for LP.
3635ffd83dbSDimitry Andric   unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
3645ffd83dbSDimitry Andric     SmallVector<BasicBlock *, 8> LoopExitBlocks;
3655ffd83dbSDimitry Andric     LP->getExitBlocks(LoopExitBlocks);
3665ffd83dbSDimitry Andric     if (!isPromotionPossible(LP, LoopExitBlocks))
367*0b57cec5SDimitry Andric       return 0;
368*0b57cec5SDimitry Andric 
369*0b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> ExitingBlocks;
370*0b57cec5SDimitry Andric     LP->getExitingBlocks(ExitingBlocks);
371*0b57cec5SDimitry Andric 
372*0b57cec5SDimitry Andric     // If BFI is set, we do more aggressive promotions based on BFI.
373*0b57cec5SDimitry Andric     if (BFI)
374*0b57cec5SDimitry Andric       return (unsigned)-1;
375*0b57cec5SDimitry Andric 
376*0b57cec5SDimitry Andric     // Not considierered speculative.
377*0b57cec5SDimitry Andric     if (ExitingBlocks.size() == 1)
378*0b57cec5SDimitry Andric       return MaxNumOfPromotionsPerLoop;
379*0b57cec5SDimitry Andric 
380*0b57cec5SDimitry Andric     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
381*0b57cec5SDimitry Andric       return 0;
382*0b57cec5SDimitry Andric 
383*0b57cec5SDimitry Andric     // Whether the target block is in a loop does not matter:
384*0b57cec5SDimitry Andric     if (SpeculativeCounterPromotionToLoop)
385*0b57cec5SDimitry Andric       return MaxNumOfPromotionsPerLoop;
386*0b57cec5SDimitry Andric 
387*0b57cec5SDimitry Andric     // Now check the target block:
388*0b57cec5SDimitry Andric     unsigned MaxProm = MaxNumOfPromotionsPerLoop;
389*0b57cec5SDimitry Andric     for (auto *TargetBlock : LoopExitBlocks) {
390*0b57cec5SDimitry Andric       auto *TargetLoop = LI.getLoopFor(TargetBlock);
391*0b57cec5SDimitry Andric       if (!TargetLoop)
392*0b57cec5SDimitry Andric         continue;
393*0b57cec5SDimitry Andric       unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
394*0b57cec5SDimitry Andric       unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
395*0b57cec5SDimitry Andric       MaxProm =
396*0b57cec5SDimitry Andric           std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
397*0b57cec5SDimitry Andric                                 PendingCandsInTarget);
398*0b57cec5SDimitry Andric     }
399*0b57cec5SDimitry Andric     return MaxProm;
400*0b57cec5SDimitry Andric   }
401*0b57cec5SDimitry Andric 
402*0b57cec5SDimitry Andric   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
403*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 8> ExitBlocks;
404*0b57cec5SDimitry Andric   SmallVector<Instruction *, 8> InsertPts;
405*0b57cec5SDimitry Andric   Loop &L;
406*0b57cec5SDimitry Andric   LoopInfo &LI;
407*0b57cec5SDimitry Andric   BlockFrequencyInfo *BFI;
408*0b57cec5SDimitry Andric };
409*0b57cec5SDimitry Andric 
410e8d8bef9SDimitry Andric enum class ValueProfilingCallType {
411e8d8bef9SDimitry Andric   // Individual values are tracked. Currently used for indiret call target
412e8d8bef9SDimitry Andric   // profiling.
413e8d8bef9SDimitry Andric   Default,
414e8d8bef9SDimitry Andric 
415e8d8bef9SDimitry Andric   // MemOp: the memop size value profiling.
416e8d8bef9SDimitry Andric   MemOp
417e8d8bef9SDimitry Andric };
418e8d8bef9SDimitry Andric 
419*0b57cec5SDimitry Andric } // end anonymous namespace
420*0b57cec5SDimitry Andric 
421*0b57cec5SDimitry Andric PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
4228bcb0991SDimitry Andric   FunctionAnalysisManager &FAM =
4238bcb0991SDimitry Andric       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
4248bcb0991SDimitry Andric   auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
4258bcb0991SDimitry Andric     return FAM.getResult<TargetLibraryAnalysis>(F);
4268bcb0991SDimitry Andric   };
4278bcb0991SDimitry Andric   if (!run(M, GetTLI))
428*0b57cec5SDimitry Andric     return PreservedAnalyses::all();
429*0b57cec5SDimitry Andric 
430*0b57cec5SDimitry Andric   return PreservedAnalyses::none();
431*0b57cec5SDimitry Andric }
432*0b57cec5SDimitry Andric 
433*0b57cec5SDimitry Andric char InstrProfilingLegacyPass::ID = 0;
4344824e7fdSDimitry Andric INITIALIZE_PASS_BEGIN(InstrProfilingLegacyPass, "instrprof",
4354824e7fdSDimitry Andric                       "Frontend instrumentation-based coverage lowering.",
4364824e7fdSDimitry Andric                       false, false)
437*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
4384824e7fdSDimitry Andric INITIALIZE_PASS_END(InstrProfilingLegacyPass, "instrprof",
4394824e7fdSDimitry Andric                     "Frontend instrumentation-based coverage lowering.", false,
4404824e7fdSDimitry Andric                     false)
441*0b57cec5SDimitry Andric 
442*0b57cec5SDimitry Andric ModulePass *
443*0b57cec5SDimitry Andric llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options,
444*0b57cec5SDimitry Andric                                      bool IsCS) {
445*0b57cec5SDimitry Andric   return new InstrProfilingLegacyPass(Options, IsCS);
446*0b57cec5SDimitry Andric }
447*0b57cec5SDimitry Andric 
448*0b57cec5SDimitry Andric bool InstrProfiling::lowerIntrinsics(Function *F) {
449*0b57cec5SDimitry Andric   bool MadeChange = false;
450*0b57cec5SDimitry Andric   PromotionCandidates.clear();
451*0b57cec5SDimitry Andric   for (BasicBlock &BB : *F) {
452349cc55cSDimitry Andric     for (Instruction &Instr : llvm::make_early_inc_range(BB)) {
45304eeddc0SDimitry Andric       if (auto *IPIS = dyn_cast<InstrProfIncrementInstStep>(&Instr)) {
45404eeddc0SDimitry Andric         lowerIncrement(IPIS);
455*0b57cec5SDimitry Andric         MadeChange = true;
45604eeddc0SDimitry Andric       } else if (auto *IPI = dyn_cast<InstrProfIncrementInst>(&Instr)) {
45704eeddc0SDimitry Andric         lowerIncrement(IPI);
45804eeddc0SDimitry Andric         MadeChange = true;
45904eeddc0SDimitry Andric       } else if (auto *IPVP = dyn_cast<InstrProfValueProfileInst>(&Instr)) {
46004eeddc0SDimitry Andric         lowerValueProfileInst(IPVP);
461*0b57cec5SDimitry Andric         MadeChange = true;
462*0b57cec5SDimitry Andric       }
463*0b57cec5SDimitry Andric     }
464*0b57cec5SDimitry Andric   }
465*0b57cec5SDimitry Andric 
466*0b57cec5SDimitry Andric   if (!MadeChange)
467*0b57cec5SDimitry Andric     return false;
468*0b57cec5SDimitry Andric 
469*0b57cec5SDimitry Andric   promoteCounterLoadStores(F);
470*0b57cec5SDimitry Andric   return true;
471*0b57cec5SDimitry Andric }
472*0b57cec5SDimitry Andric 
4735ffd83dbSDimitry Andric bool InstrProfiling::isRuntimeCounterRelocationEnabled() const {
474fe6060f1SDimitry Andric   // Mach-O don't support weak external references.
475fe6060f1SDimitry Andric   if (TT.isOSBinFormatMachO())
476fe6060f1SDimitry Andric     return false;
477fe6060f1SDimitry Andric 
4785ffd83dbSDimitry Andric   if (RuntimeCounterRelocation.getNumOccurrences() > 0)
4795ffd83dbSDimitry Andric     return RuntimeCounterRelocation;
4805ffd83dbSDimitry Andric 
481fe6060f1SDimitry Andric   // Fuchsia uses runtime counter relocation by default.
4825ffd83dbSDimitry Andric   return TT.isOSFuchsia();
4835ffd83dbSDimitry Andric }
4845ffd83dbSDimitry Andric 
485*0b57cec5SDimitry Andric bool InstrProfiling::isCounterPromotionEnabled() const {
486*0b57cec5SDimitry Andric   if (DoCounterPromotion.getNumOccurrences() > 0)
487*0b57cec5SDimitry Andric     return DoCounterPromotion;
488*0b57cec5SDimitry Andric 
489*0b57cec5SDimitry Andric   return Options.DoCounterPromotion;
490*0b57cec5SDimitry Andric }
491*0b57cec5SDimitry Andric 
492*0b57cec5SDimitry Andric void InstrProfiling::promoteCounterLoadStores(Function *F) {
493*0b57cec5SDimitry Andric   if (!isCounterPromotionEnabled())
494*0b57cec5SDimitry Andric     return;
495*0b57cec5SDimitry Andric 
496*0b57cec5SDimitry Andric   DominatorTree DT(*F);
497*0b57cec5SDimitry Andric   LoopInfo LI(DT);
498*0b57cec5SDimitry Andric   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
499*0b57cec5SDimitry Andric 
500*0b57cec5SDimitry Andric   std::unique_ptr<BlockFrequencyInfo> BFI;
501*0b57cec5SDimitry Andric   if (Options.UseBFIInPromotion) {
502*0b57cec5SDimitry Andric     std::unique_ptr<BranchProbabilityInfo> BPI;
5038bcb0991SDimitry Andric     BPI.reset(new BranchProbabilityInfo(*F, LI, &GetTLI(*F)));
504*0b57cec5SDimitry Andric     BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
505*0b57cec5SDimitry Andric   }
506*0b57cec5SDimitry Andric 
507*0b57cec5SDimitry Andric   for (const auto &LoadStore : PromotionCandidates) {
508*0b57cec5SDimitry Andric     auto *CounterLoad = LoadStore.first;
509*0b57cec5SDimitry Andric     auto *CounterStore = LoadStore.second;
510*0b57cec5SDimitry Andric     BasicBlock *BB = CounterLoad->getParent();
511*0b57cec5SDimitry Andric     Loop *ParentLoop = LI.getLoopFor(BB);
512*0b57cec5SDimitry Andric     if (!ParentLoop)
513*0b57cec5SDimitry Andric       continue;
514*0b57cec5SDimitry Andric     LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
515*0b57cec5SDimitry Andric   }
516*0b57cec5SDimitry Andric 
517*0b57cec5SDimitry Andric   SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
518*0b57cec5SDimitry Andric 
519*0b57cec5SDimitry Andric   // Do a post-order traversal of the loops so that counter updates can be
520*0b57cec5SDimitry Andric   // iteratively hoisted outside the loop nest.
521*0b57cec5SDimitry Andric   for (auto *Loop : llvm::reverse(Loops)) {
522*0b57cec5SDimitry Andric     PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get());
523*0b57cec5SDimitry Andric     Promoter.run(&TotalCountersPromoted);
524*0b57cec5SDimitry Andric   }
525*0b57cec5SDimitry Andric }
526*0b57cec5SDimitry Andric 
527349cc55cSDimitry Andric static bool needsRuntimeHookUnconditionally(const Triple &TT) {
528349cc55cSDimitry Andric   // On Fuchsia, we only need runtime hook if any counters are present.
529349cc55cSDimitry Andric   if (TT.isOSFuchsia())
530349cc55cSDimitry Andric     return false;
531349cc55cSDimitry Andric 
532349cc55cSDimitry Andric   return true;
533349cc55cSDimitry Andric }
534349cc55cSDimitry Andric 
535*0b57cec5SDimitry Andric /// Check if the module contains uses of any profiling intrinsics.
536*0b57cec5SDimitry Andric static bool containsProfilingIntrinsics(Module &M) {
53704eeddc0SDimitry Andric   auto containsIntrinsic = [&](int ID) {
53804eeddc0SDimitry Andric     if (auto *F = M.getFunction(Intrinsic::getName(ID)))
53904eeddc0SDimitry Andric       return !F->use_empty();
540*0b57cec5SDimitry Andric     return false;
54104eeddc0SDimitry Andric   };
54204eeddc0SDimitry Andric   return containsIntrinsic(llvm::Intrinsic::instrprof_increment) ||
54304eeddc0SDimitry Andric          containsIntrinsic(llvm::Intrinsic::instrprof_increment_step) ||
54404eeddc0SDimitry Andric          containsIntrinsic(llvm::Intrinsic::instrprof_value_profile);
545*0b57cec5SDimitry Andric }
546*0b57cec5SDimitry Andric 
5478bcb0991SDimitry Andric bool InstrProfiling::run(
5488bcb0991SDimitry Andric     Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
549*0b57cec5SDimitry Andric   this->M = &M;
5508bcb0991SDimitry Andric   this->GetTLI = std::move(GetTLI);
551*0b57cec5SDimitry Andric   NamesVar = nullptr;
552*0b57cec5SDimitry Andric   NamesSize = 0;
553*0b57cec5SDimitry Andric   ProfileDataMap.clear();
554fe6060f1SDimitry Andric   CompilerUsedVars.clear();
555*0b57cec5SDimitry Andric   UsedVars.clear();
556*0b57cec5SDimitry Andric   TT = Triple(M.getTargetTriple());
557*0b57cec5SDimitry Andric 
558349cc55cSDimitry Andric   bool MadeChange = false;
559349cc55cSDimitry Andric 
560*0b57cec5SDimitry Andric   // Emit the runtime hook even if no counters are present.
561349cc55cSDimitry Andric   if (needsRuntimeHookUnconditionally(TT))
562349cc55cSDimitry Andric     MadeChange = emitRuntimeHook();
563*0b57cec5SDimitry Andric 
564*0b57cec5SDimitry Andric   // Improve compile time by avoiding linear scans when there is no work.
565*0b57cec5SDimitry Andric   GlobalVariable *CoverageNamesVar =
566*0b57cec5SDimitry Andric       M.getNamedGlobal(getCoverageUnusedNamesVarName());
567*0b57cec5SDimitry Andric   if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
568*0b57cec5SDimitry Andric     return MadeChange;
569*0b57cec5SDimitry Andric 
570*0b57cec5SDimitry Andric   // We did not know how many value sites there would be inside
571*0b57cec5SDimitry Andric   // the instrumented function. This is counting the number of instrumented
572*0b57cec5SDimitry Andric   // target value sites to enter it as field in the profile data variable.
573*0b57cec5SDimitry Andric   for (Function &F : M) {
574*0b57cec5SDimitry Andric     InstrProfIncrementInst *FirstProfIncInst = nullptr;
575*0b57cec5SDimitry Andric     for (BasicBlock &BB : F)
576*0b57cec5SDimitry Andric       for (auto I = BB.begin(), E = BB.end(); I != E; I++)
577*0b57cec5SDimitry Andric         if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
578*0b57cec5SDimitry Andric           computeNumValueSiteCounts(Ind);
579*0b57cec5SDimitry Andric         else if (FirstProfIncInst == nullptr)
580*0b57cec5SDimitry Andric           FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
581*0b57cec5SDimitry Andric 
582*0b57cec5SDimitry Andric     // Value profiling intrinsic lowering requires per-function profile data
583*0b57cec5SDimitry Andric     // variable to be created first.
584*0b57cec5SDimitry Andric     if (FirstProfIncInst != nullptr)
585*0b57cec5SDimitry Andric       static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
586*0b57cec5SDimitry Andric   }
587*0b57cec5SDimitry Andric 
588*0b57cec5SDimitry Andric   for (Function &F : M)
589*0b57cec5SDimitry Andric     MadeChange |= lowerIntrinsics(&F);
590*0b57cec5SDimitry Andric 
591*0b57cec5SDimitry Andric   if (CoverageNamesVar) {
592*0b57cec5SDimitry Andric     lowerCoverageData(CoverageNamesVar);
593*0b57cec5SDimitry Andric     MadeChange = true;
594*0b57cec5SDimitry Andric   }
595*0b57cec5SDimitry Andric 
596*0b57cec5SDimitry Andric   if (!MadeChange)
597*0b57cec5SDimitry Andric     return false;
598*0b57cec5SDimitry Andric 
599*0b57cec5SDimitry Andric   emitVNodes();
600*0b57cec5SDimitry Andric   emitNameData();
601349cc55cSDimitry Andric   emitRuntimeHook();
602*0b57cec5SDimitry Andric   emitRegistration();
603*0b57cec5SDimitry Andric   emitUses();
604*0b57cec5SDimitry Andric   emitInitialization();
605*0b57cec5SDimitry Andric   return true;
606*0b57cec5SDimitry Andric }
607*0b57cec5SDimitry Andric 
608e8d8bef9SDimitry Andric static FunctionCallee getOrInsertValueProfilingCall(
609e8d8bef9SDimitry Andric     Module &M, const TargetLibraryInfo &TLI,
610e8d8bef9SDimitry Andric     ValueProfilingCallType CallType = ValueProfilingCallType::Default) {
611*0b57cec5SDimitry Andric   LLVMContext &Ctx = M.getContext();
612*0b57cec5SDimitry Andric   auto *ReturnTy = Type::getVoidTy(M.getContext());
613*0b57cec5SDimitry Andric 
614*0b57cec5SDimitry Andric   AttributeList AL;
615*0b57cec5SDimitry Andric   if (auto AK = TLI.getExtAttrForI32Param(false))
616*0b57cec5SDimitry Andric     AL = AL.addParamAttribute(M.getContext(), 2, AK);
617*0b57cec5SDimitry Andric 
618e8d8bef9SDimitry Andric   assert((CallType == ValueProfilingCallType::Default ||
619e8d8bef9SDimitry Andric           CallType == ValueProfilingCallType::MemOp) &&
620e8d8bef9SDimitry Andric          "Must be Default or MemOp");
621*0b57cec5SDimitry Andric   Type *ParamTypes[] = {
622*0b57cec5SDimitry Andric #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
623*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
624*0b57cec5SDimitry Andric   };
625*0b57cec5SDimitry Andric   auto *ValueProfilingCallTy =
626*0b57cec5SDimitry Andric       FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
627e8d8bef9SDimitry Andric   StringRef FuncName = CallType == ValueProfilingCallType::Default
628e8d8bef9SDimitry Andric                            ? getInstrProfValueProfFuncName()
629e8d8bef9SDimitry Andric                            : getInstrProfValueProfMemOpFuncName();
630e8d8bef9SDimitry Andric   return M.getOrInsertFunction(FuncName, ValueProfilingCallTy, AL);
631*0b57cec5SDimitry Andric }
632*0b57cec5SDimitry Andric 
633*0b57cec5SDimitry Andric void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
634*0b57cec5SDimitry Andric   GlobalVariable *Name = Ind->getName();
635*0b57cec5SDimitry Andric   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
636*0b57cec5SDimitry Andric   uint64_t Index = Ind->getIndex()->getZExtValue();
6374824e7fdSDimitry Andric   auto &PD = ProfileDataMap[Name];
6384824e7fdSDimitry Andric   PD.NumValueSites[ValueKind] =
6394824e7fdSDimitry Andric       std::max(PD.NumValueSites[ValueKind], (uint32_t)(Index + 1));
640*0b57cec5SDimitry Andric }
641*0b57cec5SDimitry Andric 
642*0b57cec5SDimitry Andric void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
6430eae32dcSDimitry Andric   // TODO: Value profiling heavily depends on the data section which is omitted
6440eae32dcSDimitry Andric   // in lightweight mode. We need to move the value profile pointer to the
6450eae32dcSDimitry Andric   // Counter struct to get this working.
6460eae32dcSDimitry Andric   assert(
6470eae32dcSDimitry Andric       !DebugInfoCorrelate &&
6480eae32dcSDimitry Andric       "Value profiling is not yet supported with lightweight instrumentation");
649*0b57cec5SDimitry Andric   GlobalVariable *Name = Ind->getName();
650*0b57cec5SDimitry Andric   auto It = ProfileDataMap.find(Name);
651*0b57cec5SDimitry Andric   assert(It != ProfileDataMap.end() && It->second.DataVar &&
652*0b57cec5SDimitry Andric          "value profiling detected in function with no counter incerement");
653*0b57cec5SDimitry Andric 
654*0b57cec5SDimitry Andric   GlobalVariable *DataVar = It->second.DataVar;
655*0b57cec5SDimitry Andric   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
656*0b57cec5SDimitry Andric   uint64_t Index = Ind->getIndex()->getZExtValue();
657*0b57cec5SDimitry Andric   for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
658*0b57cec5SDimitry Andric     Index += It->second.NumValueSites[Kind];
659*0b57cec5SDimitry Andric 
660*0b57cec5SDimitry Andric   IRBuilder<> Builder(Ind);
661e8d8bef9SDimitry Andric   bool IsMemOpSize = (Ind->getValueKind()->getZExtValue() ==
662*0b57cec5SDimitry Andric                       llvm::InstrProfValueKind::IPVK_MemOPSize);
663*0b57cec5SDimitry Andric   CallInst *Call = nullptr;
6648bcb0991SDimitry Andric   auto *TLI = &GetTLI(*Ind->getFunction());
6655ffd83dbSDimitry Andric 
6665ffd83dbSDimitry Andric   // To support value profiling calls within Windows exception handlers, funclet
6675ffd83dbSDimitry Andric   // information contained within operand bundles needs to be copied over to
6685ffd83dbSDimitry Andric   // the library call. This is required for the IR to be processed by the
6695ffd83dbSDimitry Andric   // WinEHPrepare pass.
6705ffd83dbSDimitry Andric   SmallVector<OperandBundleDef, 1> OpBundles;
6715ffd83dbSDimitry Andric   Ind->getOperandBundlesAsDefs(OpBundles);
672e8d8bef9SDimitry Andric   if (!IsMemOpSize) {
673*0b57cec5SDimitry Andric     Value *Args[3] = {Ind->getTargetValue(),
674*0b57cec5SDimitry Andric                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
675*0b57cec5SDimitry Andric                       Builder.getInt32(Index)};
6765ffd83dbSDimitry Andric     Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args,
6775ffd83dbSDimitry Andric                               OpBundles);
678*0b57cec5SDimitry Andric   } else {
679e8d8bef9SDimitry Andric     Value *Args[3] = {Ind->getTargetValue(),
680*0b57cec5SDimitry Andric                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
681e8d8bef9SDimitry Andric                       Builder.getInt32(Index)};
682e8d8bef9SDimitry Andric     Call = Builder.CreateCall(
683e8d8bef9SDimitry Andric         getOrInsertValueProfilingCall(*M, *TLI, ValueProfilingCallType::MemOp),
6845ffd83dbSDimitry Andric         Args, OpBundles);
685*0b57cec5SDimitry Andric   }
686*0b57cec5SDimitry Andric   if (auto AK = TLI->getExtAttrForI32Param(false))
687*0b57cec5SDimitry Andric     Call->addParamAttr(2, AK);
688*0b57cec5SDimitry Andric   Ind->replaceAllUsesWith(Call);
689*0b57cec5SDimitry Andric   Ind->eraseFromParent();
690*0b57cec5SDimitry Andric }
691*0b57cec5SDimitry Andric 
692*0b57cec5SDimitry Andric void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
693*0b57cec5SDimitry Andric   GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
694*0b57cec5SDimitry Andric 
695*0b57cec5SDimitry Andric   IRBuilder<> Builder(Inc);
696*0b57cec5SDimitry Andric   uint64_t Index = Inc->getIndex()->getZExtValue();
6975e801ac6SDimitry Andric   Value *Addr = Builder.CreateConstInBoundsGEP2_32(Counters->getValueType(),
698*0b57cec5SDimitry Andric                                                    Counters, 0, Index);
699*0b57cec5SDimitry Andric 
7005ffd83dbSDimitry Andric   if (isRuntimeCounterRelocationEnabled()) {
7015ffd83dbSDimitry Andric     Type *Int64Ty = Type::getInt64Ty(M->getContext());
7025ffd83dbSDimitry Andric     Type *Int64PtrTy = Type::getInt64PtrTy(M->getContext());
7035ffd83dbSDimitry Andric     Function *Fn = Inc->getParent()->getParent();
7045ffd83dbSDimitry Andric     Instruction &I = Fn->getEntryBlock().front();
7055ffd83dbSDimitry Andric     LoadInst *LI = dyn_cast<LoadInst>(&I);
7065ffd83dbSDimitry Andric     if (!LI) {
7075ffd83dbSDimitry Andric       IRBuilder<> Builder(&I);
7084824e7fdSDimitry Andric       GlobalVariable *Bias =
7094824e7fdSDimitry Andric           M->getGlobalVariable(getInstrProfCounterBiasVarName());
7105ffd83dbSDimitry Andric       if (!Bias) {
711fe6060f1SDimitry Andric         // Compiler must define this variable when runtime counter relocation
712fe6060f1SDimitry Andric         // is being used. Runtime has a weak external reference that is used
713fe6060f1SDimitry Andric         // to check whether that's the case or not.
7144824e7fdSDimitry Andric         Bias = new GlobalVariable(
7154824e7fdSDimitry Andric             *M, Int64Ty, false, GlobalValue::LinkOnceODRLinkage,
7164824e7fdSDimitry Andric             Constant::getNullValue(Int64Ty), getInstrProfCounterBiasVarName());
7175ffd83dbSDimitry Andric         Bias->setVisibility(GlobalVariable::HiddenVisibility);
718fe6060f1SDimitry Andric         // A definition that's weak (linkonce_odr) without being in a COMDAT
719fe6060f1SDimitry Andric         // section wouldn't lead to link errors, but it would lead to a dead
720fe6060f1SDimitry Andric         // data word from every TU but one. Putting it in COMDAT ensures there
721fe6060f1SDimitry Andric         // will be exactly one data slot in the link.
722fe6060f1SDimitry Andric         if (TT.supportsCOMDAT())
723fe6060f1SDimitry Andric           Bias->setComdat(M->getOrInsertComdat(Bias->getName()));
7245ffd83dbSDimitry Andric       }
7255ffd83dbSDimitry Andric       LI = Builder.CreateLoad(Int64Ty, Bias);
7265ffd83dbSDimitry Andric     }
7275ffd83dbSDimitry Andric     auto *Add = Builder.CreateAdd(Builder.CreatePtrToInt(Addr, Int64Ty), LI);
7285ffd83dbSDimitry Andric     Addr = Builder.CreateIntToPtr(Add, Int64PtrTy);
7295ffd83dbSDimitry Andric   }
7305ffd83dbSDimitry Andric 
7315ffd83dbSDimitry Andric   if (Options.Atomic || AtomicCounterUpdateAll ||
7325ffd83dbSDimitry Andric       (Index == 0 && AtomicFirstCounter)) {
733*0b57cec5SDimitry Andric     Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
734fe6060f1SDimitry Andric                             MaybeAlign(), AtomicOrdering::Monotonic);
735*0b57cec5SDimitry Andric   } else {
736*0b57cec5SDimitry Andric     Value *IncStep = Inc->getStep();
737*0b57cec5SDimitry Andric     Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
738*0b57cec5SDimitry Andric     auto *Count = Builder.CreateAdd(Load, Inc->getStep());
739*0b57cec5SDimitry Andric     auto *Store = Builder.CreateStore(Count, Addr);
740*0b57cec5SDimitry Andric     if (isCounterPromotionEnabled())
741*0b57cec5SDimitry Andric       PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
742*0b57cec5SDimitry Andric   }
743*0b57cec5SDimitry Andric   Inc->eraseFromParent();
744*0b57cec5SDimitry Andric }
745*0b57cec5SDimitry Andric 
746*0b57cec5SDimitry Andric void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
747*0b57cec5SDimitry Andric   ConstantArray *Names =
748*0b57cec5SDimitry Andric       cast<ConstantArray>(CoverageNamesVar->getInitializer());
749*0b57cec5SDimitry Andric   for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
750*0b57cec5SDimitry Andric     Constant *NC = Names->getOperand(I);
751*0b57cec5SDimitry Andric     Value *V = NC->stripPointerCasts();
752*0b57cec5SDimitry Andric     assert(isa<GlobalVariable>(V) && "Missing reference to function name");
753*0b57cec5SDimitry Andric     GlobalVariable *Name = cast<GlobalVariable>(V);
754*0b57cec5SDimitry Andric 
755*0b57cec5SDimitry Andric     Name->setLinkage(GlobalValue::PrivateLinkage);
756*0b57cec5SDimitry Andric     ReferencedNames.push_back(Name);
757*0b57cec5SDimitry Andric     NC->dropAllReferences();
758*0b57cec5SDimitry Andric   }
759*0b57cec5SDimitry Andric   CoverageNamesVar->eraseFromParent();
760*0b57cec5SDimitry Andric }
761*0b57cec5SDimitry Andric 
762*0b57cec5SDimitry Andric /// Get the name of a profiling variable for a particular function.
76304eeddc0SDimitry Andric static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix,
764349cc55cSDimitry Andric                               bool &Renamed) {
765*0b57cec5SDimitry Andric   StringRef NamePrefix = getInstrProfNameVarPrefix();
766*0b57cec5SDimitry Andric   StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
767*0b57cec5SDimitry Andric   Function *F = Inc->getParent()->getParent();
768*0b57cec5SDimitry Andric   Module *M = F->getParent();
769*0b57cec5SDimitry Andric   if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
770349cc55cSDimitry Andric       !canRenameComdatFunc(*F)) {
771349cc55cSDimitry Andric     Renamed = false;
772*0b57cec5SDimitry Andric     return (Prefix + Name).str();
773349cc55cSDimitry Andric   }
774349cc55cSDimitry Andric   Renamed = true;
775*0b57cec5SDimitry Andric   uint64_t FuncHash = Inc->getHash()->getZExtValue();
776*0b57cec5SDimitry Andric   SmallVector<char, 24> HashPostfix;
777*0b57cec5SDimitry Andric   if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
778*0b57cec5SDimitry Andric     return (Prefix + Name).str();
779*0b57cec5SDimitry Andric   return (Prefix + Name + "." + Twine(FuncHash)).str();
780*0b57cec5SDimitry Andric }
781*0b57cec5SDimitry Andric 
782fe6060f1SDimitry Andric static uint64_t getIntModuleFlagOrZero(const Module &M, StringRef Flag) {
783fe6060f1SDimitry Andric   auto *MD = dyn_cast_or_null<ConstantAsMetadata>(M.getModuleFlag(Flag));
784fe6060f1SDimitry Andric   if (!MD)
785fe6060f1SDimitry Andric     return 0;
786fe6060f1SDimitry Andric 
787fe6060f1SDimitry Andric   // If the flag is a ConstantAsMetadata, it should be an integer representable
788fe6060f1SDimitry Andric   // in 64-bits.
789fe6060f1SDimitry Andric   return cast<ConstantInt>(MD->getValue())->getZExtValue();
790fe6060f1SDimitry Andric }
791fe6060f1SDimitry Andric 
792fe6060f1SDimitry Andric static bool enablesValueProfiling(const Module &M) {
793fe6060f1SDimitry Andric   return isIRPGOFlagSet(&M) ||
794fe6060f1SDimitry Andric          getIntModuleFlagOrZero(M, "EnableValueProfiling") != 0;
795fe6060f1SDimitry Andric }
796fe6060f1SDimitry Andric 
797fe6060f1SDimitry Andric // Conservatively returns true if data variables may be referenced by code.
798fe6060f1SDimitry Andric static bool profDataReferencedByCode(const Module &M) {
799fe6060f1SDimitry Andric   return enablesValueProfiling(M);
800fe6060f1SDimitry Andric }
801fe6060f1SDimitry Andric 
802*0b57cec5SDimitry Andric static inline bool shouldRecordFunctionAddr(Function *F) {
803fe6060f1SDimitry Andric   // Only record function addresses if IR PGO is enabled or if clang value
804fe6060f1SDimitry Andric   // profiling is enabled. Recording function addresses greatly increases object
805fe6060f1SDimitry Andric   // file size, because it prevents the inliner from deleting functions that
806fe6060f1SDimitry Andric   // have been inlined everywhere.
807fe6060f1SDimitry Andric   if (!profDataReferencedByCode(*F->getParent()))
808fe6060f1SDimitry Andric     return false;
809fe6060f1SDimitry Andric 
810*0b57cec5SDimitry Andric   // Check the linkage
811*0b57cec5SDimitry Andric   bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
812*0b57cec5SDimitry Andric   if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
813*0b57cec5SDimitry Andric       !HasAvailableExternallyLinkage)
814*0b57cec5SDimitry Andric     return true;
815*0b57cec5SDimitry Andric 
816*0b57cec5SDimitry Andric   // A function marked 'alwaysinline' with available_externally linkage can't
817*0b57cec5SDimitry Andric   // have its address taken. Doing so would create an undefined external ref to
818*0b57cec5SDimitry Andric   // the function, which would fail to link.
819*0b57cec5SDimitry Andric   if (HasAvailableExternallyLinkage &&
820*0b57cec5SDimitry Andric       F->hasFnAttribute(Attribute::AlwaysInline))
821*0b57cec5SDimitry Andric     return false;
822*0b57cec5SDimitry Andric 
823*0b57cec5SDimitry Andric   // Prohibit function address recording if the function is both internal and
824*0b57cec5SDimitry Andric   // COMDAT. This avoids the profile data variable referencing internal symbols
825*0b57cec5SDimitry Andric   // in COMDAT.
826*0b57cec5SDimitry Andric   if (F->hasLocalLinkage() && F->hasComdat())
827*0b57cec5SDimitry Andric     return false;
828*0b57cec5SDimitry Andric 
829*0b57cec5SDimitry Andric   // Check uses of this function for other than direct calls or invokes to it.
830*0b57cec5SDimitry Andric   // Inline virtual functions have linkeOnceODR linkage. When a key method
831*0b57cec5SDimitry Andric   // exists, the vtable will only be emitted in the TU where the key method
832*0b57cec5SDimitry Andric   // is defined. In a TU where vtable is not available, the function won't
833*0b57cec5SDimitry Andric   // be 'addresstaken'. If its address is not recorded here, the profile data
834*0b57cec5SDimitry Andric   // with missing address may be picked by the linker leading  to missing
835*0b57cec5SDimitry Andric   // indirect call target info.
836*0b57cec5SDimitry Andric   return F->hasAddressTaken() || F->hasLinkOnceLinkage();
837*0b57cec5SDimitry Andric }
838*0b57cec5SDimitry Andric 
839*0b57cec5SDimitry Andric static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT) {
840*0b57cec5SDimitry Andric   // Don't do this for Darwin.  compiler-rt uses linker magic.
841*0b57cec5SDimitry Andric   if (TT.isOSDarwin())
842*0b57cec5SDimitry Andric     return false;
843*0b57cec5SDimitry Andric   // Use linker script magic to get data/cnts/name start/end.
844*0b57cec5SDimitry Andric   if (TT.isOSLinux() || TT.isOSFreeBSD() || TT.isOSNetBSD() ||
8454824e7fdSDimitry Andric       TT.isOSSolaris() || TT.isOSFuchsia() || TT.isPS4CPU() || TT.isOSWindows())
846*0b57cec5SDimitry Andric     return false;
847*0b57cec5SDimitry Andric 
848*0b57cec5SDimitry Andric   return true;
849*0b57cec5SDimitry Andric }
850*0b57cec5SDimitry Andric 
851*0b57cec5SDimitry Andric GlobalVariable *
85204eeddc0SDimitry Andric InstrProfiling::getOrCreateRegionCounters(InstrProfInstBase *Inc) {
853*0b57cec5SDimitry Andric   GlobalVariable *NamePtr = Inc->getName();
8544824e7fdSDimitry Andric   auto &PD = ProfileDataMap[NamePtr];
8554824e7fdSDimitry Andric   if (PD.RegionCounters)
8564824e7fdSDimitry Andric     return PD.RegionCounters;
857*0b57cec5SDimitry Andric 
858fe6060f1SDimitry Andric   // Match the linkage and visibility of the name global.
859*0b57cec5SDimitry Andric   Function *Fn = Inc->getParent()->getParent();
860*0b57cec5SDimitry Andric   GlobalValue::LinkageTypes Linkage = NamePtr->getLinkage();
861*0b57cec5SDimitry Andric   GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
862*0b57cec5SDimitry Andric 
8630eae32dcSDimitry Andric   // Use internal rather than private linkage so the counter variable shows up
8640eae32dcSDimitry Andric   // in the symbol table when using debug info for correlation.
8650eae32dcSDimitry Andric   if (DebugInfoCorrelate && TT.isOSBinFormatMachO() &&
8660eae32dcSDimitry Andric       Linkage == GlobalValue::PrivateLinkage)
8670eae32dcSDimitry Andric     Linkage = GlobalValue::InternalLinkage;
8680eae32dcSDimitry Andric 
869349cc55cSDimitry Andric   // Due to the limitation of binder as of 2021/09/28, the duplicate weak
870349cc55cSDimitry Andric   // symbols in the same csect won't be discarded. When there are duplicate weak
871349cc55cSDimitry Andric   // symbols, we can NOT guarantee that the relocations get resolved to the
872349cc55cSDimitry Andric   // intended weak symbol, so we can not ensure the correctness of the relative
873349cc55cSDimitry Andric   // CounterPtr, so we have to use private linkage for counter and data symbols.
874349cc55cSDimitry Andric   if (TT.isOSBinFormatXCOFF()) {
875349cc55cSDimitry Andric     Linkage = GlobalValue::PrivateLinkage;
876349cc55cSDimitry Andric     Visibility = GlobalValue::DefaultVisibility;
877349cc55cSDimitry Andric   }
878*0b57cec5SDimitry Andric   // Move the name variable to the right section. Place them in a COMDAT group
879*0b57cec5SDimitry Andric   // if the associated function is a COMDAT. This will make sure that only one
880*0b57cec5SDimitry Andric   // copy of counters of the COMDAT function will be emitted after linking. Keep
881*0b57cec5SDimitry Andric   // in mind that this pass may run before the inliner, so we need to create a
882*0b57cec5SDimitry Andric   // new comdat group for the counters and profiling data. If we use the comdat
883*0b57cec5SDimitry Andric   // of the parent function, that will result in relocations against discarded
884*0b57cec5SDimitry Andric   // sections.
885fe6060f1SDimitry Andric   //
886fe6060f1SDimitry Andric   // If the data variable is referenced by code,  counters and data have to be
887fe6060f1SDimitry Andric   // in different comdats for COFF because the Visual C++ linker will report
888fe6060f1SDimitry Andric   // duplicate symbol errors if there are multiple external symbols with the
889fe6060f1SDimitry Andric   // same name marked IMAGE_COMDAT_SELECT_ASSOCIATIVE.
890fe6060f1SDimitry Andric   //
891fe6060f1SDimitry Andric   // For ELF, when not using COMDAT, put counters, data and values into a
892fe6060f1SDimitry Andric   // nodeduplicate COMDAT which is lowered to a zero-flag section group. This
893fe6060f1SDimitry Andric   // allows -z start-stop-gc to discard the entire group when the function is
894fe6060f1SDimitry Andric   // discarded.
895fe6060f1SDimitry Andric   bool DataReferencedByCode = profDataReferencedByCode(*M);
896c14a5a88SDimitry Andric   bool NeedComdat = needsComdatForCounter(*Fn, *M);
897349cc55cSDimitry Andric   bool Renamed;
898349cc55cSDimitry Andric   std::string CntsVarName =
899349cc55cSDimitry Andric       getVarName(Inc, getInstrProfCountersVarPrefix(), Renamed);
900349cc55cSDimitry Andric   std::string DataVarName =
901349cc55cSDimitry Andric       getVarName(Inc, getInstrProfDataVarPrefix(), Renamed);
902fe6060f1SDimitry Andric   auto MaybeSetComdat = [&](GlobalVariable *GV) {
903fe6060f1SDimitry Andric     bool UseComdat = (NeedComdat || TT.isOSBinFormatELF());
904fe6060f1SDimitry Andric     if (UseComdat) {
905fe6060f1SDimitry Andric       StringRef GroupName = TT.isOSBinFormatCOFF() && DataReferencedByCode
906fe6060f1SDimitry Andric                                 ? GV->getName()
907fe6060f1SDimitry Andric                                 : CntsVarName;
908fe6060f1SDimitry Andric       Comdat *C = M->getOrInsertComdat(GroupName);
909fe6060f1SDimitry Andric       if (!NeedComdat)
910fe6060f1SDimitry Andric         C->setSelectionKind(Comdat::NoDeduplicate);
911fe6060f1SDimitry Andric       GV->setComdat(C);
912fe6060f1SDimitry Andric     }
913c14a5a88SDimitry Andric   };
914*0b57cec5SDimitry Andric 
915*0b57cec5SDimitry Andric   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
916*0b57cec5SDimitry Andric   LLVMContext &Ctx = M->getContext();
917*0b57cec5SDimitry Andric   ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
918*0b57cec5SDimitry Andric 
919*0b57cec5SDimitry Andric   // Create the counters variable.
920*0b57cec5SDimitry Andric   auto *CounterPtr =
921*0b57cec5SDimitry Andric       new GlobalVariable(*M, CounterTy, false, Linkage,
922fe6060f1SDimitry Andric                          Constant::getNullValue(CounterTy), CntsVarName);
923*0b57cec5SDimitry Andric   CounterPtr->setVisibility(Visibility);
924*0b57cec5SDimitry Andric   CounterPtr->setSection(
925*0b57cec5SDimitry Andric       getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
9268bcb0991SDimitry Andric   CounterPtr->setAlignment(Align(8));
927c14a5a88SDimitry Andric   MaybeSetComdat(CounterPtr);
928c14a5a88SDimitry Andric   CounterPtr->setLinkage(Linkage);
9294824e7fdSDimitry Andric   PD.RegionCounters = CounterPtr;
9300eae32dcSDimitry Andric   if (DebugInfoCorrelate) {
9310eae32dcSDimitry Andric     if (auto *SP = Fn->getSubprogram()) {
9320eae32dcSDimitry Andric       DIBuilder DB(*M, true, SP->getUnit());
9330eae32dcSDimitry Andric       Metadata *FunctionNameAnnotation[] = {
9340eae32dcSDimitry Andric           MDString::get(Ctx, InstrProfCorrelator::FunctionNameAttributeName),
9350eae32dcSDimitry Andric           MDString::get(Ctx, getPGOFuncNameVarInitializer(NamePtr)),
9360eae32dcSDimitry Andric       };
9370eae32dcSDimitry Andric       Metadata *CFGHashAnnotation[] = {
9380eae32dcSDimitry Andric           MDString::get(Ctx, InstrProfCorrelator::CFGHashAttributeName),
9390eae32dcSDimitry Andric           ConstantAsMetadata::get(Inc->getHash()),
9400eae32dcSDimitry Andric       };
9410eae32dcSDimitry Andric       Metadata *NumCountersAnnotation[] = {
9420eae32dcSDimitry Andric           MDString::get(Ctx, InstrProfCorrelator::NumCountersAttributeName),
9430eae32dcSDimitry Andric           ConstantAsMetadata::get(Inc->getNumCounters()),
9440eae32dcSDimitry Andric       };
9450eae32dcSDimitry Andric       auto Annotations = DB.getOrCreateArray({
9460eae32dcSDimitry Andric           MDNode::get(Ctx, FunctionNameAnnotation),
9470eae32dcSDimitry Andric           MDNode::get(Ctx, CFGHashAnnotation),
9480eae32dcSDimitry Andric           MDNode::get(Ctx, NumCountersAnnotation),
9490eae32dcSDimitry Andric       });
9500eae32dcSDimitry Andric       auto *DICounter = DB.createGlobalVariableExpression(
9510eae32dcSDimitry Andric           SP, CounterPtr->getName(), /*LinkageName=*/StringRef(), SP->getFile(),
9520eae32dcSDimitry Andric           /*LineNo=*/0, DB.createUnspecifiedType("Profile Data Type"),
9530eae32dcSDimitry Andric           CounterPtr->hasLocalLinkage(), /*IsDefined=*/true, /*Expr=*/nullptr,
9540eae32dcSDimitry Andric           /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
9550eae32dcSDimitry Andric           Annotations);
9560eae32dcSDimitry Andric       CounterPtr->addDebugInfo(DICounter);
9570eae32dcSDimitry Andric       DB.finalize();
9580eae32dcSDimitry Andric     } else {
9590eae32dcSDimitry Andric       std::string Msg = ("Missing debug info for function " + Fn->getName() +
9600eae32dcSDimitry Andric                          "; required for profile correlation.")
9610eae32dcSDimitry Andric                             .str();
9620eae32dcSDimitry Andric       Ctx.diagnose(
9630eae32dcSDimitry Andric           DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
9640eae32dcSDimitry Andric     }
9650eae32dcSDimitry Andric   }
966*0b57cec5SDimitry Andric 
967*0b57cec5SDimitry Andric   auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
968*0b57cec5SDimitry Andric   // Allocate statically the array of pointers to value profile nodes for
969*0b57cec5SDimitry Andric   // the current function.
970*0b57cec5SDimitry Andric   Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
971*0b57cec5SDimitry Andric   uint64_t NS = 0;
972*0b57cec5SDimitry Andric   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
973*0b57cec5SDimitry Andric     NS += PD.NumValueSites[Kind];
974fe6060f1SDimitry Andric   if (NS > 0 && ValueProfileStaticAlloc &&
975fe6060f1SDimitry Andric       !needsRuntimeRegistrationOfSectionRange(TT)) {
976*0b57cec5SDimitry Andric     ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
977fe6060f1SDimitry Andric     auto *ValuesVar = new GlobalVariable(
978fe6060f1SDimitry Andric         *M, ValuesTy, false, Linkage, Constant::getNullValue(ValuesTy),
979349cc55cSDimitry Andric         getVarName(Inc, getInstrProfValuesVarPrefix(), Renamed));
980*0b57cec5SDimitry Andric     ValuesVar->setVisibility(Visibility);
981*0b57cec5SDimitry Andric     ValuesVar->setSection(
982*0b57cec5SDimitry Andric         getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
9838bcb0991SDimitry Andric     ValuesVar->setAlignment(Align(8));
984c14a5a88SDimitry Andric     MaybeSetComdat(ValuesVar);
985*0b57cec5SDimitry Andric     ValuesPtrExpr =
986*0b57cec5SDimitry Andric         ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
987*0b57cec5SDimitry Andric   }
988*0b57cec5SDimitry Andric 
98904eeddc0SDimitry Andric   if (DebugInfoCorrelate) {
99004eeddc0SDimitry Andric     // Mark the counter variable as used so that it isn't optimized out.
99104eeddc0SDimitry Andric     CompilerUsedVars.push_back(PD.RegionCounters);
9920eae32dcSDimitry Andric     return PD.RegionCounters;
99304eeddc0SDimitry Andric   }
9940eae32dcSDimitry Andric 
995*0b57cec5SDimitry Andric   // Create data variable.
996349cc55cSDimitry Andric   auto *IntPtrTy = M->getDataLayout().getIntPtrType(M->getContext());
997*0b57cec5SDimitry Andric   auto *Int16Ty = Type::getInt16Ty(Ctx);
998*0b57cec5SDimitry Andric   auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
999*0b57cec5SDimitry Andric   Type *DataTypes[] = {
1000*0b57cec5SDimitry Andric #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
1001*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
1002*0b57cec5SDimitry Andric   };
1003*0b57cec5SDimitry Andric   auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
1004*0b57cec5SDimitry Andric 
1005*0b57cec5SDimitry Andric   Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
1006*0b57cec5SDimitry Andric                                ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
1007*0b57cec5SDimitry Andric                                : ConstantPointerNull::get(Int8PtrTy);
1008*0b57cec5SDimitry Andric 
1009*0b57cec5SDimitry Andric   Constant *Int16ArrayVals[IPVK_Last + 1];
1010*0b57cec5SDimitry Andric   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1011*0b57cec5SDimitry Andric     Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
1012*0b57cec5SDimitry Andric 
1013fe6060f1SDimitry Andric   // If the data variable is not referenced by code (if we don't emit
1014fe6060f1SDimitry Andric   // @llvm.instrprof.value.profile, NS will be 0), and the counter keeps the
1015fe6060f1SDimitry Andric   // data variable live under linker GC, the data variable can be private. This
1016fe6060f1SDimitry Andric   // optimization applies to ELF.
1017fe6060f1SDimitry Andric   //
1018fe6060f1SDimitry Andric   // On COFF, a comdat leader cannot be local so we require DataReferencedByCode
1019fe6060f1SDimitry Andric   // to be false.
1020349cc55cSDimitry Andric   //
1021349cc55cSDimitry Andric   // If profd is in a deduplicate comdat, NS==0 with a hash suffix guarantees
1022349cc55cSDimitry Andric   // that other copies must have the same CFG and cannot have value profiling.
1023349cc55cSDimitry Andric   // If no hash suffix, other profd copies may be referenced by code.
1024349cc55cSDimitry Andric   if (NS == 0 && !(DataReferencedByCode && NeedComdat && !Renamed) &&
1025349cc55cSDimitry Andric       (TT.isOSBinFormatELF() ||
1026fe6060f1SDimitry Andric        (!DataReferencedByCode && TT.isOSBinFormatCOFF()))) {
1027fe6060f1SDimitry Andric     Linkage = GlobalValue::PrivateLinkage;
1028fe6060f1SDimitry Andric     Visibility = GlobalValue::DefaultVisibility;
1029fe6060f1SDimitry Andric   }
1030e8d8bef9SDimitry Andric   auto *Data =
1031349cc55cSDimitry Andric       new GlobalVariable(*M, DataTy, false, Linkage, nullptr, DataVarName);
1032349cc55cSDimitry Andric   // Reference the counter variable with a label difference (link-time
1033349cc55cSDimitry Andric   // constant).
1034349cc55cSDimitry Andric   auto *RelativeCounterPtr =
1035349cc55cSDimitry Andric       ConstantExpr::getSub(ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy),
1036349cc55cSDimitry Andric                            ConstantExpr::getPtrToInt(Data, IntPtrTy));
1037349cc55cSDimitry Andric 
1038349cc55cSDimitry Andric   Constant *DataVals[] = {
1039349cc55cSDimitry Andric #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
1040349cc55cSDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
1041349cc55cSDimitry Andric   };
1042349cc55cSDimitry Andric   Data->setInitializer(ConstantStruct::get(DataTy, DataVals));
1043349cc55cSDimitry Andric 
1044*0b57cec5SDimitry Andric   Data->setVisibility(Visibility);
1045*0b57cec5SDimitry Andric   Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
10468bcb0991SDimitry Andric   Data->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
1047c14a5a88SDimitry Andric   MaybeSetComdat(Data);
1048c14a5a88SDimitry Andric   Data->setLinkage(Linkage);
1049*0b57cec5SDimitry Andric 
1050*0b57cec5SDimitry Andric   PD.DataVar = Data;
1051*0b57cec5SDimitry Andric 
1052*0b57cec5SDimitry Andric   // Mark the data variable as used so that it isn't stripped out.
1053fe6060f1SDimitry Andric   CompilerUsedVars.push_back(Data);
1054*0b57cec5SDimitry Andric   // Now that the linkage set by the FE has been passed to the data and counter
1055*0b57cec5SDimitry Andric   // variables, reset Name variable's linkage and visibility to private so that
1056*0b57cec5SDimitry Andric   // it can be removed later by the compiler.
1057*0b57cec5SDimitry Andric   NamePtr->setLinkage(GlobalValue::PrivateLinkage);
1058*0b57cec5SDimitry Andric   // Collect the referenced names to be used by emitNameData.
1059*0b57cec5SDimitry Andric   ReferencedNames.push_back(NamePtr);
1060*0b57cec5SDimitry Andric 
10614824e7fdSDimitry Andric   return PD.RegionCounters;
1062*0b57cec5SDimitry Andric }
1063*0b57cec5SDimitry Andric 
1064*0b57cec5SDimitry Andric void InstrProfiling::emitVNodes() {
1065*0b57cec5SDimitry Andric   if (!ValueProfileStaticAlloc)
1066*0b57cec5SDimitry Andric     return;
1067*0b57cec5SDimitry Andric 
1068*0b57cec5SDimitry Andric   // For now only support this on platforms that do
1069*0b57cec5SDimitry Andric   // not require runtime registration to discover
1070*0b57cec5SDimitry Andric   // named section start/end.
1071*0b57cec5SDimitry Andric   if (needsRuntimeRegistrationOfSectionRange(TT))
1072*0b57cec5SDimitry Andric     return;
1073*0b57cec5SDimitry Andric 
1074*0b57cec5SDimitry Andric   size_t TotalNS = 0;
1075*0b57cec5SDimitry Andric   for (auto &PD : ProfileDataMap) {
1076*0b57cec5SDimitry Andric     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1077*0b57cec5SDimitry Andric       TotalNS += PD.second.NumValueSites[Kind];
1078*0b57cec5SDimitry Andric   }
1079*0b57cec5SDimitry Andric 
1080*0b57cec5SDimitry Andric   if (!TotalNS)
1081*0b57cec5SDimitry Andric     return;
1082*0b57cec5SDimitry Andric 
1083*0b57cec5SDimitry Andric   uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
1084*0b57cec5SDimitry Andric // Heuristic for small programs with very few total value sites.
1085*0b57cec5SDimitry Andric // The default value of vp-counters-per-site is chosen based on
1086*0b57cec5SDimitry Andric // the observation that large apps usually have a low percentage
1087*0b57cec5SDimitry Andric // of value sites that actually have any profile data, and thus
1088*0b57cec5SDimitry Andric // the average number of counters per site is low. For small
1089*0b57cec5SDimitry Andric // apps with very few sites, this may not be true. Bump up the
1090*0b57cec5SDimitry Andric // number of counters in this case.
1091*0b57cec5SDimitry Andric #define INSTR_PROF_MIN_VAL_COUNTS 10
1092*0b57cec5SDimitry Andric   if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
1093*0b57cec5SDimitry Andric     NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
1094*0b57cec5SDimitry Andric 
1095*0b57cec5SDimitry Andric   auto &Ctx = M->getContext();
1096*0b57cec5SDimitry Andric   Type *VNodeTypes[] = {
1097*0b57cec5SDimitry Andric #define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
1098*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
1099*0b57cec5SDimitry Andric   };
1100*0b57cec5SDimitry Andric   auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
1101*0b57cec5SDimitry Andric 
1102*0b57cec5SDimitry Andric   ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
1103*0b57cec5SDimitry Andric   auto *VNodesVar = new GlobalVariable(
1104*0b57cec5SDimitry Andric       *M, VNodesTy, false, GlobalValue::PrivateLinkage,
1105*0b57cec5SDimitry Andric       Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
1106*0b57cec5SDimitry Andric   VNodesVar->setSection(
1107*0b57cec5SDimitry Andric       getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
1108fe6060f1SDimitry Andric   // VNodesVar is used by runtime but not referenced via relocation by other
1109fe6060f1SDimitry Andric   // sections. Conservatively make it linker retained.
1110*0b57cec5SDimitry Andric   UsedVars.push_back(VNodesVar);
1111*0b57cec5SDimitry Andric }
1112*0b57cec5SDimitry Andric 
1113*0b57cec5SDimitry Andric void InstrProfiling::emitNameData() {
1114*0b57cec5SDimitry Andric   std::string UncompressedData;
1115*0b57cec5SDimitry Andric 
1116*0b57cec5SDimitry Andric   if (ReferencedNames.empty())
1117*0b57cec5SDimitry Andric     return;
1118*0b57cec5SDimitry Andric 
1119*0b57cec5SDimitry Andric   std::string CompressedNameStr;
1120*0b57cec5SDimitry Andric   if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
11215ffd83dbSDimitry Andric                                           DoInstrProfNameCompression)) {
1122349cc55cSDimitry Andric     report_fatal_error(Twine(toString(std::move(E))), false);
1123*0b57cec5SDimitry Andric   }
1124*0b57cec5SDimitry Andric 
1125*0b57cec5SDimitry Andric   auto &Ctx = M->getContext();
11264824e7fdSDimitry Andric   auto *NamesVal =
11274824e7fdSDimitry Andric       ConstantDataArray::getString(Ctx, StringRef(CompressedNameStr), false);
1128*0b57cec5SDimitry Andric   NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
1129*0b57cec5SDimitry Andric                                 GlobalValue::PrivateLinkage, NamesVal,
1130*0b57cec5SDimitry Andric                                 getInstrProfNamesVarName());
1131*0b57cec5SDimitry Andric   NamesSize = CompressedNameStr.size();
1132*0b57cec5SDimitry Andric   NamesVar->setSection(
1133*0b57cec5SDimitry Andric       getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
1134*0b57cec5SDimitry Andric   // On COFF, it's important to reduce the alignment down to 1 to prevent the
1135*0b57cec5SDimitry Andric   // linker from inserting padding before the start of the names section or
1136*0b57cec5SDimitry Andric   // between names entries.
11375ffd83dbSDimitry Andric   NamesVar->setAlignment(Align(1));
1138fe6060f1SDimitry Andric   // NamesVar is used by runtime but not referenced via relocation by other
1139fe6060f1SDimitry Andric   // sections. Conservatively make it linker retained.
1140*0b57cec5SDimitry Andric   UsedVars.push_back(NamesVar);
1141*0b57cec5SDimitry Andric 
1142*0b57cec5SDimitry Andric   for (auto *NamePtr : ReferencedNames)
1143*0b57cec5SDimitry Andric     NamePtr->eraseFromParent();
1144*0b57cec5SDimitry Andric }
1145*0b57cec5SDimitry Andric 
1146*0b57cec5SDimitry Andric void InstrProfiling::emitRegistration() {
1147*0b57cec5SDimitry Andric   if (!needsRuntimeRegistrationOfSectionRange(TT))
1148*0b57cec5SDimitry Andric     return;
1149*0b57cec5SDimitry Andric 
1150*0b57cec5SDimitry Andric   // Construct the function.
1151*0b57cec5SDimitry Andric   auto *VoidTy = Type::getVoidTy(M->getContext());
1152*0b57cec5SDimitry Andric   auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
1153*0b57cec5SDimitry Andric   auto *Int64Ty = Type::getInt64Ty(M->getContext());
1154*0b57cec5SDimitry Andric   auto *RegisterFTy = FunctionType::get(VoidTy, false);
1155*0b57cec5SDimitry Andric   auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
1156*0b57cec5SDimitry Andric                                      getInstrProfRegFuncsName(), M);
1157*0b57cec5SDimitry Andric   RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1158*0b57cec5SDimitry Andric   if (Options.NoRedZone)
1159*0b57cec5SDimitry Andric     RegisterF->addFnAttr(Attribute::NoRedZone);
1160*0b57cec5SDimitry Andric 
1161*0b57cec5SDimitry Andric   auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
1162*0b57cec5SDimitry Andric   auto *RuntimeRegisterF =
1163*0b57cec5SDimitry Andric       Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
1164*0b57cec5SDimitry Andric                        getInstrProfRegFuncName(), M);
1165*0b57cec5SDimitry Andric 
1166*0b57cec5SDimitry Andric   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
1167fe6060f1SDimitry Andric   for (Value *Data : CompilerUsedVars)
1168fe6060f1SDimitry Andric     if (!isa<Function>(Data))
1169fe6060f1SDimitry Andric       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
1170*0b57cec5SDimitry Andric   for (Value *Data : UsedVars)
1171*0b57cec5SDimitry Andric     if (Data != NamesVar && !isa<Function>(Data))
1172*0b57cec5SDimitry Andric       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
1173*0b57cec5SDimitry Andric 
1174*0b57cec5SDimitry Andric   if (NamesVar) {
1175*0b57cec5SDimitry Andric     Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
1176*0b57cec5SDimitry Andric     auto *NamesRegisterTy =
1177*0b57cec5SDimitry Andric         FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
1178*0b57cec5SDimitry Andric     auto *NamesRegisterF =
1179*0b57cec5SDimitry Andric         Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
1180*0b57cec5SDimitry Andric                          getInstrProfNamesRegFuncName(), M);
1181*0b57cec5SDimitry Andric     IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
1182*0b57cec5SDimitry Andric                                     IRB.getInt64(NamesSize)});
1183*0b57cec5SDimitry Andric   }
1184*0b57cec5SDimitry Andric 
1185*0b57cec5SDimitry Andric   IRB.CreateRetVoid();
1186*0b57cec5SDimitry Andric }
1187*0b57cec5SDimitry Andric 
1188*0b57cec5SDimitry Andric bool InstrProfiling::emitRuntimeHook() {
1189349cc55cSDimitry Andric   // We expect the linker to be invoked with -u<hook_var> flag for Linux
1190349cc55cSDimitry Andric   // in which case there is no need to emit the external variable.
1191349cc55cSDimitry Andric   if (TT.isOSLinux())
1192*0b57cec5SDimitry Andric     return false;
1193*0b57cec5SDimitry Andric 
1194*0b57cec5SDimitry Andric   // If the module's provided its own runtime, we don't need to do anything.
1195*0b57cec5SDimitry Andric   if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
1196*0b57cec5SDimitry Andric     return false;
1197*0b57cec5SDimitry Andric 
1198*0b57cec5SDimitry Andric   // Declare an external variable that will pull in the runtime initialization.
1199*0b57cec5SDimitry Andric   auto *Int32Ty = Type::getInt32Ty(M->getContext());
1200*0b57cec5SDimitry Andric   auto *Var =
1201*0b57cec5SDimitry Andric       new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
1202*0b57cec5SDimitry Andric                          nullptr, getInstrProfRuntimeHookVarName());
1203*0b57cec5SDimitry Andric 
1204349cc55cSDimitry Andric   if (TT.isOSBinFormatELF()) {
1205349cc55cSDimitry Andric     // Mark the user variable as used so that it isn't stripped out.
1206349cc55cSDimitry Andric     CompilerUsedVars.push_back(Var);
1207349cc55cSDimitry Andric   } else {
1208*0b57cec5SDimitry Andric     // Make a function that uses it.
1209*0b57cec5SDimitry Andric     auto *User = Function::Create(FunctionType::get(Int32Ty, false),
1210*0b57cec5SDimitry Andric                                   GlobalValue::LinkOnceODRLinkage,
1211*0b57cec5SDimitry Andric                                   getInstrProfRuntimeHookVarUseFuncName(), M);
1212*0b57cec5SDimitry Andric     User->addFnAttr(Attribute::NoInline);
1213*0b57cec5SDimitry Andric     if (Options.NoRedZone)
1214*0b57cec5SDimitry Andric       User->addFnAttr(Attribute::NoRedZone);
1215*0b57cec5SDimitry Andric     User->setVisibility(GlobalValue::HiddenVisibility);
1216*0b57cec5SDimitry Andric     if (TT.supportsCOMDAT())
1217*0b57cec5SDimitry Andric       User->setComdat(M->getOrInsertComdat(User->getName()));
1218*0b57cec5SDimitry Andric 
1219*0b57cec5SDimitry Andric     IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
1220*0b57cec5SDimitry Andric     auto *Load = IRB.CreateLoad(Int32Ty, Var);
1221*0b57cec5SDimitry Andric     IRB.CreateRet(Load);
1222*0b57cec5SDimitry Andric 
1223349cc55cSDimitry Andric     // Mark the function as used so that it isn't stripped out.
1224fe6060f1SDimitry Andric     CompilerUsedVars.push_back(User);
1225349cc55cSDimitry Andric   }
1226*0b57cec5SDimitry Andric   return true;
1227*0b57cec5SDimitry Andric }
1228*0b57cec5SDimitry Andric 
1229*0b57cec5SDimitry Andric void InstrProfiling::emitUses() {
1230fe6060f1SDimitry Andric   // The metadata sections are parallel arrays. Optimizers (e.g.
1231fe6060f1SDimitry Andric   // GlobalOpt/ConstantMerge) may not discard associated sections as a unit, so
1232fe6060f1SDimitry Andric   // we conservatively retain all unconditionally in the compiler.
1233fe6060f1SDimitry Andric   //
1234349cc55cSDimitry Andric   // On ELF and Mach-O, the linker can guarantee the associated sections will be
1235349cc55cSDimitry Andric   // retained or discarded as a unit, so llvm.compiler.used is sufficient.
1236349cc55cSDimitry Andric   // Similarly on COFF, if prof data is not referenced by code we use one comdat
1237349cc55cSDimitry Andric   // and ensure this GC property as well. Otherwise, we have to conservatively
1238349cc55cSDimitry Andric   // make all of the sections retained by the linker.
1239349cc55cSDimitry Andric   if (TT.isOSBinFormatELF() || TT.isOSBinFormatMachO() ||
1240fe6060f1SDimitry Andric       (TT.isOSBinFormatCOFF() && !profDataReferencedByCode(*M)))
1241fe6060f1SDimitry Andric     appendToCompilerUsed(*M, CompilerUsedVars);
1242fe6060f1SDimitry Andric   else
1243fe6060f1SDimitry Andric     appendToUsed(*M, CompilerUsedVars);
1244fe6060f1SDimitry Andric 
1245fe6060f1SDimitry Andric   // We do not add proper references from used metadata sections to NamesVar and
1246fe6060f1SDimitry Andric   // VNodesVar, so we have to be conservative and place them in llvm.used
1247fe6060f1SDimitry Andric   // regardless of the target,
1248*0b57cec5SDimitry Andric   appendToUsed(*M, UsedVars);
1249*0b57cec5SDimitry Andric }
1250*0b57cec5SDimitry Andric 
1251*0b57cec5SDimitry Andric void InstrProfiling::emitInitialization() {
1252*0b57cec5SDimitry Andric   // Create ProfileFileName variable. Don't don't this for the
1253*0b57cec5SDimitry Andric   // context-sensitive instrumentation lowering: This lowering is after
1254*0b57cec5SDimitry Andric   // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
1255*0b57cec5SDimitry Andric   // have already create the variable before LTO/ThinLTO linking.
1256*0b57cec5SDimitry Andric   if (!IsCS)
1257*0b57cec5SDimitry Andric     createProfileFileNameVar(*M, Options.InstrProfileOutput);
1258*0b57cec5SDimitry Andric   Function *RegisterF = M->getFunction(getInstrProfRegFuncsName());
1259*0b57cec5SDimitry Andric   if (!RegisterF)
1260*0b57cec5SDimitry Andric     return;
1261*0b57cec5SDimitry Andric 
1262*0b57cec5SDimitry Andric   // Create the initialization function.
1263*0b57cec5SDimitry Andric   auto *VoidTy = Type::getVoidTy(M->getContext());
1264*0b57cec5SDimitry Andric   auto *F = Function::Create(FunctionType::get(VoidTy, false),
1265*0b57cec5SDimitry Andric                              GlobalValue::InternalLinkage,
1266*0b57cec5SDimitry Andric                              getInstrProfInitFuncName(), M);
1267*0b57cec5SDimitry Andric   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1268*0b57cec5SDimitry Andric   F->addFnAttr(Attribute::NoInline);
1269*0b57cec5SDimitry Andric   if (Options.NoRedZone)
1270*0b57cec5SDimitry Andric     F->addFnAttr(Attribute::NoRedZone);
1271*0b57cec5SDimitry Andric 
1272*0b57cec5SDimitry Andric   // Add the basic block and the necessary calls.
1273*0b57cec5SDimitry Andric   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
1274*0b57cec5SDimitry Andric   IRB.CreateCall(RegisterF, {});
1275*0b57cec5SDimitry Andric   IRB.CreateRetVoid();
1276*0b57cec5SDimitry Andric 
1277*0b57cec5SDimitry Andric   appendToGlobalCtors(*M, F, 0);
1278*0b57cec5SDimitry Andric }
1279