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/ModuleUtils.h"
51*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdater.h"
52*0b57cec5SDimitry Andric #include <algorithm>
53*0b57cec5SDimitry Andric #include <cassert>
54*0b57cec5SDimitry Andric #include <cstdint>
55*0b57cec5SDimitry Andric #include <string>
56*0b57cec5SDimitry Andric 
57*0b57cec5SDimitry Andric using namespace llvm;
58*0b57cec5SDimitry Andric 
59*0b57cec5SDimitry Andric #define DEBUG_TYPE "instrprof"
60*0b57cec5SDimitry Andric 
610eae32dcSDimitry Andric namespace llvm {
620eae32dcSDimitry Andric cl::opt<bool>
6381ad6265SDimitry Andric     DebugInfoCorrelate("debug-info-correlate",
640eae32dcSDimitry Andric                        cl::desc("Use debug info to correlate profiles."),
650eae32dcSDimitry Andric                        cl::init(false));
660eae32dcSDimitry Andric } // namespace llvm
670eae32dcSDimitry Andric 
68*0b57cec5SDimitry Andric namespace {
69*0b57cec5SDimitry Andric 
70*0b57cec5SDimitry Andric cl::opt<bool> DoHashBasedCounterSplit(
71*0b57cec5SDimitry Andric     "hash-based-counter-split",
72*0b57cec5SDimitry Andric     cl::desc("Rename counter variable of a comdat function based on cfg hash"),
73*0b57cec5SDimitry Andric     cl::init(true));
74*0b57cec5SDimitry Andric 
754824e7fdSDimitry Andric cl::opt<bool>
764824e7fdSDimitry Andric     RuntimeCounterRelocation("runtime-counter-relocation",
775ffd83dbSDimitry Andric                              cl::desc("Enable relocating counters at runtime."),
785ffd83dbSDimitry Andric                              cl::init(false));
795ffd83dbSDimitry Andric 
80*0b57cec5SDimitry Andric cl::opt<bool> ValueProfileStaticAlloc(
81*0b57cec5SDimitry Andric     "vp-static-alloc",
82*0b57cec5SDimitry Andric     cl::desc("Do static counter allocation for value profiler"),
83*0b57cec5SDimitry Andric     cl::init(true));
84*0b57cec5SDimitry Andric 
85*0b57cec5SDimitry Andric cl::opt<double> NumCountersPerValueSite(
86*0b57cec5SDimitry Andric     "vp-counters-per-site",
87*0b57cec5SDimitry Andric     cl::desc("The average number of profile counters allocated "
88*0b57cec5SDimitry Andric              "per value profiling site."),
89*0b57cec5SDimitry Andric     // This is set to a very small value because in real programs, only
90*0b57cec5SDimitry Andric     // a very small percentage of value sites have non-zero targets, e.g, 1/30.
91*0b57cec5SDimitry Andric     // For those sites with non-zero profile, the average number of targets
92*0b57cec5SDimitry Andric     // is usually smaller than 2.
93*0b57cec5SDimitry Andric     cl::init(1.0));
94*0b57cec5SDimitry Andric 
95*0b57cec5SDimitry Andric cl::opt<bool> AtomicCounterUpdateAll(
9681ad6265SDimitry Andric     "instrprof-atomic-counter-update-all",
97*0b57cec5SDimitry Andric     cl::desc("Make all profile counter updates atomic (for testing only)"),
98*0b57cec5SDimitry Andric     cl::init(false));
99*0b57cec5SDimitry Andric 
100*0b57cec5SDimitry Andric cl::opt<bool> AtomicCounterUpdatePromoted(
10181ad6265SDimitry Andric     "atomic-counter-update-promoted",
102*0b57cec5SDimitry Andric     cl::desc("Do counter update using atomic fetch add "
103*0b57cec5SDimitry Andric              " for promoted counters only"),
104*0b57cec5SDimitry Andric     cl::init(false));
105*0b57cec5SDimitry Andric 
1065ffd83dbSDimitry Andric cl::opt<bool> AtomicFirstCounter(
10781ad6265SDimitry Andric     "atomic-first-counter",
1085ffd83dbSDimitry Andric     cl::desc("Use atomic fetch add for first counter in a function (usually "
1095ffd83dbSDimitry Andric              "the entry counter)"),
1105ffd83dbSDimitry Andric     cl::init(false));
1115ffd83dbSDimitry Andric 
112*0b57cec5SDimitry Andric // If the option is not specified, the default behavior about whether
113*0b57cec5SDimitry Andric // counter promotion is done depends on how instrumentaiton lowering
114*0b57cec5SDimitry Andric // pipeline is setup, i.e., the default value of true of this option
115*0b57cec5SDimitry Andric // does not mean the promotion will be done by default. Explicitly
116*0b57cec5SDimitry Andric // setting this option can override the default behavior.
11781ad6265SDimitry Andric cl::opt<bool> DoCounterPromotion("do-counter-promotion",
118*0b57cec5SDimitry Andric                                  cl::desc("Do counter register promotion"),
119*0b57cec5SDimitry Andric                                  cl::init(false));
120*0b57cec5SDimitry Andric cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
12181ad6265SDimitry Andric     "max-counter-promotions-per-loop", cl::init(20),
122*0b57cec5SDimitry Andric     cl::desc("Max number counter promotions per loop to avoid"
123*0b57cec5SDimitry Andric              " increasing register pressure too much"));
124*0b57cec5SDimitry Andric 
125*0b57cec5SDimitry Andric // A debug option
126*0b57cec5SDimitry Andric cl::opt<int>
12781ad6265SDimitry Andric     MaxNumOfPromotions("max-counter-promotions", cl::init(-1),
128*0b57cec5SDimitry Andric                        cl::desc("Max number of allowed counter promotions"));
129*0b57cec5SDimitry Andric 
130*0b57cec5SDimitry Andric cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
13181ad6265SDimitry Andric     "speculative-counter-promotion-max-exiting", cl::init(3),
132*0b57cec5SDimitry Andric     cl::desc("The max number of exiting blocks of a loop to allow "
133*0b57cec5SDimitry Andric              " speculative counter promotion"));
134*0b57cec5SDimitry Andric 
135*0b57cec5SDimitry Andric cl::opt<bool> SpeculativeCounterPromotionToLoop(
13681ad6265SDimitry Andric     "speculative-counter-promotion-to-loop",
137*0b57cec5SDimitry Andric     cl::desc("When the option is false, if the target block is in a loop, "
138*0b57cec5SDimitry Andric              "the promotion will be disallowed unless the promoted counter "
139*0b57cec5SDimitry Andric              " update can be further/iteratively promoted into an acyclic "
140*0b57cec5SDimitry Andric              " region."));
141*0b57cec5SDimitry Andric 
142*0b57cec5SDimitry Andric cl::opt<bool> IterativeCounterPromotion(
14381ad6265SDimitry Andric     "iterative-counter-promotion", cl::init(true),
144*0b57cec5SDimitry Andric     cl::desc("Allow counter promotion across the whole loop nest."));
145*0b57cec5SDimitry Andric 
146e8d8bef9SDimitry Andric cl::opt<bool> SkipRetExitBlock(
14781ad6265SDimitry Andric     "skip-ret-exit-block", cl::init(true),
148e8d8bef9SDimitry Andric     cl::desc("Suppress counter promotion if exit blocks contain ret."));
149e8d8bef9SDimitry Andric 
150*0b57cec5SDimitry Andric ///
151*0b57cec5SDimitry Andric /// A helper class to promote one counter RMW operation in the loop
152*0b57cec5SDimitry Andric /// into register update.
153*0b57cec5SDimitry Andric ///
154*0b57cec5SDimitry Andric /// RWM update for the counter will be sinked out of the loop after
155*0b57cec5SDimitry Andric /// the transformation.
156*0b57cec5SDimitry Andric ///
157*0b57cec5SDimitry Andric class PGOCounterPromoterHelper : public LoadAndStorePromoter {
158*0b57cec5SDimitry Andric public:
159*0b57cec5SDimitry Andric   PGOCounterPromoterHelper(
160*0b57cec5SDimitry Andric       Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
161*0b57cec5SDimitry Andric       BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
162*0b57cec5SDimitry Andric       ArrayRef<Instruction *> InsertPts,
163*0b57cec5SDimitry Andric       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
164*0b57cec5SDimitry Andric       LoopInfo &LI)
165*0b57cec5SDimitry Andric       : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
166*0b57cec5SDimitry Andric         InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
167*0b57cec5SDimitry Andric     assert(isa<LoadInst>(L));
168*0b57cec5SDimitry Andric     assert(isa<StoreInst>(S));
169*0b57cec5SDimitry Andric     SSA.AddAvailableValue(PH, Init);
170*0b57cec5SDimitry Andric   }
171*0b57cec5SDimitry Andric 
172*0b57cec5SDimitry Andric   void doExtraRewritesBeforeFinalDeletion() override {
173*0b57cec5SDimitry Andric     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
174*0b57cec5SDimitry Andric       BasicBlock *ExitBlock = ExitBlocks[i];
175*0b57cec5SDimitry Andric       Instruction *InsertPos = InsertPts[i];
176*0b57cec5SDimitry Andric       // Get LiveIn value into the ExitBlock. If there are multiple
177*0b57cec5SDimitry Andric       // predecessors, the value is defined by a PHI node in this
178*0b57cec5SDimitry Andric       // block.
179*0b57cec5SDimitry Andric       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
180*0b57cec5SDimitry Andric       Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
181*0b57cec5SDimitry Andric       Type *Ty = LiveInValue->getType();
182*0b57cec5SDimitry Andric       IRBuilder<> Builder(InsertPos);
18381ad6265SDimitry Andric       if (auto *AddrInst = dyn_cast_or_null<IntToPtrInst>(Addr)) {
18481ad6265SDimitry Andric         // If isRuntimeCounterRelocationEnabled() is true then the address of
18581ad6265SDimitry Andric         // the store instruction is computed with two instructions in
18681ad6265SDimitry Andric         // InstrProfiling::getCounterAddress(). We need to copy those
18781ad6265SDimitry Andric         // instructions to this block to compute Addr correctly.
18881ad6265SDimitry Andric         // %BiasAdd = add i64 ptrtoint <__profc_>, <__llvm_profile_counter_bias>
18981ad6265SDimitry Andric         // %Addr = inttoptr i64 %BiasAdd to i64*
19081ad6265SDimitry Andric         auto *OrigBiasInst = dyn_cast<BinaryOperator>(AddrInst->getOperand(0));
19181ad6265SDimitry Andric         assert(OrigBiasInst->getOpcode() == Instruction::BinaryOps::Add);
19281ad6265SDimitry Andric         Value *BiasInst = Builder.Insert(OrigBiasInst->clone());
19381ad6265SDimitry Andric         Addr = Builder.CreateIntToPtr(BiasInst, Ty->getPointerTo());
19481ad6265SDimitry Andric       }
195*0b57cec5SDimitry Andric       if (AtomicCounterUpdatePromoted)
196*0b57cec5SDimitry Andric         // automic update currently can only be promoted across the current
197*0b57cec5SDimitry Andric         // loop, not the whole loop nest.
198*0b57cec5SDimitry Andric         Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
199fe6060f1SDimitry Andric                                 MaybeAlign(),
200*0b57cec5SDimitry Andric                                 AtomicOrdering::SequentiallyConsistent);
201*0b57cec5SDimitry Andric       else {
202*0b57cec5SDimitry Andric         LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
203*0b57cec5SDimitry Andric         auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
204*0b57cec5SDimitry Andric         auto *NewStore = Builder.CreateStore(NewVal, Addr);
205*0b57cec5SDimitry Andric 
206*0b57cec5SDimitry Andric         // Now update the parent loop's candidate list:
207*0b57cec5SDimitry Andric         if (IterativeCounterPromotion) {
208*0b57cec5SDimitry Andric           auto *TargetLoop = LI.getLoopFor(ExitBlock);
209*0b57cec5SDimitry Andric           if (TargetLoop)
210*0b57cec5SDimitry Andric             LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
211*0b57cec5SDimitry Andric         }
212*0b57cec5SDimitry Andric       }
213*0b57cec5SDimitry Andric     }
214*0b57cec5SDimitry Andric   }
215*0b57cec5SDimitry Andric 
216*0b57cec5SDimitry Andric private:
217*0b57cec5SDimitry Andric   Instruction *Store;
218*0b57cec5SDimitry Andric   ArrayRef<BasicBlock *> ExitBlocks;
219*0b57cec5SDimitry Andric   ArrayRef<Instruction *> InsertPts;
220*0b57cec5SDimitry Andric   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
221*0b57cec5SDimitry Andric   LoopInfo &LI;
222*0b57cec5SDimitry Andric };
223*0b57cec5SDimitry Andric 
224*0b57cec5SDimitry Andric /// A helper class to do register promotion for all profile counter
225*0b57cec5SDimitry Andric /// updates in a loop.
226*0b57cec5SDimitry Andric ///
227*0b57cec5SDimitry Andric class PGOCounterPromoter {
228*0b57cec5SDimitry Andric public:
229*0b57cec5SDimitry Andric   PGOCounterPromoter(
230*0b57cec5SDimitry Andric       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
231*0b57cec5SDimitry Andric       Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI)
23204eeddc0SDimitry Andric       : LoopToCandidates(LoopToCands), L(CurLoop), LI(LI), BFI(BFI) {
233*0b57cec5SDimitry Andric 
2345ffd83dbSDimitry Andric     // Skip collection of ExitBlocks and InsertPts for loops that will not be
2355ffd83dbSDimitry Andric     // able to have counters promoted.
236*0b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> LoopExitBlocks;
237*0b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 8> BlockSet;
2385ffd83dbSDimitry Andric 
239*0b57cec5SDimitry Andric     L.getExitBlocks(LoopExitBlocks);
2405ffd83dbSDimitry Andric     if (!isPromotionPossible(&L, LoopExitBlocks))
2415ffd83dbSDimitry Andric       return;
242*0b57cec5SDimitry Andric 
243*0b57cec5SDimitry Andric     for (BasicBlock *ExitBlock : LoopExitBlocks) {
244*0b57cec5SDimitry Andric       if (BlockSet.insert(ExitBlock).second) {
245*0b57cec5SDimitry Andric         ExitBlocks.push_back(ExitBlock);
246*0b57cec5SDimitry Andric         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
247*0b57cec5SDimitry Andric       }
248*0b57cec5SDimitry Andric     }
249*0b57cec5SDimitry Andric   }
250*0b57cec5SDimitry Andric 
251*0b57cec5SDimitry Andric   bool run(int64_t *NumPromoted) {
252*0b57cec5SDimitry Andric     // Skip 'infinite' loops:
253*0b57cec5SDimitry Andric     if (ExitBlocks.size() == 0)
254*0b57cec5SDimitry Andric       return false;
255e8d8bef9SDimitry Andric 
256e8d8bef9SDimitry Andric     // Skip if any of the ExitBlocks contains a ret instruction.
257e8d8bef9SDimitry Andric     // This is to prevent dumping of incomplete profile -- if the
258e8d8bef9SDimitry Andric     // the loop is a long running loop and dump is called in the middle
259e8d8bef9SDimitry Andric     // of the loop, the result profile is incomplete.
260e8d8bef9SDimitry Andric     // FIXME: add other heuristics to detect long running loops.
261e8d8bef9SDimitry Andric     if (SkipRetExitBlock) {
262bdd1243dSDimitry Andric       for (auto *BB : ExitBlocks)
263e8d8bef9SDimitry Andric         if (isa<ReturnInst>(BB->getTerminator()))
264e8d8bef9SDimitry Andric           return false;
265e8d8bef9SDimitry Andric     }
266e8d8bef9SDimitry Andric 
267*0b57cec5SDimitry Andric     unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
268*0b57cec5SDimitry Andric     if (MaxProm == 0)
269*0b57cec5SDimitry Andric       return false;
270*0b57cec5SDimitry Andric 
271*0b57cec5SDimitry Andric     unsigned Promoted = 0;
272*0b57cec5SDimitry Andric     for (auto &Cand : LoopToCandidates[&L]) {
273*0b57cec5SDimitry Andric 
274*0b57cec5SDimitry Andric       SmallVector<PHINode *, 4> NewPHIs;
275*0b57cec5SDimitry Andric       SSAUpdater SSA(&NewPHIs);
276*0b57cec5SDimitry Andric       Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
277*0b57cec5SDimitry Andric 
278*0b57cec5SDimitry Andric       // If BFI is set, we will use it to guide the promotions.
279*0b57cec5SDimitry Andric       if (BFI) {
280*0b57cec5SDimitry Andric         auto *BB = Cand.first->getParent();
281*0b57cec5SDimitry Andric         auto InstrCount = BFI->getBlockProfileCount(BB);
282*0b57cec5SDimitry Andric         if (!InstrCount)
283*0b57cec5SDimitry Andric           continue;
284*0b57cec5SDimitry Andric         auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
285*0b57cec5SDimitry Andric         // If the average loop trip count is not greater than 1.5, we skip
286*0b57cec5SDimitry Andric         // promotion.
28781ad6265SDimitry Andric         if (PreheaderCount && (*PreheaderCount * 3) >= (*InstrCount * 2))
288*0b57cec5SDimitry Andric           continue;
289*0b57cec5SDimitry Andric       }
290*0b57cec5SDimitry Andric 
291*0b57cec5SDimitry Andric       PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
292*0b57cec5SDimitry Andric                                         L.getLoopPreheader(), ExitBlocks,
293*0b57cec5SDimitry Andric                                         InsertPts, LoopToCandidates, LI);
294*0b57cec5SDimitry Andric       Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
295*0b57cec5SDimitry Andric       Promoted++;
296*0b57cec5SDimitry Andric       if (Promoted >= MaxProm)
297*0b57cec5SDimitry Andric         break;
298*0b57cec5SDimitry Andric 
299*0b57cec5SDimitry Andric       (*NumPromoted)++;
300*0b57cec5SDimitry Andric       if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
301*0b57cec5SDimitry Andric         break;
302*0b57cec5SDimitry Andric     }
303*0b57cec5SDimitry Andric 
304*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
305*0b57cec5SDimitry Andric                       << L.getLoopDepth() << ")\n");
306*0b57cec5SDimitry Andric     return Promoted != 0;
307*0b57cec5SDimitry Andric   }
308*0b57cec5SDimitry Andric 
309*0b57cec5SDimitry Andric private:
310*0b57cec5SDimitry Andric   bool allowSpeculativeCounterPromotion(Loop *LP) {
311*0b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> ExitingBlocks;
312*0b57cec5SDimitry Andric     L.getExitingBlocks(ExitingBlocks);
313*0b57cec5SDimitry Andric     // Not considierered speculative.
314*0b57cec5SDimitry Andric     if (ExitingBlocks.size() == 1)
315*0b57cec5SDimitry Andric       return true;
316*0b57cec5SDimitry Andric     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
317*0b57cec5SDimitry Andric       return false;
318*0b57cec5SDimitry Andric     return true;
319*0b57cec5SDimitry Andric   }
320*0b57cec5SDimitry Andric 
3215ffd83dbSDimitry Andric   // Check whether the loop satisfies the basic conditions needed to perform
3225ffd83dbSDimitry Andric   // Counter Promotions.
3234824e7fdSDimitry Andric   bool
3244824e7fdSDimitry Andric   isPromotionPossible(Loop *LP,
3255ffd83dbSDimitry Andric                       const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
326*0b57cec5SDimitry Andric     // We can't insert into a catchswitch.
327*0b57cec5SDimitry Andric     if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
328*0b57cec5SDimitry Andric           return isa<CatchSwitchInst>(Exit->getTerminator());
329*0b57cec5SDimitry Andric         }))
3305ffd83dbSDimitry Andric       return false;
331*0b57cec5SDimitry Andric 
332*0b57cec5SDimitry Andric     if (!LP->hasDedicatedExits())
3335ffd83dbSDimitry Andric       return false;
334*0b57cec5SDimitry Andric 
335*0b57cec5SDimitry Andric     BasicBlock *PH = LP->getLoopPreheader();
336*0b57cec5SDimitry Andric     if (!PH)
3375ffd83dbSDimitry Andric       return false;
3385ffd83dbSDimitry Andric 
3395ffd83dbSDimitry Andric     return true;
3405ffd83dbSDimitry Andric   }
3415ffd83dbSDimitry Andric 
3425ffd83dbSDimitry Andric   // Returns the max number of Counter Promotions for LP.
3435ffd83dbSDimitry Andric   unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
3445ffd83dbSDimitry Andric     SmallVector<BasicBlock *, 8> LoopExitBlocks;
3455ffd83dbSDimitry Andric     LP->getExitBlocks(LoopExitBlocks);
3465ffd83dbSDimitry Andric     if (!isPromotionPossible(LP, LoopExitBlocks))
347*0b57cec5SDimitry Andric       return 0;
348*0b57cec5SDimitry Andric 
349*0b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> ExitingBlocks;
350*0b57cec5SDimitry Andric     LP->getExitingBlocks(ExitingBlocks);
351*0b57cec5SDimitry Andric 
352*0b57cec5SDimitry Andric     // If BFI is set, we do more aggressive promotions based on BFI.
353*0b57cec5SDimitry Andric     if (BFI)
354*0b57cec5SDimitry Andric       return (unsigned)-1;
355*0b57cec5SDimitry Andric 
356*0b57cec5SDimitry Andric     // Not considierered speculative.
357*0b57cec5SDimitry Andric     if (ExitingBlocks.size() == 1)
358*0b57cec5SDimitry Andric       return MaxNumOfPromotionsPerLoop;
359*0b57cec5SDimitry Andric 
360*0b57cec5SDimitry Andric     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
361*0b57cec5SDimitry Andric       return 0;
362*0b57cec5SDimitry Andric 
363*0b57cec5SDimitry Andric     // Whether the target block is in a loop does not matter:
364*0b57cec5SDimitry Andric     if (SpeculativeCounterPromotionToLoop)
365*0b57cec5SDimitry Andric       return MaxNumOfPromotionsPerLoop;
366*0b57cec5SDimitry Andric 
367*0b57cec5SDimitry Andric     // Now check the target block:
368*0b57cec5SDimitry Andric     unsigned MaxProm = MaxNumOfPromotionsPerLoop;
369*0b57cec5SDimitry Andric     for (auto *TargetBlock : LoopExitBlocks) {
370*0b57cec5SDimitry Andric       auto *TargetLoop = LI.getLoopFor(TargetBlock);
371*0b57cec5SDimitry Andric       if (!TargetLoop)
372*0b57cec5SDimitry Andric         continue;
373*0b57cec5SDimitry Andric       unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
374*0b57cec5SDimitry Andric       unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
375*0b57cec5SDimitry Andric       MaxProm =
376*0b57cec5SDimitry Andric           std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
377*0b57cec5SDimitry Andric                                 PendingCandsInTarget);
378*0b57cec5SDimitry Andric     }
379*0b57cec5SDimitry Andric     return MaxProm;
380*0b57cec5SDimitry Andric   }
381*0b57cec5SDimitry Andric 
382*0b57cec5SDimitry Andric   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
383*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 8> ExitBlocks;
384*0b57cec5SDimitry Andric   SmallVector<Instruction *, 8> InsertPts;
385*0b57cec5SDimitry Andric   Loop &L;
386*0b57cec5SDimitry Andric   LoopInfo &LI;
387*0b57cec5SDimitry Andric   BlockFrequencyInfo *BFI;
388*0b57cec5SDimitry Andric };
389*0b57cec5SDimitry Andric 
390e8d8bef9SDimitry Andric enum class ValueProfilingCallType {
391e8d8bef9SDimitry Andric   // Individual values are tracked. Currently used for indiret call target
392e8d8bef9SDimitry Andric   // profiling.
393e8d8bef9SDimitry Andric   Default,
394e8d8bef9SDimitry Andric 
395e8d8bef9SDimitry Andric   // MemOp: the memop size value profiling.
396e8d8bef9SDimitry Andric   MemOp
397e8d8bef9SDimitry Andric };
398e8d8bef9SDimitry Andric 
399*0b57cec5SDimitry Andric } // end anonymous namespace
400*0b57cec5SDimitry Andric 
401*0b57cec5SDimitry Andric PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
4028bcb0991SDimitry Andric   FunctionAnalysisManager &FAM =
4038bcb0991SDimitry Andric       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
4048bcb0991SDimitry Andric   auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
4058bcb0991SDimitry Andric     return FAM.getResult<TargetLibraryAnalysis>(F);
4068bcb0991SDimitry Andric   };
4078bcb0991SDimitry Andric   if (!run(M, GetTLI))
408*0b57cec5SDimitry Andric     return PreservedAnalyses::all();
409*0b57cec5SDimitry Andric 
410*0b57cec5SDimitry Andric   return PreservedAnalyses::none();
411*0b57cec5SDimitry Andric }
412*0b57cec5SDimitry Andric 
413*0b57cec5SDimitry Andric bool InstrProfiling::lowerIntrinsics(Function *F) {
414*0b57cec5SDimitry Andric   bool MadeChange = false;
415*0b57cec5SDimitry Andric   PromotionCandidates.clear();
416*0b57cec5SDimitry Andric   for (BasicBlock &BB : *F) {
417349cc55cSDimitry Andric     for (Instruction &Instr : llvm::make_early_inc_range(BB)) {
41804eeddc0SDimitry Andric       if (auto *IPIS = dyn_cast<InstrProfIncrementInstStep>(&Instr)) {
41904eeddc0SDimitry Andric         lowerIncrement(IPIS);
420*0b57cec5SDimitry Andric         MadeChange = true;
42104eeddc0SDimitry Andric       } else if (auto *IPI = dyn_cast<InstrProfIncrementInst>(&Instr)) {
42204eeddc0SDimitry Andric         lowerIncrement(IPI);
42304eeddc0SDimitry Andric         MadeChange = true;
4241fd87a68SDimitry Andric       } else if (auto *IPC = dyn_cast<InstrProfCoverInst>(&Instr)) {
4251fd87a68SDimitry Andric         lowerCover(IPC);
4261fd87a68SDimitry Andric         MadeChange = true;
42704eeddc0SDimitry Andric       } else if (auto *IPVP = dyn_cast<InstrProfValueProfileInst>(&Instr)) {
42804eeddc0SDimitry Andric         lowerValueProfileInst(IPVP);
429*0b57cec5SDimitry Andric         MadeChange = true;
430*0b57cec5SDimitry Andric       }
431*0b57cec5SDimitry Andric     }
432*0b57cec5SDimitry Andric   }
433*0b57cec5SDimitry Andric 
434*0b57cec5SDimitry Andric   if (!MadeChange)
435*0b57cec5SDimitry Andric     return false;
436*0b57cec5SDimitry Andric 
437*0b57cec5SDimitry Andric   promoteCounterLoadStores(F);
438*0b57cec5SDimitry Andric   return true;
439*0b57cec5SDimitry Andric }
440*0b57cec5SDimitry Andric 
4415ffd83dbSDimitry Andric bool InstrProfiling::isRuntimeCounterRelocationEnabled() const {
442fe6060f1SDimitry Andric   // Mach-O don't support weak external references.
443fe6060f1SDimitry Andric   if (TT.isOSBinFormatMachO())
444fe6060f1SDimitry Andric     return false;
445fe6060f1SDimitry Andric 
4465ffd83dbSDimitry Andric   if (RuntimeCounterRelocation.getNumOccurrences() > 0)
4475ffd83dbSDimitry Andric     return RuntimeCounterRelocation;
4485ffd83dbSDimitry Andric 
449fe6060f1SDimitry Andric   // Fuchsia uses runtime counter relocation by default.
4505ffd83dbSDimitry Andric   return TT.isOSFuchsia();
4515ffd83dbSDimitry Andric }
4525ffd83dbSDimitry Andric 
453*0b57cec5SDimitry Andric bool InstrProfiling::isCounterPromotionEnabled() const {
454*0b57cec5SDimitry Andric   if (DoCounterPromotion.getNumOccurrences() > 0)
455*0b57cec5SDimitry Andric     return DoCounterPromotion;
456*0b57cec5SDimitry Andric 
457*0b57cec5SDimitry Andric   return Options.DoCounterPromotion;
458*0b57cec5SDimitry Andric }
459*0b57cec5SDimitry Andric 
460*0b57cec5SDimitry Andric void InstrProfiling::promoteCounterLoadStores(Function *F) {
461*0b57cec5SDimitry Andric   if (!isCounterPromotionEnabled())
462*0b57cec5SDimitry Andric     return;
463*0b57cec5SDimitry Andric 
464*0b57cec5SDimitry Andric   DominatorTree DT(*F);
465*0b57cec5SDimitry Andric   LoopInfo LI(DT);
466*0b57cec5SDimitry Andric   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
467*0b57cec5SDimitry Andric 
468*0b57cec5SDimitry Andric   std::unique_ptr<BlockFrequencyInfo> BFI;
469*0b57cec5SDimitry Andric   if (Options.UseBFIInPromotion) {
470*0b57cec5SDimitry Andric     std::unique_ptr<BranchProbabilityInfo> BPI;
4718bcb0991SDimitry Andric     BPI.reset(new BranchProbabilityInfo(*F, LI, &GetTLI(*F)));
472*0b57cec5SDimitry Andric     BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
473*0b57cec5SDimitry Andric   }
474*0b57cec5SDimitry Andric 
475*0b57cec5SDimitry Andric   for (const auto &LoadStore : PromotionCandidates) {
476*0b57cec5SDimitry Andric     auto *CounterLoad = LoadStore.first;
477*0b57cec5SDimitry Andric     auto *CounterStore = LoadStore.second;
478*0b57cec5SDimitry Andric     BasicBlock *BB = CounterLoad->getParent();
479*0b57cec5SDimitry Andric     Loop *ParentLoop = LI.getLoopFor(BB);
480*0b57cec5SDimitry Andric     if (!ParentLoop)
481*0b57cec5SDimitry Andric       continue;
482*0b57cec5SDimitry Andric     LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
483*0b57cec5SDimitry Andric   }
484*0b57cec5SDimitry Andric 
485*0b57cec5SDimitry Andric   SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
486*0b57cec5SDimitry Andric 
487*0b57cec5SDimitry Andric   // Do a post-order traversal of the loops so that counter updates can be
488*0b57cec5SDimitry Andric   // iteratively hoisted outside the loop nest.
489*0b57cec5SDimitry Andric   for (auto *Loop : llvm::reverse(Loops)) {
490*0b57cec5SDimitry Andric     PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get());
491*0b57cec5SDimitry Andric     Promoter.run(&TotalCountersPromoted);
492*0b57cec5SDimitry Andric   }
493*0b57cec5SDimitry Andric }
494*0b57cec5SDimitry Andric 
495349cc55cSDimitry Andric static bool needsRuntimeHookUnconditionally(const Triple &TT) {
496349cc55cSDimitry Andric   // On Fuchsia, we only need runtime hook if any counters are present.
497349cc55cSDimitry Andric   if (TT.isOSFuchsia())
498349cc55cSDimitry Andric     return false;
499349cc55cSDimitry Andric 
500349cc55cSDimitry Andric   return true;
501349cc55cSDimitry Andric }
502349cc55cSDimitry Andric 
503*0b57cec5SDimitry Andric /// Check if the module contains uses of any profiling intrinsics.
504*0b57cec5SDimitry Andric static bool containsProfilingIntrinsics(Module &M) {
50504eeddc0SDimitry Andric   auto containsIntrinsic = [&](int ID) {
50604eeddc0SDimitry Andric     if (auto *F = M.getFunction(Intrinsic::getName(ID)))
50704eeddc0SDimitry Andric       return !F->use_empty();
508*0b57cec5SDimitry Andric     return false;
50904eeddc0SDimitry Andric   };
5101fd87a68SDimitry Andric   return containsIntrinsic(llvm::Intrinsic::instrprof_cover) ||
5111fd87a68SDimitry Andric          containsIntrinsic(llvm::Intrinsic::instrprof_increment) ||
51204eeddc0SDimitry Andric          containsIntrinsic(llvm::Intrinsic::instrprof_increment_step) ||
51304eeddc0SDimitry Andric          containsIntrinsic(llvm::Intrinsic::instrprof_value_profile);
514*0b57cec5SDimitry Andric }
515*0b57cec5SDimitry Andric 
5168bcb0991SDimitry Andric bool InstrProfiling::run(
5178bcb0991SDimitry Andric     Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
518*0b57cec5SDimitry Andric   this->M = &M;
5198bcb0991SDimitry Andric   this->GetTLI = std::move(GetTLI);
520*0b57cec5SDimitry Andric   NamesVar = nullptr;
521*0b57cec5SDimitry Andric   NamesSize = 0;
522*0b57cec5SDimitry Andric   ProfileDataMap.clear();
523fe6060f1SDimitry Andric   CompilerUsedVars.clear();
524*0b57cec5SDimitry Andric   UsedVars.clear();
525*0b57cec5SDimitry Andric   TT = Triple(M.getTargetTriple());
526*0b57cec5SDimitry Andric 
527349cc55cSDimitry Andric   bool MadeChange = false;
528bdd1243dSDimitry Andric   bool NeedsRuntimeHook = needsRuntimeHookUnconditionally(TT);
529bdd1243dSDimitry Andric   if (NeedsRuntimeHook)
530349cc55cSDimitry Andric     MadeChange = emitRuntimeHook();
531*0b57cec5SDimitry Andric 
532bdd1243dSDimitry Andric   bool ContainsProfiling = containsProfilingIntrinsics(M);
533*0b57cec5SDimitry Andric   GlobalVariable *CoverageNamesVar =
534*0b57cec5SDimitry Andric       M.getNamedGlobal(getCoverageUnusedNamesVarName());
535bdd1243dSDimitry Andric   // Improve compile time by avoiding linear scans when there is no work.
536bdd1243dSDimitry Andric   if (!ContainsProfiling && !CoverageNamesVar)
537*0b57cec5SDimitry Andric     return MadeChange;
538*0b57cec5SDimitry Andric 
539*0b57cec5SDimitry Andric   // We did not know how many value sites there would be inside
540*0b57cec5SDimitry Andric   // the instrumented function. This is counting the number of instrumented
541*0b57cec5SDimitry Andric   // target value sites to enter it as field in the profile data variable.
542*0b57cec5SDimitry Andric   for (Function &F : M) {
543*0b57cec5SDimitry Andric     InstrProfIncrementInst *FirstProfIncInst = nullptr;
544*0b57cec5SDimitry Andric     for (BasicBlock &BB : F)
545*0b57cec5SDimitry Andric       for (auto I = BB.begin(), E = BB.end(); I != E; I++)
546*0b57cec5SDimitry Andric         if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
547*0b57cec5SDimitry Andric           computeNumValueSiteCounts(Ind);
548*0b57cec5SDimitry Andric         else if (FirstProfIncInst == nullptr)
549*0b57cec5SDimitry Andric           FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
550*0b57cec5SDimitry Andric 
551*0b57cec5SDimitry Andric     // Value profiling intrinsic lowering requires per-function profile data
552*0b57cec5SDimitry Andric     // variable to be created first.
553*0b57cec5SDimitry Andric     if (FirstProfIncInst != nullptr)
554*0b57cec5SDimitry Andric       static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
555*0b57cec5SDimitry Andric   }
556*0b57cec5SDimitry Andric 
557*0b57cec5SDimitry Andric   for (Function &F : M)
558*0b57cec5SDimitry Andric     MadeChange |= lowerIntrinsics(&F);
559*0b57cec5SDimitry Andric 
560*0b57cec5SDimitry Andric   if (CoverageNamesVar) {
561*0b57cec5SDimitry Andric     lowerCoverageData(CoverageNamesVar);
562*0b57cec5SDimitry Andric     MadeChange = true;
563*0b57cec5SDimitry Andric   }
564*0b57cec5SDimitry Andric 
565*0b57cec5SDimitry Andric   if (!MadeChange)
566*0b57cec5SDimitry Andric     return false;
567*0b57cec5SDimitry Andric 
568*0b57cec5SDimitry Andric   emitVNodes();
569*0b57cec5SDimitry Andric   emitNameData();
570bdd1243dSDimitry Andric 
571bdd1243dSDimitry Andric   // Emit runtime hook for the cases where the target does not unconditionally
572bdd1243dSDimitry Andric   // require pulling in profile runtime, and coverage is enabled on code that is
573bdd1243dSDimitry Andric   // not eliminated by the front-end, e.g. unused functions with internal
574bdd1243dSDimitry Andric   // linkage.
575bdd1243dSDimitry Andric   if (!NeedsRuntimeHook && ContainsProfiling)
576349cc55cSDimitry Andric     emitRuntimeHook();
577bdd1243dSDimitry Andric 
578*0b57cec5SDimitry Andric   emitRegistration();
579*0b57cec5SDimitry Andric   emitUses();
580*0b57cec5SDimitry Andric   emitInitialization();
581*0b57cec5SDimitry Andric   return true;
582*0b57cec5SDimitry Andric }
583*0b57cec5SDimitry Andric 
584e8d8bef9SDimitry Andric static FunctionCallee getOrInsertValueProfilingCall(
585e8d8bef9SDimitry Andric     Module &M, const TargetLibraryInfo &TLI,
586e8d8bef9SDimitry Andric     ValueProfilingCallType CallType = ValueProfilingCallType::Default) {
587*0b57cec5SDimitry Andric   LLVMContext &Ctx = M.getContext();
588*0b57cec5SDimitry Andric   auto *ReturnTy = Type::getVoidTy(M.getContext());
589*0b57cec5SDimitry Andric 
590*0b57cec5SDimitry Andric   AttributeList AL;
591*0b57cec5SDimitry Andric   if (auto AK = TLI.getExtAttrForI32Param(false))
592*0b57cec5SDimitry Andric     AL = AL.addParamAttribute(M.getContext(), 2, AK);
593*0b57cec5SDimitry Andric 
594e8d8bef9SDimitry Andric   assert((CallType == ValueProfilingCallType::Default ||
595e8d8bef9SDimitry Andric           CallType == ValueProfilingCallType::MemOp) &&
596e8d8bef9SDimitry Andric          "Must be Default or MemOp");
597*0b57cec5SDimitry Andric   Type *ParamTypes[] = {
598*0b57cec5SDimitry Andric #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
599*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
600*0b57cec5SDimitry Andric   };
601*0b57cec5SDimitry Andric   auto *ValueProfilingCallTy =
602bdd1243dSDimitry Andric       FunctionType::get(ReturnTy, ArrayRef(ParamTypes), false);
603e8d8bef9SDimitry Andric   StringRef FuncName = CallType == ValueProfilingCallType::Default
604e8d8bef9SDimitry Andric                            ? getInstrProfValueProfFuncName()
605e8d8bef9SDimitry Andric                            : getInstrProfValueProfMemOpFuncName();
606e8d8bef9SDimitry Andric   return M.getOrInsertFunction(FuncName, ValueProfilingCallTy, AL);
607*0b57cec5SDimitry Andric }
608*0b57cec5SDimitry Andric 
609*0b57cec5SDimitry Andric void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
610*0b57cec5SDimitry Andric   GlobalVariable *Name = Ind->getName();
611*0b57cec5SDimitry Andric   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
612*0b57cec5SDimitry Andric   uint64_t Index = Ind->getIndex()->getZExtValue();
6134824e7fdSDimitry Andric   auto &PD = ProfileDataMap[Name];
6144824e7fdSDimitry Andric   PD.NumValueSites[ValueKind] =
6154824e7fdSDimitry Andric       std::max(PD.NumValueSites[ValueKind], (uint32_t)(Index + 1));
616*0b57cec5SDimitry Andric }
617*0b57cec5SDimitry Andric 
618*0b57cec5SDimitry Andric void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
6190eae32dcSDimitry Andric   // TODO: Value profiling heavily depends on the data section which is omitted
6200eae32dcSDimitry Andric   // in lightweight mode. We need to move the value profile pointer to the
6210eae32dcSDimitry Andric   // Counter struct to get this working.
6220eae32dcSDimitry Andric   assert(
6230eae32dcSDimitry Andric       !DebugInfoCorrelate &&
6240eae32dcSDimitry Andric       "Value profiling is not yet supported with lightweight instrumentation");
625*0b57cec5SDimitry Andric   GlobalVariable *Name = Ind->getName();
626*0b57cec5SDimitry Andric   auto It = ProfileDataMap.find(Name);
627*0b57cec5SDimitry Andric   assert(It != ProfileDataMap.end() && It->second.DataVar &&
628*0b57cec5SDimitry Andric          "value profiling detected in function with no counter incerement");
629*0b57cec5SDimitry Andric 
630*0b57cec5SDimitry Andric   GlobalVariable *DataVar = It->second.DataVar;
631*0b57cec5SDimitry Andric   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
632*0b57cec5SDimitry Andric   uint64_t Index = Ind->getIndex()->getZExtValue();
633*0b57cec5SDimitry Andric   for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
634*0b57cec5SDimitry Andric     Index += It->second.NumValueSites[Kind];
635*0b57cec5SDimitry Andric 
636*0b57cec5SDimitry Andric   IRBuilder<> Builder(Ind);
637e8d8bef9SDimitry Andric   bool IsMemOpSize = (Ind->getValueKind()->getZExtValue() ==
638*0b57cec5SDimitry Andric                       llvm::InstrProfValueKind::IPVK_MemOPSize);
639*0b57cec5SDimitry Andric   CallInst *Call = nullptr;
6408bcb0991SDimitry Andric   auto *TLI = &GetTLI(*Ind->getFunction());
6415ffd83dbSDimitry Andric 
6425ffd83dbSDimitry Andric   // To support value profiling calls within Windows exception handlers, funclet
6435ffd83dbSDimitry Andric   // information contained within operand bundles needs to be copied over to
6445ffd83dbSDimitry Andric   // the library call. This is required for the IR to be processed by the
6455ffd83dbSDimitry Andric   // WinEHPrepare pass.
6465ffd83dbSDimitry Andric   SmallVector<OperandBundleDef, 1> OpBundles;
6475ffd83dbSDimitry Andric   Ind->getOperandBundlesAsDefs(OpBundles);
648e8d8bef9SDimitry Andric   if (!IsMemOpSize) {
649*0b57cec5SDimitry Andric     Value *Args[3] = {Ind->getTargetValue(),
650*0b57cec5SDimitry Andric                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
651*0b57cec5SDimitry Andric                       Builder.getInt32(Index)};
6525ffd83dbSDimitry Andric     Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args,
6535ffd83dbSDimitry Andric                               OpBundles);
654*0b57cec5SDimitry Andric   } else {
655e8d8bef9SDimitry Andric     Value *Args[3] = {Ind->getTargetValue(),
656*0b57cec5SDimitry Andric                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
657e8d8bef9SDimitry Andric                       Builder.getInt32(Index)};
658e8d8bef9SDimitry Andric     Call = Builder.CreateCall(
659e8d8bef9SDimitry Andric         getOrInsertValueProfilingCall(*M, *TLI, ValueProfilingCallType::MemOp),
6605ffd83dbSDimitry Andric         Args, OpBundles);
661*0b57cec5SDimitry Andric   }
662*0b57cec5SDimitry Andric   if (auto AK = TLI->getExtAttrForI32Param(false))
663*0b57cec5SDimitry Andric     Call->addParamAttr(2, AK);
664*0b57cec5SDimitry Andric   Ind->replaceAllUsesWith(Call);
665*0b57cec5SDimitry Andric   Ind->eraseFromParent();
666*0b57cec5SDimitry Andric }
667*0b57cec5SDimitry Andric 
6681fd87a68SDimitry Andric Value *InstrProfiling::getCounterAddress(InstrProfInstBase *I) {
6691fd87a68SDimitry Andric   auto *Counters = getOrCreateRegionCounters(I);
6701fd87a68SDimitry Andric   IRBuilder<> Builder(I);
671*0b57cec5SDimitry Andric 
6721fd87a68SDimitry Andric   auto *Addr = Builder.CreateConstInBoundsGEP2_32(
6731fd87a68SDimitry Andric       Counters->getValueType(), Counters, 0, I->getIndex()->getZExtValue());
674*0b57cec5SDimitry Andric 
6751fd87a68SDimitry Andric   if (!isRuntimeCounterRelocationEnabled())
6761fd87a68SDimitry Andric     return Addr;
6771fd87a68SDimitry Andric 
6785ffd83dbSDimitry Andric   Type *Int64Ty = Type::getInt64Ty(M->getContext());
6791fd87a68SDimitry Andric   Function *Fn = I->getParent()->getParent();
68081ad6265SDimitry Andric   LoadInst *&BiasLI = FunctionToProfileBiasMap[Fn];
68181ad6265SDimitry Andric   if (!BiasLI) {
68281ad6265SDimitry Andric     IRBuilder<> EntryBuilder(&Fn->getEntryBlock().front());
6831fd87a68SDimitry Andric     auto *Bias = M->getGlobalVariable(getInstrProfCounterBiasVarName());
6845ffd83dbSDimitry Andric     if (!Bias) {
685fe6060f1SDimitry Andric       // Compiler must define this variable when runtime counter relocation
686fe6060f1SDimitry Andric       // is being used. Runtime has a weak external reference that is used
687fe6060f1SDimitry Andric       // to check whether that's the case or not.
6884824e7fdSDimitry Andric       Bias = new GlobalVariable(
6894824e7fdSDimitry Andric           *M, Int64Ty, false, GlobalValue::LinkOnceODRLinkage,
6904824e7fdSDimitry Andric           Constant::getNullValue(Int64Ty), getInstrProfCounterBiasVarName());
6915ffd83dbSDimitry Andric       Bias->setVisibility(GlobalVariable::HiddenVisibility);
692fe6060f1SDimitry Andric       // A definition that's weak (linkonce_odr) without being in a COMDAT
693fe6060f1SDimitry Andric       // section wouldn't lead to link errors, but it would lead to a dead
694fe6060f1SDimitry Andric       // data word from every TU but one. Putting it in COMDAT ensures there
695fe6060f1SDimitry Andric       // will be exactly one data slot in the link.
696fe6060f1SDimitry Andric       if (TT.supportsCOMDAT())
697fe6060f1SDimitry Andric         Bias->setComdat(M->getOrInsertComdat(Bias->getName()));
6985ffd83dbSDimitry Andric     }
69981ad6265SDimitry Andric     BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias);
7005ffd83dbSDimitry Andric   }
70181ad6265SDimitry Andric   auto *Add = Builder.CreateAdd(Builder.CreatePtrToInt(Addr, Int64Ty), BiasLI);
7021fd87a68SDimitry Andric   return Builder.CreateIntToPtr(Add, Addr->getType());
7035ffd83dbSDimitry Andric }
7045ffd83dbSDimitry Andric 
7051fd87a68SDimitry Andric void InstrProfiling::lowerCover(InstrProfCoverInst *CoverInstruction) {
7061fd87a68SDimitry Andric   auto *Addr = getCounterAddress(CoverInstruction);
7071fd87a68SDimitry Andric   IRBuilder<> Builder(CoverInstruction);
7081fd87a68SDimitry Andric   // We store zero to represent that this block is covered.
7091fd87a68SDimitry Andric   Builder.CreateStore(Builder.getInt8(0), Addr);
7101fd87a68SDimitry Andric   CoverInstruction->eraseFromParent();
7111fd87a68SDimitry Andric }
7121fd87a68SDimitry Andric 
7131fd87a68SDimitry Andric void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
7141fd87a68SDimitry Andric   auto *Addr = getCounterAddress(Inc);
7151fd87a68SDimitry Andric 
7161fd87a68SDimitry Andric   IRBuilder<> Builder(Inc);
7175ffd83dbSDimitry Andric   if (Options.Atomic || AtomicCounterUpdateAll ||
7181fd87a68SDimitry Andric       (Inc->getIndex()->isZeroValue() && AtomicFirstCounter)) {
719*0b57cec5SDimitry Andric     Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
720fe6060f1SDimitry Andric                             MaybeAlign(), AtomicOrdering::Monotonic);
721*0b57cec5SDimitry Andric   } else {
722*0b57cec5SDimitry Andric     Value *IncStep = Inc->getStep();
723*0b57cec5SDimitry Andric     Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
724*0b57cec5SDimitry Andric     auto *Count = Builder.CreateAdd(Load, Inc->getStep());
725*0b57cec5SDimitry Andric     auto *Store = Builder.CreateStore(Count, Addr);
726*0b57cec5SDimitry Andric     if (isCounterPromotionEnabled())
727*0b57cec5SDimitry Andric       PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
728*0b57cec5SDimitry Andric   }
729*0b57cec5SDimitry Andric   Inc->eraseFromParent();
730*0b57cec5SDimitry Andric }
731*0b57cec5SDimitry Andric 
732*0b57cec5SDimitry Andric void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
733*0b57cec5SDimitry Andric   ConstantArray *Names =
734*0b57cec5SDimitry Andric       cast<ConstantArray>(CoverageNamesVar->getInitializer());
735*0b57cec5SDimitry Andric   for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
736*0b57cec5SDimitry Andric     Constant *NC = Names->getOperand(I);
737*0b57cec5SDimitry Andric     Value *V = NC->stripPointerCasts();
738*0b57cec5SDimitry Andric     assert(isa<GlobalVariable>(V) && "Missing reference to function name");
739*0b57cec5SDimitry Andric     GlobalVariable *Name = cast<GlobalVariable>(V);
740*0b57cec5SDimitry Andric 
741*0b57cec5SDimitry Andric     Name->setLinkage(GlobalValue::PrivateLinkage);
742*0b57cec5SDimitry Andric     ReferencedNames.push_back(Name);
74381ad6265SDimitry Andric     if (isa<ConstantExpr>(NC))
744*0b57cec5SDimitry Andric       NC->dropAllReferences();
745*0b57cec5SDimitry Andric   }
746*0b57cec5SDimitry Andric   CoverageNamesVar->eraseFromParent();
747*0b57cec5SDimitry Andric }
748*0b57cec5SDimitry Andric 
749*0b57cec5SDimitry Andric /// Get the name of a profiling variable for a particular function.
75004eeddc0SDimitry Andric static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix,
751349cc55cSDimitry Andric                               bool &Renamed) {
752*0b57cec5SDimitry Andric   StringRef NamePrefix = getInstrProfNameVarPrefix();
753*0b57cec5SDimitry Andric   StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
754*0b57cec5SDimitry Andric   Function *F = Inc->getParent()->getParent();
755*0b57cec5SDimitry Andric   Module *M = F->getParent();
756*0b57cec5SDimitry Andric   if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
757349cc55cSDimitry Andric       !canRenameComdatFunc(*F)) {
758349cc55cSDimitry Andric     Renamed = false;
759*0b57cec5SDimitry Andric     return (Prefix + Name).str();
760349cc55cSDimitry Andric   }
761349cc55cSDimitry Andric   Renamed = true;
762*0b57cec5SDimitry Andric   uint64_t FuncHash = Inc->getHash()->getZExtValue();
763*0b57cec5SDimitry Andric   SmallVector<char, 24> HashPostfix;
764*0b57cec5SDimitry Andric   if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
765*0b57cec5SDimitry Andric     return (Prefix + Name).str();
766*0b57cec5SDimitry Andric   return (Prefix + Name + "." + Twine(FuncHash)).str();
767*0b57cec5SDimitry Andric }
768*0b57cec5SDimitry Andric 
769fe6060f1SDimitry Andric static uint64_t getIntModuleFlagOrZero(const Module &M, StringRef Flag) {
770fe6060f1SDimitry Andric   auto *MD = dyn_cast_or_null<ConstantAsMetadata>(M.getModuleFlag(Flag));
771fe6060f1SDimitry Andric   if (!MD)
772fe6060f1SDimitry Andric     return 0;
773fe6060f1SDimitry Andric 
774fe6060f1SDimitry Andric   // If the flag is a ConstantAsMetadata, it should be an integer representable
775fe6060f1SDimitry Andric   // in 64-bits.
776fe6060f1SDimitry Andric   return cast<ConstantInt>(MD->getValue())->getZExtValue();
777fe6060f1SDimitry Andric }
778fe6060f1SDimitry Andric 
779fe6060f1SDimitry Andric static bool enablesValueProfiling(const Module &M) {
780fe6060f1SDimitry Andric   return isIRPGOFlagSet(&M) ||
781fe6060f1SDimitry Andric          getIntModuleFlagOrZero(M, "EnableValueProfiling") != 0;
782fe6060f1SDimitry Andric }
783fe6060f1SDimitry Andric 
784fe6060f1SDimitry Andric // Conservatively returns true if data variables may be referenced by code.
785fe6060f1SDimitry Andric static bool profDataReferencedByCode(const Module &M) {
786fe6060f1SDimitry Andric   return enablesValueProfiling(M);
787fe6060f1SDimitry Andric }
788fe6060f1SDimitry Andric 
789*0b57cec5SDimitry Andric static inline bool shouldRecordFunctionAddr(Function *F) {
790fe6060f1SDimitry Andric   // Only record function addresses if IR PGO is enabled or if clang value
791fe6060f1SDimitry Andric   // profiling is enabled. Recording function addresses greatly increases object
792fe6060f1SDimitry Andric   // file size, because it prevents the inliner from deleting functions that
793fe6060f1SDimitry Andric   // have been inlined everywhere.
794fe6060f1SDimitry Andric   if (!profDataReferencedByCode(*F->getParent()))
795fe6060f1SDimitry Andric     return false;
796fe6060f1SDimitry Andric 
797*0b57cec5SDimitry Andric   // Check the linkage
798*0b57cec5SDimitry Andric   bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
799*0b57cec5SDimitry Andric   if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
800*0b57cec5SDimitry Andric       !HasAvailableExternallyLinkage)
801*0b57cec5SDimitry Andric     return true;
802*0b57cec5SDimitry Andric 
803*0b57cec5SDimitry Andric   // A function marked 'alwaysinline' with available_externally linkage can't
804*0b57cec5SDimitry Andric   // have its address taken. Doing so would create an undefined external ref to
805*0b57cec5SDimitry Andric   // the function, which would fail to link.
806*0b57cec5SDimitry Andric   if (HasAvailableExternallyLinkage &&
807*0b57cec5SDimitry Andric       F->hasFnAttribute(Attribute::AlwaysInline))
808*0b57cec5SDimitry Andric     return false;
809*0b57cec5SDimitry Andric 
810*0b57cec5SDimitry Andric   // Prohibit function address recording if the function is both internal and
811*0b57cec5SDimitry Andric   // COMDAT. This avoids the profile data variable referencing internal symbols
812*0b57cec5SDimitry Andric   // in COMDAT.
813*0b57cec5SDimitry Andric   if (F->hasLocalLinkage() && F->hasComdat())
814*0b57cec5SDimitry Andric     return false;
815*0b57cec5SDimitry Andric 
816*0b57cec5SDimitry Andric   // Check uses of this function for other than direct calls or invokes to it.
817*0b57cec5SDimitry Andric   // Inline virtual functions have linkeOnceODR linkage. When a key method
818*0b57cec5SDimitry Andric   // exists, the vtable will only be emitted in the TU where the key method
819*0b57cec5SDimitry Andric   // is defined. In a TU where vtable is not available, the function won't
820*0b57cec5SDimitry Andric   // be 'addresstaken'. If its address is not recorded here, the profile data
821*0b57cec5SDimitry Andric   // with missing address may be picked by the linker leading  to missing
822*0b57cec5SDimitry Andric   // indirect call target info.
823*0b57cec5SDimitry Andric   return F->hasAddressTaken() || F->hasLinkOnceLinkage();
824*0b57cec5SDimitry Andric }
825*0b57cec5SDimitry Andric 
826*0b57cec5SDimitry Andric static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT) {
827*0b57cec5SDimitry Andric   // Don't do this for Darwin.  compiler-rt uses linker magic.
828*0b57cec5SDimitry Andric   if (TT.isOSDarwin())
829*0b57cec5SDimitry Andric     return false;
830*0b57cec5SDimitry Andric   // Use linker script magic to get data/cnts/name start/end.
83181ad6265SDimitry Andric   if (TT.isOSAIX() || TT.isOSLinux() || TT.isOSFreeBSD() || TT.isOSNetBSD() ||
83281ad6265SDimitry Andric       TT.isOSSolaris() || TT.isOSFuchsia() || TT.isPS() || TT.isOSWindows())
833*0b57cec5SDimitry Andric     return false;
834*0b57cec5SDimitry Andric 
835*0b57cec5SDimitry Andric   return true;
836*0b57cec5SDimitry Andric }
837*0b57cec5SDimitry Andric 
838*0b57cec5SDimitry Andric GlobalVariable *
8391fd87a68SDimitry Andric InstrProfiling::createRegionCounters(InstrProfInstBase *Inc, StringRef Name,
8401fd87a68SDimitry Andric                                      GlobalValue::LinkageTypes Linkage) {
8411fd87a68SDimitry Andric   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
8421fd87a68SDimitry Andric   auto &Ctx = M->getContext();
8431fd87a68SDimitry Andric   GlobalVariable *GV;
8441fd87a68SDimitry Andric   if (isa<InstrProfCoverInst>(Inc)) {
8451fd87a68SDimitry Andric     auto *CounterTy = Type::getInt8Ty(Ctx);
8461fd87a68SDimitry Andric     auto *CounterArrTy = ArrayType::get(CounterTy, NumCounters);
8471fd87a68SDimitry Andric     // TODO: `Constant::getAllOnesValue()` does not yet accept an array type.
8481fd87a68SDimitry Andric     std::vector<Constant *> InitialValues(NumCounters,
8491fd87a68SDimitry Andric                                           Constant::getAllOnesValue(CounterTy));
8501fd87a68SDimitry Andric     GV = new GlobalVariable(*M, CounterArrTy, false, Linkage,
8511fd87a68SDimitry Andric                             ConstantArray::get(CounterArrTy, InitialValues),
8521fd87a68SDimitry Andric                             Name);
8531fd87a68SDimitry Andric     GV->setAlignment(Align(1));
8541fd87a68SDimitry Andric   } else {
8551fd87a68SDimitry Andric     auto *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
8561fd87a68SDimitry Andric     GV = new GlobalVariable(*M, CounterTy, false, Linkage,
8571fd87a68SDimitry Andric                             Constant::getNullValue(CounterTy), Name);
8581fd87a68SDimitry Andric     GV->setAlignment(Align(8));
8591fd87a68SDimitry Andric   }
8601fd87a68SDimitry Andric   return GV;
8611fd87a68SDimitry Andric }
8621fd87a68SDimitry Andric 
8631fd87a68SDimitry Andric GlobalVariable *
86404eeddc0SDimitry Andric InstrProfiling::getOrCreateRegionCounters(InstrProfInstBase *Inc) {
865*0b57cec5SDimitry Andric   GlobalVariable *NamePtr = Inc->getName();
8664824e7fdSDimitry Andric   auto &PD = ProfileDataMap[NamePtr];
8674824e7fdSDimitry Andric   if (PD.RegionCounters)
8684824e7fdSDimitry Andric     return PD.RegionCounters;
869*0b57cec5SDimitry Andric 
870fe6060f1SDimitry Andric   // Match the linkage and visibility of the name global.
871*0b57cec5SDimitry Andric   Function *Fn = Inc->getParent()->getParent();
872*0b57cec5SDimitry Andric   GlobalValue::LinkageTypes Linkage = NamePtr->getLinkage();
873*0b57cec5SDimitry Andric   GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
874*0b57cec5SDimitry Andric 
8750eae32dcSDimitry Andric   // Use internal rather than private linkage so the counter variable shows up
8760eae32dcSDimitry Andric   // in the symbol table when using debug info for correlation.
8770eae32dcSDimitry Andric   if (DebugInfoCorrelate && TT.isOSBinFormatMachO() &&
8780eae32dcSDimitry Andric       Linkage == GlobalValue::PrivateLinkage)
8790eae32dcSDimitry Andric     Linkage = GlobalValue::InternalLinkage;
8800eae32dcSDimitry Andric 
881349cc55cSDimitry Andric   // Due to the limitation of binder as of 2021/09/28, the duplicate weak
882349cc55cSDimitry Andric   // symbols in the same csect won't be discarded. When there are duplicate weak
883349cc55cSDimitry Andric   // symbols, we can NOT guarantee that the relocations get resolved to the
884349cc55cSDimitry Andric   // intended weak symbol, so we can not ensure the correctness of the relative
885349cc55cSDimitry Andric   // CounterPtr, so we have to use private linkage for counter and data symbols.
886349cc55cSDimitry Andric   if (TT.isOSBinFormatXCOFF()) {
887349cc55cSDimitry Andric     Linkage = GlobalValue::PrivateLinkage;
888349cc55cSDimitry Andric     Visibility = GlobalValue::DefaultVisibility;
889349cc55cSDimitry Andric   }
890*0b57cec5SDimitry Andric   // Move the name variable to the right section. Place them in a COMDAT group
891*0b57cec5SDimitry Andric   // if the associated function is a COMDAT. This will make sure that only one
892*0b57cec5SDimitry Andric   // copy of counters of the COMDAT function will be emitted after linking. Keep
893*0b57cec5SDimitry Andric   // in mind that this pass may run before the inliner, so we need to create a
894*0b57cec5SDimitry Andric   // new comdat group for the counters and profiling data. If we use the comdat
895*0b57cec5SDimitry Andric   // of the parent function, that will result in relocations against discarded
896*0b57cec5SDimitry Andric   // sections.
897fe6060f1SDimitry Andric   //
898fe6060f1SDimitry Andric   // If the data variable is referenced by code,  counters and data have to be
899fe6060f1SDimitry Andric   // in different comdats for COFF because the Visual C++ linker will report
900fe6060f1SDimitry Andric   // duplicate symbol errors if there are multiple external symbols with the
901fe6060f1SDimitry Andric   // same name marked IMAGE_COMDAT_SELECT_ASSOCIATIVE.
902fe6060f1SDimitry Andric   //
903fe6060f1SDimitry Andric   // For ELF, when not using COMDAT, put counters, data and values into a
904fe6060f1SDimitry Andric   // nodeduplicate COMDAT which is lowered to a zero-flag section group. This
905fe6060f1SDimitry Andric   // allows -z start-stop-gc to discard the entire group when the function is
906fe6060f1SDimitry Andric   // discarded.
907fe6060f1SDimitry Andric   bool DataReferencedByCode = profDataReferencedByCode(*M);
908c14a5a88SDimitry Andric   bool NeedComdat = needsComdatForCounter(*Fn, *M);
909349cc55cSDimitry Andric   bool Renamed;
910349cc55cSDimitry Andric   std::string CntsVarName =
911349cc55cSDimitry Andric       getVarName(Inc, getInstrProfCountersVarPrefix(), Renamed);
912349cc55cSDimitry Andric   std::string DataVarName =
913349cc55cSDimitry Andric       getVarName(Inc, getInstrProfDataVarPrefix(), Renamed);
914fe6060f1SDimitry Andric   auto MaybeSetComdat = [&](GlobalVariable *GV) {
915fe6060f1SDimitry Andric     bool UseComdat = (NeedComdat || TT.isOSBinFormatELF());
916fe6060f1SDimitry Andric     if (UseComdat) {
917fe6060f1SDimitry Andric       StringRef GroupName = TT.isOSBinFormatCOFF() && DataReferencedByCode
918fe6060f1SDimitry Andric                                 ? GV->getName()
919fe6060f1SDimitry Andric                                 : CntsVarName;
920fe6060f1SDimitry Andric       Comdat *C = M->getOrInsertComdat(GroupName);
921fe6060f1SDimitry Andric       if (!NeedComdat)
922fe6060f1SDimitry Andric         C->setSelectionKind(Comdat::NoDeduplicate);
923fe6060f1SDimitry Andric       GV->setComdat(C);
924bdd1243dSDimitry Andric       // COFF doesn't allow the comdat group leader to have private linkage, so
925bdd1243dSDimitry Andric       // upgrade private linkage to internal linkage to produce a symbol table
926bdd1243dSDimitry Andric       // entry.
927bdd1243dSDimitry Andric       if (TT.isOSBinFormatCOFF() && GV->hasPrivateLinkage())
928bdd1243dSDimitry Andric         GV->setLinkage(GlobalValue::InternalLinkage);
929fe6060f1SDimitry Andric     }
930c14a5a88SDimitry Andric   };
931*0b57cec5SDimitry Andric 
932*0b57cec5SDimitry Andric   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
933*0b57cec5SDimitry Andric   LLVMContext &Ctx = M->getContext();
934*0b57cec5SDimitry Andric 
9351fd87a68SDimitry Andric   auto *CounterPtr = createRegionCounters(Inc, CntsVarName, Linkage);
936*0b57cec5SDimitry Andric   CounterPtr->setVisibility(Visibility);
937*0b57cec5SDimitry Andric   CounterPtr->setSection(
938*0b57cec5SDimitry Andric       getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
939c14a5a88SDimitry Andric   CounterPtr->setLinkage(Linkage);
940bdd1243dSDimitry Andric   MaybeSetComdat(CounterPtr);
9414824e7fdSDimitry Andric   PD.RegionCounters = CounterPtr;
9420eae32dcSDimitry Andric   if (DebugInfoCorrelate) {
9430eae32dcSDimitry Andric     if (auto *SP = Fn->getSubprogram()) {
9440eae32dcSDimitry Andric       DIBuilder DB(*M, true, SP->getUnit());
9450eae32dcSDimitry Andric       Metadata *FunctionNameAnnotation[] = {
9460eae32dcSDimitry Andric           MDString::get(Ctx, InstrProfCorrelator::FunctionNameAttributeName),
9470eae32dcSDimitry Andric           MDString::get(Ctx, getPGOFuncNameVarInitializer(NamePtr)),
9480eae32dcSDimitry Andric       };
9490eae32dcSDimitry Andric       Metadata *CFGHashAnnotation[] = {
9500eae32dcSDimitry Andric           MDString::get(Ctx, InstrProfCorrelator::CFGHashAttributeName),
9510eae32dcSDimitry Andric           ConstantAsMetadata::get(Inc->getHash()),
9520eae32dcSDimitry Andric       };
9530eae32dcSDimitry Andric       Metadata *NumCountersAnnotation[] = {
9540eae32dcSDimitry Andric           MDString::get(Ctx, InstrProfCorrelator::NumCountersAttributeName),
9550eae32dcSDimitry Andric           ConstantAsMetadata::get(Inc->getNumCounters()),
9560eae32dcSDimitry Andric       };
9570eae32dcSDimitry Andric       auto Annotations = DB.getOrCreateArray({
9580eae32dcSDimitry Andric           MDNode::get(Ctx, FunctionNameAnnotation),
9590eae32dcSDimitry Andric           MDNode::get(Ctx, CFGHashAnnotation),
9600eae32dcSDimitry Andric           MDNode::get(Ctx, NumCountersAnnotation),
9610eae32dcSDimitry Andric       });
9620eae32dcSDimitry Andric       auto *DICounter = DB.createGlobalVariableExpression(
9630eae32dcSDimitry Andric           SP, CounterPtr->getName(), /*LinkageName=*/StringRef(), SP->getFile(),
9640eae32dcSDimitry Andric           /*LineNo=*/0, DB.createUnspecifiedType("Profile Data Type"),
9650eae32dcSDimitry Andric           CounterPtr->hasLocalLinkage(), /*IsDefined=*/true, /*Expr=*/nullptr,
9660eae32dcSDimitry Andric           /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
9670eae32dcSDimitry Andric           Annotations);
9680eae32dcSDimitry Andric       CounterPtr->addDebugInfo(DICounter);
9690eae32dcSDimitry Andric       DB.finalize();
9700eae32dcSDimitry Andric     } else {
9710eae32dcSDimitry Andric       std::string Msg = ("Missing debug info for function " + Fn->getName() +
9720eae32dcSDimitry Andric                          "; required for profile correlation.")
9730eae32dcSDimitry Andric                             .str();
9740eae32dcSDimitry Andric       Ctx.diagnose(
9750eae32dcSDimitry Andric           DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
9760eae32dcSDimitry Andric     }
9770eae32dcSDimitry Andric   }
978*0b57cec5SDimitry Andric 
979*0b57cec5SDimitry Andric   auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
980*0b57cec5SDimitry Andric   // Allocate statically the array of pointers to value profile nodes for
981*0b57cec5SDimitry Andric   // the current function.
982*0b57cec5SDimitry Andric   Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
983*0b57cec5SDimitry Andric   uint64_t NS = 0;
984*0b57cec5SDimitry Andric   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
985*0b57cec5SDimitry Andric     NS += PD.NumValueSites[Kind];
986fe6060f1SDimitry Andric   if (NS > 0 && ValueProfileStaticAlloc &&
987fe6060f1SDimitry Andric       !needsRuntimeRegistrationOfSectionRange(TT)) {
988*0b57cec5SDimitry Andric     ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
989fe6060f1SDimitry Andric     auto *ValuesVar = new GlobalVariable(
990fe6060f1SDimitry Andric         *M, ValuesTy, false, Linkage, Constant::getNullValue(ValuesTy),
991349cc55cSDimitry Andric         getVarName(Inc, getInstrProfValuesVarPrefix(), Renamed));
992*0b57cec5SDimitry Andric     ValuesVar->setVisibility(Visibility);
993*0b57cec5SDimitry Andric     ValuesVar->setSection(
994*0b57cec5SDimitry Andric         getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
9958bcb0991SDimitry Andric     ValuesVar->setAlignment(Align(8));
996c14a5a88SDimitry Andric     MaybeSetComdat(ValuesVar);
997*0b57cec5SDimitry Andric     ValuesPtrExpr =
998*0b57cec5SDimitry Andric         ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
999*0b57cec5SDimitry Andric   }
1000*0b57cec5SDimitry Andric 
100104eeddc0SDimitry Andric   if (DebugInfoCorrelate) {
100204eeddc0SDimitry Andric     // Mark the counter variable as used so that it isn't optimized out.
100304eeddc0SDimitry Andric     CompilerUsedVars.push_back(PD.RegionCounters);
10040eae32dcSDimitry Andric     return PD.RegionCounters;
100504eeddc0SDimitry Andric   }
10060eae32dcSDimitry Andric 
1007*0b57cec5SDimitry Andric   // Create data variable.
1008349cc55cSDimitry Andric   auto *IntPtrTy = M->getDataLayout().getIntPtrType(M->getContext());
1009*0b57cec5SDimitry Andric   auto *Int16Ty = Type::getInt16Ty(Ctx);
1010*0b57cec5SDimitry Andric   auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
1011*0b57cec5SDimitry Andric   Type *DataTypes[] = {
1012*0b57cec5SDimitry Andric #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
1013*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
1014*0b57cec5SDimitry Andric   };
1015bdd1243dSDimitry Andric   auto *DataTy = StructType::get(Ctx, ArrayRef(DataTypes));
1016*0b57cec5SDimitry Andric 
1017*0b57cec5SDimitry Andric   Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
1018*0b57cec5SDimitry Andric                                ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
1019*0b57cec5SDimitry Andric                                : ConstantPointerNull::get(Int8PtrTy);
1020*0b57cec5SDimitry Andric 
1021*0b57cec5SDimitry Andric   Constant *Int16ArrayVals[IPVK_Last + 1];
1022*0b57cec5SDimitry Andric   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1023*0b57cec5SDimitry Andric     Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
1024*0b57cec5SDimitry Andric 
1025fe6060f1SDimitry Andric   // If the data variable is not referenced by code (if we don't emit
1026fe6060f1SDimitry Andric   // @llvm.instrprof.value.profile, NS will be 0), and the counter keeps the
1027fe6060f1SDimitry Andric   // data variable live under linker GC, the data variable can be private. This
1028fe6060f1SDimitry Andric   // optimization applies to ELF.
1029fe6060f1SDimitry Andric   //
1030fe6060f1SDimitry Andric   // On COFF, a comdat leader cannot be local so we require DataReferencedByCode
1031fe6060f1SDimitry Andric   // to be false.
1032349cc55cSDimitry Andric   //
1033349cc55cSDimitry Andric   // If profd is in a deduplicate comdat, NS==0 with a hash suffix guarantees
1034349cc55cSDimitry Andric   // that other copies must have the same CFG and cannot have value profiling.
1035349cc55cSDimitry Andric   // If no hash suffix, other profd copies may be referenced by code.
1036349cc55cSDimitry Andric   if (NS == 0 && !(DataReferencedByCode && NeedComdat && !Renamed) &&
1037349cc55cSDimitry Andric       (TT.isOSBinFormatELF() ||
1038fe6060f1SDimitry Andric        (!DataReferencedByCode && TT.isOSBinFormatCOFF()))) {
1039fe6060f1SDimitry Andric     Linkage = GlobalValue::PrivateLinkage;
1040fe6060f1SDimitry Andric     Visibility = GlobalValue::DefaultVisibility;
1041fe6060f1SDimitry Andric   }
1042e8d8bef9SDimitry Andric   auto *Data =
1043349cc55cSDimitry Andric       new GlobalVariable(*M, DataTy, false, Linkage, nullptr, DataVarName);
1044349cc55cSDimitry Andric   // Reference the counter variable with a label difference (link-time
1045349cc55cSDimitry Andric   // constant).
1046349cc55cSDimitry Andric   auto *RelativeCounterPtr =
1047349cc55cSDimitry Andric       ConstantExpr::getSub(ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy),
1048349cc55cSDimitry Andric                            ConstantExpr::getPtrToInt(Data, IntPtrTy));
1049349cc55cSDimitry Andric 
1050349cc55cSDimitry Andric   Constant *DataVals[] = {
1051349cc55cSDimitry Andric #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
1052349cc55cSDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
1053349cc55cSDimitry Andric   };
1054349cc55cSDimitry Andric   Data->setInitializer(ConstantStruct::get(DataTy, DataVals));
1055349cc55cSDimitry Andric 
1056*0b57cec5SDimitry Andric   Data->setVisibility(Visibility);
1057*0b57cec5SDimitry Andric   Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
10588bcb0991SDimitry Andric   Data->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
1059c14a5a88SDimitry Andric   MaybeSetComdat(Data);
1060*0b57cec5SDimitry Andric 
1061*0b57cec5SDimitry Andric   PD.DataVar = Data;
1062*0b57cec5SDimitry Andric 
1063*0b57cec5SDimitry Andric   // Mark the data variable as used so that it isn't stripped out.
1064fe6060f1SDimitry Andric   CompilerUsedVars.push_back(Data);
1065*0b57cec5SDimitry Andric   // Now that the linkage set by the FE has been passed to the data and counter
1066*0b57cec5SDimitry Andric   // variables, reset Name variable's linkage and visibility to private so that
1067*0b57cec5SDimitry Andric   // it can be removed later by the compiler.
1068*0b57cec5SDimitry Andric   NamePtr->setLinkage(GlobalValue::PrivateLinkage);
1069*0b57cec5SDimitry Andric   // Collect the referenced names to be used by emitNameData.
1070*0b57cec5SDimitry Andric   ReferencedNames.push_back(NamePtr);
1071*0b57cec5SDimitry Andric 
10724824e7fdSDimitry Andric   return PD.RegionCounters;
1073*0b57cec5SDimitry Andric }
1074*0b57cec5SDimitry Andric 
1075*0b57cec5SDimitry Andric void InstrProfiling::emitVNodes() {
1076*0b57cec5SDimitry Andric   if (!ValueProfileStaticAlloc)
1077*0b57cec5SDimitry Andric     return;
1078*0b57cec5SDimitry Andric 
1079*0b57cec5SDimitry Andric   // For now only support this on platforms that do
1080*0b57cec5SDimitry Andric   // not require runtime registration to discover
1081*0b57cec5SDimitry Andric   // named section start/end.
1082*0b57cec5SDimitry Andric   if (needsRuntimeRegistrationOfSectionRange(TT))
1083*0b57cec5SDimitry Andric     return;
1084*0b57cec5SDimitry Andric 
1085*0b57cec5SDimitry Andric   size_t TotalNS = 0;
1086*0b57cec5SDimitry Andric   for (auto &PD : ProfileDataMap) {
1087*0b57cec5SDimitry Andric     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1088*0b57cec5SDimitry Andric       TotalNS += PD.second.NumValueSites[Kind];
1089*0b57cec5SDimitry Andric   }
1090*0b57cec5SDimitry Andric 
1091*0b57cec5SDimitry Andric   if (!TotalNS)
1092*0b57cec5SDimitry Andric     return;
1093*0b57cec5SDimitry Andric 
1094*0b57cec5SDimitry Andric   uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
1095*0b57cec5SDimitry Andric // Heuristic for small programs with very few total value sites.
1096*0b57cec5SDimitry Andric // The default value of vp-counters-per-site is chosen based on
1097*0b57cec5SDimitry Andric // the observation that large apps usually have a low percentage
1098*0b57cec5SDimitry Andric // of value sites that actually have any profile data, and thus
1099*0b57cec5SDimitry Andric // the average number of counters per site is low. For small
1100*0b57cec5SDimitry Andric // apps with very few sites, this may not be true. Bump up the
1101*0b57cec5SDimitry Andric // number of counters in this case.
1102*0b57cec5SDimitry Andric #define INSTR_PROF_MIN_VAL_COUNTS 10
1103*0b57cec5SDimitry Andric   if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
1104*0b57cec5SDimitry Andric     NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
1105*0b57cec5SDimitry Andric 
1106*0b57cec5SDimitry Andric   auto &Ctx = M->getContext();
1107*0b57cec5SDimitry Andric   Type *VNodeTypes[] = {
1108*0b57cec5SDimitry Andric #define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
1109*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
1110*0b57cec5SDimitry Andric   };
1111bdd1243dSDimitry Andric   auto *VNodeTy = StructType::get(Ctx, ArrayRef(VNodeTypes));
1112*0b57cec5SDimitry Andric 
1113*0b57cec5SDimitry Andric   ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
1114*0b57cec5SDimitry Andric   auto *VNodesVar = new GlobalVariable(
1115*0b57cec5SDimitry Andric       *M, VNodesTy, false, GlobalValue::PrivateLinkage,
1116*0b57cec5SDimitry Andric       Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
1117*0b57cec5SDimitry Andric   VNodesVar->setSection(
1118*0b57cec5SDimitry Andric       getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
1119fe6060f1SDimitry Andric   // VNodesVar is used by runtime but not referenced via relocation by other
1120fe6060f1SDimitry Andric   // sections. Conservatively make it linker retained.
1121*0b57cec5SDimitry Andric   UsedVars.push_back(VNodesVar);
1122*0b57cec5SDimitry Andric }
1123*0b57cec5SDimitry Andric 
1124*0b57cec5SDimitry Andric void InstrProfiling::emitNameData() {
1125*0b57cec5SDimitry Andric   std::string UncompressedData;
1126*0b57cec5SDimitry Andric 
1127*0b57cec5SDimitry Andric   if (ReferencedNames.empty())
1128*0b57cec5SDimitry Andric     return;
1129*0b57cec5SDimitry Andric 
1130*0b57cec5SDimitry Andric   std::string CompressedNameStr;
1131*0b57cec5SDimitry Andric   if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
11325ffd83dbSDimitry Andric                                           DoInstrProfNameCompression)) {
1133349cc55cSDimitry Andric     report_fatal_error(Twine(toString(std::move(E))), false);
1134*0b57cec5SDimitry Andric   }
1135*0b57cec5SDimitry Andric 
1136*0b57cec5SDimitry Andric   auto &Ctx = M->getContext();
11374824e7fdSDimitry Andric   auto *NamesVal =
11384824e7fdSDimitry Andric       ConstantDataArray::getString(Ctx, StringRef(CompressedNameStr), false);
1139*0b57cec5SDimitry Andric   NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
1140*0b57cec5SDimitry Andric                                 GlobalValue::PrivateLinkage, NamesVal,
1141*0b57cec5SDimitry Andric                                 getInstrProfNamesVarName());
1142*0b57cec5SDimitry Andric   NamesSize = CompressedNameStr.size();
1143*0b57cec5SDimitry Andric   NamesVar->setSection(
1144*0b57cec5SDimitry Andric       getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
1145*0b57cec5SDimitry Andric   // On COFF, it's important to reduce the alignment down to 1 to prevent the
1146*0b57cec5SDimitry Andric   // linker from inserting padding before the start of the names section or
1147*0b57cec5SDimitry Andric   // between names entries.
11485ffd83dbSDimitry Andric   NamesVar->setAlignment(Align(1));
1149fe6060f1SDimitry Andric   // NamesVar is used by runtime but not referenced via relocation by other
1150fe6060f1SDimitry Andric   // sections. Conservatively make it linker retained.
1151*0b57cec5SDimitry Andric   UsedVars.push_back(NamesVar);
1152*0b57cec5SDimitry Andric 
1153*0b57cec5SDimitry Andric   for (auto *NamePtr : ReferencedNames)
1154*0b57cec5SDimitry Andric     NamePtr->eraseFromParent();
1155*0b57cec5SDimitry Andric }
1156*0b57cec5SDimitry Andric 
1157*0b57cec5SDimitry Andric void InstrProfiling::emitRegistration() {
1158*0b57cec5SDimitry Andric   if (!needsRuntimeRegistrationOfSectionRange(TT))
1159*0b57cec5SDimitry Andric     return;
1160*0b57cec5SDimitry Andric 
1161*0b57cec5SDimitry Andric   // Construct the function.
1162*0b57cec5SDimitry Andric   auto *VoidTy = Type::getVoidTy(M->getContext());
1163*0b57cec5SDimitry Andric   auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
1164*0b57cec5SDimitry Andric   auto *Int64Ty = Type::getInt64Ty(M->getContext());
1165*0b57cec5SDimitry Andric   auto *RegisterFTy = FunctionType::get(VoidTy, false);
1166*0b57cec5SDimitry Andric   auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
1167*0b57cec5SDimitry Andric                                      getInstrProfRegFuncsName(), M);
1168*0b57cec5SDimitry Andric   RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1169*0b57cec5SDimitry Andric   if (Options.NoRedZone)
1170*0b57cec5SDimitry Andric     RegisterF->addFnAttr(Attribute::NoRedZone);
1171*0b57cec5SDimitry Andric 
1172*0b57cec5SDimitry Andric   auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
1173*0b57cec5SDimitry Andric   auto *RuntimeRegisterF =
1174*0b57cec5SDimitry Andric       Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
1175*0b57cec5SDimitry Andric                        getInstrProfRegFuncName(), M);
1176*0b57cec5SDimitry Andric 
1177*0b57cec5SDimitry Andric   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
1178fe6060f1SDimitry Andric   for (Value *Data : CompilerUsedVars)
1179fe6060f1SDimitry Andric     if (!isa<Function>(Data))
1180fe6060f1SDimitry Andric       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
1181*0b57cec5SDimitry Andric   for (Value *Data : UsedVars)
1182*0b57cec5SDimitry Andric     if (Data != NamesVar && !isa<Function>(Data))
1183*0b57cec5SDimitry Andric       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
1184*0b57cec5SDimitry Andric 
1185*0b57cec5SDimitry Andric   if (NamesVar) {
1186*0b57cec5SDimitry Andric     Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
1187*0b57cec5SDimitry Andric     auto *NamesRegisterTy =
1188bdd1243dSDimitry Andric         FunctionType::get(VoidTy, ArrayRef(ParamTypes), false);
1189*0b57cec5SDimitry Andric     auto *NamesRegisterF =
1190*0b57cec5SDimitry Andric         Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
1191*0b57cec5SDimitry Andric                          getInstrProfNamesRegFuncName(), M);
1192*0b57cec5SDimitry Andric     IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
1193*0b57cec5SDimitry Andric                                     IRB.getInt64(NamesSize)});
1194*0b57cec5SDimitry Andric   }
1195*0b57cec5SDimitry Andric 
1196*0b57cec5SDimitry Andric   IRB.CreateRetVoid();
1197*0b57cec5SDimitry Andric }
1198*0b57cec5SDimitry Andric 
1199*0b57cec5SDimitry Andric bool InstrProfiling::emitRuntimeHook() {
1200349cc55cSDimitry Andric   // We expect the linker to be invoked with -u<hook_var> flag for Linux
1201349cc55cSDimitry Andric   // in which case there is no need to emit the external variable.
1202bdd1243dSDimitry Andric   if (TT.isOSLinux() || TT.isOSAIX())
1203*0b57cec5SDimitry Andric     return false;
1204*0b57cec5SDimitry Andric 
1205*0b57cec5SDimitry Andric   // If the module's provided its own runtime, we don't need to do anything.
1206*0b57cec5SDimitry Andric   if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
1207*0b57cec5SDimitry Andric     return false;
1208*0b57cec5SDimitry Andric 
1209*0b57cec5SDimitry Andric   // Declare an external variable that will pull in the runtime initialization.
1210*0b57cec5SDimitry Andric   auto *Int32Ty = Type::getInt32Ty(M->getContext());
1211*0b57cec5SDimitry Andric   auto *Var =
1212*0b57cec5SDimitry Andric       new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
1213*0b57cec5SDimitry Andric                          nullptr, getInstrProfRuntimeHookVarName());
1214753f127fSDimitry Andric   Var->setVisibility(GlobalValue::HiddenVisibility);
1215*0b57cec5SDimitry Andric 
121681ad6265SDimitry Andric   if (TT.isOSBinFormatELF() && !TT.isPS()) {
1217349cc55cSDimitry Andric     // Mark the user variable as used so that it isn't stripped out.
1218349cc55cSDimitry Andric     CompilerUsedVars.push_back(Var);
1219349cc55cSDimitry Andric   } else {
1220*0b57cec5SDimitry Andric     // Make a function that uses it.
1221*0b57cec5SDimitry Andric     auto *User = Function::Create(FunctionType::get(Int32Ty, false),
1222*0b57cec5SDimitry Andric                                   GlobalValue::LinkOnceODRLinkage,
1223*0b57cec5SDimitry Andric                                   getInstrProfRuntimeHookVarUseFuncName(), M);
1224*0b57cec5SDimitry Andric     User->addFnAttr(Attribute::NoInline);
1225*0b57cec5SDimitry Andric     if (Options.NoRedZone)
1226*0b57cec5SDimitry Andric       User->addFnAttr(Attribute::NoRedZone);
1227*0b57cec5SDimitry Andric     User->setVisibility(GlobalValue::HiddenVisibility);
1228*0b57cec5SDimitry Andric     if (TT.supportsCOMDAT())
1229*0b57cec5SDimitry Andric       User->setComdat(M->getOrInsertComdat(User->getName()));
1230*0b57cec5SDimitry Andric 
1231*0b57cec5SDimitry Andric     IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
1232*0b57cec5SDimitry Andric     auto *Load = IRB.CreateLoad(Int32Ty, Var);
1233*0b57cec5SDimitry Andric     IRB.CreateRet(Load);
1234*0b57cec5SDimitry Andric 
1235349cc55cSDimitry Andric     // Mark the function as used so that it isn't stripped out.
1236fe6060f1SDimitry Andric     CompilerUsedVars.push_back(User);
1237349cc55cSDimitry Andric   }
1238*0b57cec5SDimitry Andric   return true;
1239*0b57cec5SDimitry Andric }
1240*0b57cec5SDimitry Andric 
1241*0b57cec5SDimitry Andric void InstrProfiling::emitUses() {
1242fe6060f1SDimitry Andric   // The metadata sections are parallel arrays. Optimizers (e.g.
1243fe6060f1SDimitry Andric   // GlobalOpt/ConstantMerge) may not discard associated sections as a unit, so
1244fe6060f1SDimitry Andric   // we conservatively retain all unconditionally in the compiler.
1245fe6060f1SDimitry Andric   //
1246349cc55cSDimitry Andric   // On ELF and Mach-O, the linker can guarantee the associated sections will be
1247349cc55cSDimitry Andric   // retained or discarded as a unit, so llvm.compiler.used is sufficient.
1248349cc55cSDimitry Andric   // Similarly on COFF, if prof data is not referenced by code we use one comdat
1249349cc55cSDimitry Andric   // and ensure this GC property as well. Otherwise, we have to conservatively
1250349cc55cSDimitry Andric   // make all of the sections retained by the linker.
1251349cc55cSDimitry Andric   if (TT.isOSBinFormatELF() || TT.isOSBinFormatMachO() ||
1252fe6060f1SDimitry Andric       (TT.isOSBinFormatCOFF() && !profDataReferencedByCode(*M)))
1253fe6060f1SDimitry Andric     appendToCompilerUsed(*M, CompilerUsedVars);
1254fe6060f1SDimitry Andric   else
1255fe6060f1SDimitry Andric     appendToUsed(*M, CompilerUsedVars);
1256fe6060f1SDimitry Andric 
1257fe6060f1SDimitry Andric   // We do not add proper references from used metadata sections to NamesVar and
1258fe6060f1SDimitry Andric   // VNodesVar, so we have to be conservative and place them in llvm.used
1259fe6060f1SDimitry Andric   // regardless of the target,
1260*0b57cec5SDimitry Andric   appendToUsed(*M, UsedVars);
1261*0b57cec5SDimitry Andric }
1262*0b57cec5SDimitry Andric 
1263*0b57cec5SDimitry Andric void InstrProfiling::emitInitialization() {
1264*0b57cec5SDimitry Andric   // Create ProfileFileName variable. Don't don't this for the
1265*0b57cec5SDimitry Andric   // context-sensitive instrumentation lowering: This lowering is after
1266*0b57cec5SDimitry Andric   // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
1267*0b57cec5SDimitry Andric   // have already create the variable before LTO/ThinLTO linking.
1268*0b57cec5SDimitry Andric   if (!IsCS)
1269*0b57cec5SDimitry Andric     createProfileFileNameVar(*M, Options.InstrProfileOutput);
1270*0b57cec5SDimitry Andric   Function *RegisterF = M->getFunction(getInstrProfRegFuncsName());
1271*0b57cec5SDimitry Andric   if (!RegisterF)
1272*0b57cec5SDimitry Andric     return;
1273*0b57cec5SDimitry Andric 
1274*0b57cec5SDimitry Andric   // Create the initialization function.
1275*0b57cec5SDimitry Andric   auto *VoidTy = Type::getVoidTy(M->getContext());
1276*0b57cec5SDimitry Andric   auto *F = Function::Create(FunctionType::get(VoidTy, false),
1277*0b57cec5SDimitry Andric                              GlobalValue::InternalLinkage,
1278*0b57cec5SDimitry Andric                              getInstrProfInitFuncName(), M);
1279*0b57cec5SDimitry Andric   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1280*0b57cec5SDimitry Andric   F->addFnAttr(Attribute::NoInline);
1281*0b57cec5SDimitry Andric   if (Options.NoRedZone)
1282*0b57cec5SDimitry Andric     F->addFnAttr(Attribute::NoRedZone);
1283*0b57cec5SDimitry Andric 
1284*0b57cec5SDimitry Andric   // Add the basic block and the necessary calls.
1285*0b57cec5SDimitry Andric   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
1286*0b57cec5SDimitry Andric   IRB.CreateCall(RegisterF, {});
1287*0b57cec5SDimitry Andric   IRB.CreateRetVoid();
1288*0b57cec5SDimitry Andric 
1289*0b57cec5SDimitry Andric   appendToGlobalCtors(*M, F, 0);
1290*0b57cec5SDimitry Andric }
1291