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"
29*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
30*0b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
31*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
32*0b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
33*0b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
34*0b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
35*0b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
36*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
37*0b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
38*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
39*0b57cec5SDimitry Andric #include "llvm/IR/Type.h"
40*0b57cec5SDimitry Andric #include "llvm/Pass.h"
41*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProf.h"
42*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
43*0b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
44*0b57cec5SDimitry Andric #include "llvm/Support/Error.h"
45*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
46*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h"
48*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdater.h"
49*0b57cec5SDimitry Andric #include <algorithm>
50*0b57cec5SDimitry Andric #include <cassert>
51*0b57cec5SDimitry Andric #include <cstddef>
52*0b57cec5SDimitry Andric #include <cstdint>
53*0b57cec5SDimitry Andric #include <string>
54*0b57cec5SDimitry Andric 
55*0b57cec5SDimitry Andric using namespace llvm;
56*0b57cec5SDimitry Andric 
57*0b57cec5SDimitry Andric #define DEBUG_TYPE "instrprof"
58*0b57cec5SDimitry Andric 
59*0b57cec5SDimitry Andric // The start and end values of precise value profile range for memory
60*0b57cec5SDimitry Andric // intrinsic sizes
61*0b57cec5SDimitry Andric cl::opt<std::string> MemOPSizeRange(
62*0b57cec5SDimitry Andric     "memop-size-range",
63*0b57cec5SDimitry Andric     cl::desc("Set the range of size in memory intrinsic calls to be profiled "
64*0b57cec5SDimitry Andric              "precisely, in a format of <start_val>:<end_val>"),
65*0b57cec5SDimitry Andric     cl::init(""));
66*0b57cec5SDimitry Andric 
67*0b57cec5SDimitry Andric // The value that considered to be large value in  memory intrinsic.
68*0b57cec5SDimitry Andric cl::opt<unsigned> MemOPSizeLarge(
69*0b57cec5SDimitry Andric     "memop-size-large",
70*0b57cec5SDimitry Andric     cl::desc("Set large value thresthold in memory intrinsic size profiling. "
71*0b57cec5SDimitry Andric              "Value of 0 disables the large value profiling."),
72*0b57cec5SDimitry Andric     cl::init(8192));
73*0b57cec5SDimitry Andric 
74*0b57cec5SDimitry Andric namespace {
75*0b57cec5SDimitry Andric 
76*0b57cec5SDimitry Andric cl::opt<bool> DoNameCompression("enable-name-compression",
77*0b57cec5SDimitry Andric                                 cl::desc("Enable name string compression"),
78*0b57cec5SDimitry Andric                                 cl::init(true));
79*0b57cec5SDimitry Andric 
80*0b57cec5SDimitry Andric cl::opt<bool> DoHashBasedCounterSplit(
81*0b57cec5SDimitry Andric     "hash-based-counter-split",
82*0b57cec5SDimitry Andric     cl::desc("Rename counter variable of a comdat function based on cfg hash"),
83*0b57cec5SDimitry Andric     cl::init(true));
84*0b57cec5SDimitry Andric 
85*0b57cec5SDimitry Andric cl::opt<bool> ValueProfileStaticAlloc(
86*0b57cec5SDimitry Andric     "vp-static-alloc",
87*0b57cec5SDimitry Andric     cl::desc("Do static counter allocation for value profiler"),
88*0b57cec5SDimitry Andric     cl::init(true));
89*0b57cec5SDimitry Andric 
90*0b57cec5SDimitry Andric cl::opt<double> NumCountersPerValueSite(
91*0b57cec5SDimitry Andric     "vp-counters-per-site",
92*0b57cec5SDimitry Andric     cl::desc("The average number of profile counters allocated "
93*0b57cec5SDimitry Andric              "per value profiling site."),
94*0b57cec5SDimitry Andric     // This is set to a very small value because in real programs, only
95*0b57cec5SDimitry Andric     // a very small percentage of value sites have non-zero targets, e.g, 1/30.
96*0b57cec5SDimitry Andric     // For those sites with non-zero profile, the average number of targets
97*0b57cec5SDimitry Andric     // is usually smaller than 2.
98*0b57cec5SDimitry Andric     cl::init(1.0));
99*0b57cec5SDimitry Andric 
100*0b57cec5SDimitry Andric cl::opt<bool> AtomicCounterUpdateAll(
101*0b57cec5SDimitry Andric     "instrprof-atomic-counter-update-all", cl::ZeroOrMore,
102*0b57cec5SDimitry Andric     cl::desc("Make all profile counter updates atomic (for testing only)"),
103*0b57cec5SDimitry Andric     cl::init(false));
104*0b57cec5SDimitry Andric 
105*0b57cec5SDimitry Andric cl::opt<bool> AtomicCounterUpdatePromoted(
106*0b57cec5SDimitry Andric     "atomic-counter-update-promoted", cl::ZeroOrMore,
107*0b57cec5SDimitry Andric     cl::desc("Do counter update using atomic fetch add "
108*0b57cec5SDimitry Andric              " for promoted counters only"),
109*0b57cec5SDimitry Andric     cl::init(false));
110*0b57cec5SDimitry Andric 
111*0b57cec5SDimitry Andric // If the option is not specified, the default behavior about whether
112*0b57cec5SDimitry Andric // counter promotion is done depends on how instrumentaiton lowering
113*0b57cec5SDimitry Andric // pipeline is setup, i.e., the default value of true of this option
114*0b57cec5SDimitry Andric // does not mean the promotion will be done by default. Explicitly
115*0b57cec5SDimitry Andric // setting this option can override the default behavior.
116*0b57cec5SDimitry Andric cl::opt<bool> DoCounterPromotion("do-counter-promotion", cl::ZeroOrMore,
117*0b57cec5SDimitry Andric                                  cl::desc("Do counter register promotion"),
118*0b57cec5SDimitry Andric                                  cl::init(false));
119*0b57cec5SDimitry Andric cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
120*0b57cec5SDimitry Andric     cl::ZeroOrMore, "max-counter-promotions-per-loop", cl::init(20),
121*0b57cec5SDimitry Andric     cl::desc("Max number counter promotions per loop to avoid"
122*0b57cec5SDimitry Andric              " increasing register pressure too much"));
123*0b57cec5SDimitry Andric 
124*0b57cec5SDimitry Andric // A debug option
125*0b57cec5SDimitry Andric cl::opt<int>
126*0b57cec5SDimitry Andric     MaxNumOfPromotions(cl::ZeroOrMore, "max-counter-promotions", cl::init(-1),
127*0b57cec5SDimitry Andric                        cl::desc("Max number of allowed counter promotions"));
128*0b57cec5SDimitry Andric 
129*0b57cec5SDimitry Andric cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
130*0b57cec5SDimitry Andric     cl::ZeroOrMore, "speculative-counter-promotion-max-exiting", cl::init(3),
131*0b57cec5SDimitry Andric     cl::desc("The max number of exiting blocks of a loop to allow "
132*0b57cec5SDimitry Andric              " speculative counter promotion"));
133*0b57cec5SDimitry Andric 
134*0b57cec5SDimitry Andric cl::opt<bool> SpeculativeCounterPromotionToLoop(
135*0b57cec5SDimitry Andric     cl::ZeroOrMore, "speculative-counter-promotion-to-loop", cl::init(false),
136*0b57cec5SDimitry Andric     cl::desc("When the option is false, if the target block is in a loop, "
137*0b57cec5SDimitry Andric              "the promotion will be disallowed unless the promoted counter "
138*0b57cec5SDimitry Andric              " update can be further/iteratively promoted into an acyclic "
139*0b57cec5SDimitry Andric              " region."));
140*0b57cec5SDimitry Andric 
141*0b57cec5SDimitry Andric cl::opt<bool> IterativeCounterPromotion(
142*0b57cec5SDimitry Andric     cl::ZeroOrMore, "iterative-counter-promotion", cl::init(true),
143*0b57cec5SDimitry Andric     cl::desc("Allow counter promotion across the whole loop nest."));
144*0b57cec5SDimitry Andric 
145*0b57cec5SDimitry Andric class InstrProfilingLegacyPass : public ModulePass {
146*0b57cec5SDimitry Andric   InstrProfiling InstrProf;
147*0b57cec5SDimitry Andric 
148*0b57cec5SDimitry Andric public:
149*0b57cec5SDimitry Andric   static char ID;
150*0b57cec5SDimitry Andric 
151*0b57cec5SDimitry Andric   InstrProfilingLegacyPass() : ModulePass(ID) {}
152*0b57cec5SDimitry Andric   InstrProfilingLegacyPass(const InstrProfOptions &Options, bool IsCS = false)
153*0b57cec5SDimitry Andric       : ModulePass(ID), InstrProf(Options, IsCS) {}
154*0b57cec5SDimitry Andric 
155*0b57cec5SDimitry Andric   StringRef getPassName() const override {
156*0b57cec5SDimitry Andric     return "Frontend instrumentation-based coverage lowering";
157*0b57cec5SDimitry Andric   }
158*0b57cec5SDimitry Andric 
159*0b57cec5SDimitry Andric   bool runOnModule(Module &M) override {
160*0b57cec5SDimitry Andric     return InstrProf.run(M, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI());
161*0b57cec5SDimitry Andric   }
162*0b57cec5SDimitry Andric 
163*0b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
164*0b57cec5SDimitry Andric     AU.setPreservesCFG();
165*0b57cec5SDimitry Andric     AU.addRequired<TargetLibraryInfoWrapperPass>();
166*0b57cec5SDimitry Andric   }
167*0b57cec5SDimitry Andric };
168*0b57cec5SDimitry Andric 
169*0b57cec5SDimitry Andric ///
170*0b57cec5SDimitry Andric /// A helper class to promote one counter RMW operation in the loop
171*0b57cec5SDimitry Andric /// into register update.
172*0b57cec5SDimitry Andric ///
173*0b57cec5SDimitry Andric /// RWM update for the counter will be sinked out of the loop after
174*0b57cec5SDimitry Andric /// the transformation.
175*0b57cec5SDimitry Andric ///
176*0b57cec5SDimitry Andric class PGOCounterPromoterHelper : public LoadAndStorePromoter {
177*0b57cec5SDimitry Andric public:
178*0b57cec5SDimitry Andric   PGOCounterPromoterHelper(
179*0b57cec5SDimitry Andric       Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
180*0b57cec5SDimitry Andric       BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
181*0b57cec5SDimitry Andric       ArrayRef<Instruction *> InsertPts,
182*0b57cec5SDimitry Andric       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
183*0b57cec5SDimitry Andric       LoopInfo &LI)
184*0b57cec5SDimitry Andric       : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
185*0b57cec5SDimitry Andric         InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
186*0b57cec5SDimitry Andric     assert(isa<LoadInst>(L));
187*0b57cec5SDimitry Andric     assert(isa<StoreInst>(S));
188*0b57cec5SDimitry Andric     SSA.AddAvailableValue(PH, Init);
189*0b57cec5SDimitry Andric   }
190*0b57cec5SDimitry Andric 
191*0b57cec5SDimitry Andric   void doExtraRewritesBeforeFinalDeletion() override {
192*0b57cec5SDimitry Andric     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
193*0b57cec5SDimitry Andric       BasicBlock *ExitBlock = ExitBlocks[i];
194*0b57cec5SDimitry Andric       Instruction *InsertPos = InsertPts[i];
195*0b57cec5SDimitry Andric       // Get LiveIn value into the ExitBlock. If there are multiple
196*0b57cec5SDimitry Andric       // predecessors, the value is defined by a PHI node in this
197*0b57cec5SDimitry Andric       // block.
198*0b57cec5SDimitry Andric       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
199*0b57cec5SDimitry Andric       Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
200*0b57cec5SDimitry Andric       Type *Ty = LiveInValue->getType();
201*0b57cec5SDimitry Andric       IRBuilder<> Builder(InsertPos);
202*0b57cec5SDimitry Andric       if (AtomicCounterUpdatePromoted)
203*0b57cec5SDimitry Andric         // automic update currently can only be promoted across the current
204*0b57cec5SDimitry Andric         // loop, not the whole loop nest.
205*0b57cec5SDimitry Andric         Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
206*0b57cec5SDimitry Andric                                 AtomicOrdering::SequentiallyConsistent);
207*0b57cec5SDimitry Andric       else {
208*0b57cec5SDimitry Andric         LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
209*0b57cec5SDimitry Andric         auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
210*0b57cec5SDimitry Andric         auto *NewStore = Builder.CreateStore(NewVal, Addr);
211*0b57cec5SDimitry Andric 
212*0b57cec5SDimitry Andric         // Now update the parent loop's candidate list:
213*0b57cec5SDimitry Andric         if (IterativeCounterPromotion) {
214*0b57cec5SDimitry Andric           auto *TargetLoop = LI.getLoopFor(ExitBlock);
215*0b57cec5SDimitry Andric           if (TargetLoop)
216*0b57cec5SDimitry Andric             LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
217*0b57cec5SDimitry Andric         }
218*0b57cec5SDimitry Andric       }
219*0b57cec5SDimitry Andric     }
220*0b57cec5SDimitry Andric   }
221*0b57cec5SDimitry Andric 
222*0b57cec5SDimitry Andric private:
223*0b57cec5SDimitry Andric   Instruction *Store;
224*0b57cec5SDimitry Andric   ArrayRef<BasicBlock *> ExitBlocks;
225*0b57cec5SDimitry Andric   ArrayRef<Instruction *> InsertPts;
226*0b57cec5SDimitry Andric   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
227*0b57cec5SDimitry Andric   LoopInfo &LI;
228*0b57cec5SDimitry Andric };
229*0b57cec5SDimitry Andric 
230*0b57cec5SDimitry Andric /// A helper class to do register promotion for all profile counter
231*0b57cec5SDimitry Andric /// updates in a loop.
232*0b57cec5SDimitry Andric ///
233*0b57cec5SDimitry Andric class PGOCounterPromoter {
234*0b57cec5SDimitry Andric public:
235*0b57cec5SDimitry Andric   PGOCounterPromoter(
236*0b57cec5SDimitry Andric       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
237*0b57cec5SDimitry Andric       Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI)
238*0b57cec5SDimitry Andric       : LoopToCandidates(LoopToCands), ExitBlocks(), InsertPts(), L(CurLoop),
239*0b57cec5SDimitry Andric         LI(LI), BFI(BFI) {
240*0b57cec5SDimitry Andric 
241*0b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> LoopExitBlocks;
242*0b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 8> BlockSet;
243*0b57cec5SDimitry Andric     L.getExitBlocks(LoopExitBlocks);
244*0b57cec5SDimitry Andric 
245*0b57cec5SDimitry Andric     for (BasicBlock *ExitBlock : LoopExitBlocks) {
246*0b57cec5SDimitry Andric       if (BlockSet.insert(ExitBlock).second) {
247*0b57cec5SDimitry Andric         ExitBlocks.push_back(ExitBlock);
248*0b57cec5SDimitry Andric         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
249*0b57cec5SDimitry Andric       }
250*0b57cec5SDimitry Andric     }
251*0b57cec5SDimitry Andric   }
252*0b57cec5SDimitry Andric 
253*0b57cec5SDimitry Andric   bool run(int64_t *NumPromoted) {
254*0b57cec5SDimitry Andric     // Skip 'infinite' loops:
255*0b57cec5SDimitry Andric     if (ExitBlocks.size() == 0)
256*0b57cec5SDimitry Andric       return false;
257*0b57cec5SDimitry Andric     unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
258*0b57cec5SDimitry Andric     if (MaxProm == 0)
259*0b57cec5SDimitry Andric       return false;
260*0b57cec5SDimitry Andric 
261*0b57cec5SDimitry Andric     unsigned Promoted = 0;
262*0b57cec5SDimitry Andric     for (auto &Cand : LoopToCandidates[&L]) {
263*0b57cec5SDimitry Andric 
264*0b57cec5SDimitry Andric       SmallVector<PHINode *, 4> NewPHIs;
265*0b57cec5SDimitry Andric       SSAUpdater SSA(&NewPHIs);
266*0b57cec5SDimitry Andric       Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
267*0b57cec5SDimitry Andric 
268*0b57cec5SDimitry Andric       // If BFI is set, we will use it to guide the promotions.
269*0b57cec5SDimitry Andric       if (BFI) {
270*0b57cec5SDimitry Andric         auto *BB = Cand.first->getParent();
271*0b57cec5SDimitry Andric         auto InstrCount = BFI->getBlockProfileCount(BB);
272*0b57cec5SDimitry Andric         if (!InstrCount)
273*0b57cec5SDimitry Andric           continue;
274*0b57cec5SDimitry Andric         auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
275*0b57cec5SDimitry Andric         // If the average loop trip count is not greater than 1.5, we skip
276*0b57cec5SDimitry Andric         // promotion.
277*0b57cec5SDimitry Andric         if (PreheaderCount &&
278*0b57cec5SDimitry Andric             (PreheaderCount.getValue() * 3) >= (InstrCount.getValue() * 2))
279*0b57cec5SDimitry Andric           continue;
280*0b57cec5SDimitry Andric       }
281*0b57cec5SDimitry Andric 
282*0b57cec5SDimitry Andric       PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
283*0b57cec5SDimitry Andric                                         L.getLoopPreheader(), ExitBlocks,
284*0b57cec5SDimitry Andric                                         InsertPts, LoopToCandidates, LI);
285*0b57cec5SDimitry Andric       Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
286*0b57cec5SDimitry Andric       Promoted++;
287*0b57cec5SDimitry Andric       if (Promoted >= MaxProm)
288*0b57cec5SDimitry Andric         break;
289*0b57cec5SDimitry Andric 
290*0b57cec5SDimitry Andric       (*NumPromoted)++;
291*0b57cec5SDimitry Andric       if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
292*0b57cec5SDimitry Andric         break;
293*0b57cec5SDimitry Andric     }
294*0b57cec5SDimitry Andric 
295*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
296*0b57cec5SDimitry Andric                       << L.getLoopDepth() << ")\n");
297*0b57cec5SDimitry Andric     return Promoted != 0;
298*0b57cec5SDimitry Andric   }
299*0b57cec5SDimitry Andric 
300*0b57cec5SDimitry Andric private:
301*0b57cec5SDimitry Andric   bool allowSpeculativeCounterPromotion(Loop *LP) {
302*0b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> ExitingBlocks;
303*0b57cec5SDimitry Andric     L.getExitingBlocks(ExitingBlocks);
304*0b57cec5SDimitry Andric     // Not considierered speculative.
305*0b57cec5SDimitry Andric     if (ExitingBlocks.size() == 1)
306*0b57cec5SDimitry Andric       return true;
307*0b57cec5SDimitry Andric     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
308*0b57cec5SDimitry Andric       return false;
309*0b57cec5SDimitry Andric     return true;
310*0b57cec5SDimitry Andric   }
311*0b57cec5SDimitry Andric 
312*0b57cec5SDimitry Andric   // Returns the max number of Counter Promotions for LP.
313*0b57cec5SDimitry Andric   unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
314*0b57cec5SDimitry Andric     // We can't insert into a catchswitch.
315*0b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> LoopExitBlocks;
316*0b57cec5SDimitry Andric     LP->getExitBlocks(LoopExitBlocks);
317*0b57cec5SDimitry Andric     if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
318*0b57cec5SDimitry Andric           return isa<CatchSwitchInst>(Exit->getTerminator());
319*0b57cec5SDimitry Andric         }))
320*0b57cec5SDimitry Andric       return 0;
321*0b57cec5SDimitry Andric 
322*0b57cec5SDimitry Andric     if (!LP->hasDedicatedExits())
323*0b57cec5SDimitry Andric       return 0;
324*0b57cec5SDimitry Andric 
325*0b57cec5SDimitry Andric     BasicBlock *PH = LP->getLoopPreheader();
326*0b57cec5SDimitry Andric     if (!PH)
327*0b57cec5SDimitry Andric       return 0;
328*0b57cec5SDimitry Andric 
329*0b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> ExitingBlocks;
330*0b57cec5SDimitry Andric     LP->getExitingBlocks(ExitingBlocks);
331*0b57cec5SDimitry Andric 
332*0b57cec5SDimitry Andric     // If BFI is set, we do more aggressive promotions based on BFI.
333*0b57cec5SDimitry Andric     if (BFI)
334*0b57cec5SDimitry Andric       return (unsigned)-1;
335*0b57cec5SDimitry Andric 
336*0b57cec5SDimitry Andric     // Not considierered speculative.
337*0b57cec5SDimitry Andric     if (ExitingBlocks.size() == 1)
338*0b57cec5SDimitry Andric       return MaxNumOfPromotionsPerLoop;
339*0b57cec5SDimitry Andric 
340*0b57cec5SDimitry Andric     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
341*0b57cec5SDimitry Andric       return 0;
342*0b57cec5SDimitry Andric 
343*0b57cec5SDimitry Andric     // Whether the target block is in a loop does not matter:
344*0b57cec5SDimitry Andric     if (SpeculativeCounterPromotionToLoop)
345*0b57cec5SDimitry Andric       return MaxNumOfPromotionsPerLoop;
346*0b57cec5SDimitry Andric 
347*0b57cec5SDimitry Andric     // Now check the target block:
348*0b57cec5SDimitry Andric     unsigned MaxProm = MaxNumOfPromotionsPerLoop;
349*0b57cec5SDimitry Andric     for (auto *TargetBlock : LoopExitBlocks) {
350*0b57cec5SDimitry Andric       auto *TargetLoop = LI.getLoopFor(TargetBlock);
351*0b57cec5SDimitry Andric       if (!TargetLoop)
352*0b57cec5SDimitry Andric         continue;
353*0b57cec5SDimitry Andric       unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
354*0b57cec5SDimitry Andric       unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
355*0b57cec5SDimitry Andric       MaxProm =
356*0b57cec5SDimitry Andric           std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
357*0b57cec5SDimitry Andric                                 PendingCandsInTarget);
358*0b57cec5SDimitry Andric     }
359*0b57cec5SDimitry Andric     return MaxProm;
360*0b57cec5SDimitry Andric   }
361*0b57cec5SDimitry Andric 
362*0b57cec5SDimitry Andric   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
363*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 8> ExitBlocks;
364*0b57cec5SDimitry Andric   SmallVector<Instruction *, 8> InsertPts;
365*0b57cec5SDimitry Andric   Loop &L;
366*0b57cec5SDimitry Andric   LoopInfo &LI;
367*0b57cec5SDimitry Andric   BlockFrequencyInfo *BFI;
368*0b57cec5SDimitry Andric };
369*0b57cec5SDimitry Andric 
370*0b57cec5SDimitry Andric } // end anonymous namespace
371*0b57cec5SDimitry Andric 
372*0b57cec5SDimitry Andric PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
373*0b57cec5SDimitry Andric   auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
374*0b57cec5SDimitry Andric   if (!run(M, TLI))
375*0b57cec5SDimitry Andric     return PreservedAnalyses::all();
376*0b57cec5SDimitry Andric 
377*0b57cec5SDimitry Andric   return PreservedAnalyses::none();
378*0b57cec5SDimitry Andric }
379*0b57cec5SDimitry Andric 
380*0b57cec5SDimitry Andric char InstrProfilingLegacyPass::ID = 0;
381*0b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(
382*0b57cec5SDimitry Andric     InstrProfilingLegacyPass, "instrprof",
383*0b57cec5SDimitry Andric     "Frontend instrumentation-based coverage lowering.", false, false)
384*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
385*0b57cec5SDimitry Andric INITIALIZE_PASS_END(
386*0b57cec5SDimitry Andric     InstrProfilingLegacyPass, "instrprof",
387*0b57cec5SDimitry Andric     "Frontend instrumentation-based coverage lowering.", false, false)
388*0b57cec5SDimitry Andric 
389*0b57cec5SDimitry Andric ModulePass *
390*0b57cec5SDimitry Andric llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options,
391*0b57cec5SDimitry Andric                                      bool IsCS) {
392*0b57cec5SDimitry Andric   return new InstrProfilingLegacyPass(Options, IsCS);
393*0b57cec5SDimitry Andric }
394*0b57cec5SDimitry Andric 
395*0b57cec5SDimitry Andric static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
396*0b57cec5SDimitry Andric   InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
397*0b57cec5SDimitry Andric   if (Inc)
398*0b57cec5SDimitry Andric     return Inc;
399*0b57cec5SDimitry Andric   return dyn_cast<InstrProfIncrementInst>(Instr);
400*0b57cec5SDimitry Andric }
401*0b57cec5SDimitry Andric 
402*0b57cec5SDimitry Andric bool InstrProfiling::lowerIntrinsics(Function *F) {
403*0b57cec5SDimitry Andric   bool MadeChange = false;
404*0b57cec5SDimitry Andric   PromotionCandidates.clear();
405*0b57cec5SDimitry Andric   for (BasicBlock &BB : *F) {
406*0b57cec5SDimitry Andric     for (auto I = BB.begin(), E = BB.end(); I != E;) {
407*0b57cec5SDimitry Andric       auto Instr = I++;
408*0b57cec5SDimitry Andric       InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
409*0b57cec5SDimitry Andric       if (Inc) {
410*0b57cec5SDimitry Andric         lowerIncrement(Inc);
411*0b57cec5SDimitry Andric         MadeChange = true;
412*0b57cec5SDimitry Andric       } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
413*0b57cec5SDimitry Andric         lowerValueProfileInst(Ind);
414*0b57cec5SDimitry Andric         MadeChange = true;
415*0b57cec5SDimitry Andric       }
416*0b57cec5SDimitry Andric     }
417*0b57cec5SDimitry Andric   }
418*0b57cec5SDimitry Andric 
419*0b57cec5SDimitry Andric   if (!MadeChange)
420*0b57cec5SDimitry Andric     return false;
421*0b57cec5SDimitry Andric 
422*0b57cec5SDimitry Andric   promoteCounterLoadStores(F);
423*0b57cec5SDimitry Andric   return true;
424*0b57cec5SDimitry Andric }
425*0b57cec5SDimitry Andric 
426*0b57cec5SDimitry Andric bool InstrProfiling::isCounterPromotionEnabled() const {
427*0b57cec5SDimitry Andric   if (DoCounterPromotion.getNumOccurrences() > 0)
428*0b57cec5SDimitry Andric     return DoCounterPromotion;
429*0b57cec5SDimitry Andric 
430*0b57cec5SDimitry Andric   return Options.DoCounterPromotion;
431*0b57cec5SDimitry Andric }
432*0b57cec5SDimitry Andric 
433*0b57cec5SDimitry Andric void InstrProfiling::promoteCounterLoadStores(Function *F) {
434*0b57cec5SDimitry Andric   if (!isCounterPromotionEnabled())
435*0b57cec5SDimitry Andric     return;
436*0b57cec5SDimitry Andric 
437*0b57cec5SDimitry Andric   DominatorTree DT(*F);
438*0b57cec5SDimitry Andric   LoopInfo LI(DT);
439*0b57cec5SDimitry Andric   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
440*0b57cec5SDimitry Andric 
441*0b57cec5SDimitry Andric   std::unique_ptr<BlockFrequencyInfo> BFI;
442*0b57cec5SDimitry Andric   if (Options.UseBFIInPromotion) {
443*0b57cec5SDimitry Andric     std::unique_ptr<BranchProbabilityInfo> BPI;
444*0b57cec5SDimitry Andric     BPI.reset(new BranchProbabilityInfo(*F, LI, TLI));
445*0b57cec5SDimitry Andric     BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
446*0b57cec5SDimitry Andric   }
447*0b57cec5SDimitry Andric 
448*0b57cec5SDimitry Andric   for (const auto &LoadStore : PromotionCandidates) {
449*0b57cec5SDimitry Andric     auto *CounterLoad = LoadStore.first;
450*0b57cec5SDimitry Andric     auto *CounterStore = LoadStore.second;
451*0b57cec5SDimitry Andric     BasicBlock *BB = CounterLoad->getParent();
452*0b57cec5SDimitry Andric     Loop *ParentLoop = LI.getLoopFor(BB);
453*0b57cec5SDimitry Andric     if (!ParentLoop)
454*0b57cec5SDimitry Andric       continue;
455*0b57cec5SDimitry Andric     LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
456*0b57cec5SDimitry Andric   }
457*0b57cec5SDimitry Andric 
458*0b57cec5SDimitry Andric   SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
459*0b57cec5SDimitry Andric 
460*0b57cec5SDimitry Andric   // Do a post-order traversal of the loops so that counter updates can be
461*0b57cec5SDimitry Andric   // iteratively hoisted outside the loop nest.
462*0b57cec5SDimitry Andric   for (auto *Loop : llvm::reverse(Loops)) {
463*0b57cec5SDimitry Andric     PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get());
464*0b57cec5SDimitry Andric     Promoter.run(&TotalCountersPromoted);
465*0b57cec5SDimitry Andric   }
466*0b57cec5SDimitry Andric }
467*0b57cec5SDimitry Andric 
468*0b57cec5SDimitry Andric /// Check if the module contains uses of any profiling intrinsics.
469*0b57cec5SDimitry Andric static bool containsProfilingIntrinsics(Module &M) {
470*0b57cec5SDimitry Andric   if (auto *F = M.getFunction(
471*0b57cec5SDimitry Andric           Intrinsic::getName(llvm::Intrinsic::instrprof_increment)))
472*0b57cec5SDimitry Andric     if (!F->use_empty())
473*0b57cec5SDimitry Andric       return true;
474*0b57cec5SDimitry Andric   if (auto *F = M.getFunction(
475*0b57cec5SDimitry Andric           Intrinsic::getName(llvm::Intrinsic::instrprof_increment_step)))
476*0b57cec5SDimitry Andric     if (!F->use_empty())
477*0b57cec5SDimitry Andric       return true;
478*0b57cec5SDimitry Andric   if (auto *F = M.getFunction(
479*0b57cec5SDimitry Andric           Intrinsic::getName(llvm::Intrinsic::instrprof_value_profile)))
480*0b57cec5SDimitry Andric     if (!F->use_empty())
481*0b57cec5SDimitry Andric       return true;
482*0b57cec5SDimitry Andric   return false;
483*0b57cec5SDimitry Andric }
484*0b57cec5SDimitry Andric 
485*0b57cec5SDimitry Andric bool InstrProfiling::run(Module &M, const TargetLibraryInfo &TLI) {
486*0b57cec5SDimitry Andric   this->M = &M;
487*0b57cec5SDimitry Andric   this->TLI = &TLI;
488*0b57cec5SDimitry Andric   NamesVar = nullptr;
489*0b57cec5SDimitry Andric   NamesSize = 0;
490*0b57cec5SDimitry Andric   ProfileDataMap.clear();
491*0b57cec5SDimitry Andric   UsedVars.clear();
492*0b57cec5SDimitry Andric   getMemOPSizeRangeFromOption(MemOPSizeRange, MemOPSizeRangeStart,
493*0b57cec5SDimitry Andric                               MemOPSizeRangeLast);
494*0b57cec5SDimitry Andric   TT = Triple(M.getTargetTriple());
495*0b57cec5SDimitry Andric 
496*0b57cec5SDimitry Andric   // Emit the runtime hook even if no counters are present.
497*0b57cec5SDimitry Andric   bool MadeChange = emitRuntimeHook();
498*0b57cec5SDimitry Andric 
499*0b57cec5SDimitry Andric   // Improve compile time by avoiding linear scans when there is no work.
500*0b57cec5SDimitry Andric   GlobalVariable *CoverageNamesVar =
501*0b57cec5SDimitry Andric       M.getNamedGlobal(getCoverageUnusedNamesVarName());
502*0b57cec5SDimitry Andric   if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
503*0b57cec5SDimitry Andric     return MadeChange;
504*0b57cec5SDimitry Andric 
505*0b57cec5SDimitry Andric   // We did not know how many value sites there would be inside
506*0b57cec5SDimitry Andric   // the instrumented function. This is counting the number of instrumented
507*0b57cec5SDimitry Andric   // target value sites to enter it as field in the profile data variable.
508*0b57cec5SDimitry Andric   for (Function &F : M) {
509*0b57cec5SDimitry Andric     InstrProfIncrementInst *FirstProfIncInst = nullptr;
510*0b57cec5SDimitry Andric     for (BasicBlock &BB : F)
511*0b57cec5SDimitry Andric       for (auto I = BB.begin(), E = BB.end(); I != E; I++)
512*0b57cec5SDimitry Andric         if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
513*0b57cec5SDimitry Andric           computeNumValueSiteCounts(Ind);
514*0b57cec5SDimitry Andric         else if (FirstProfIncInst == nullptr)
515*0b57cec5SDimitry Andric           FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
516*0b57cec5SDimitry Andric 
517*0b57cec5SDimitry Andric     // Value profiling intrinsic lowering requires per-function profile data
518*0b57cec5SDimitry Andric     // variable to be created first.
519*0b57cec5SDimitry Andric     if (FirstProfIncInst != nullptr)
520*0b57cec5SDimitry Andric       static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
521*0b57cec5SDimitry Andric   }
522*0b57cec5SDimitry Andric 
523*0b57cec5SDimitry Andric   for (Function &F : M)
524*0b57cec5SDimitry Andric     MadeChange |= lowerIntrinsics(&F);
525*0b57cec5SDimitry Andric 
526*0b57cec5SDimitry Andric   if (CoverageNamesVar) {
527*0b57cec5SDimitry Andric     lowerCoverageData(CoverageNamesVar);
528*0b57cec5SDimitry Andric     MadeChange = true;
529*0b57cec5SDimitry Andric   }
530*0b57cec5SDimitry Andric 
531*0b57cec5SDimitry Andric   if (!MadeChange)
532*0b57cec5SDimitry Andric     return false;
533*0b57cec5SDimitry Andric 
534*0b57cec5SDimitry Andric   emitVNodes();
535*0b57cec5SDimitry Andric   emitNameData();
536*0b57cec5SDimitry Andric   emitRegistration();
537*0b57cec5SDimitry Andric   emitUses();
538*0b57cec5SDimitry Andric   emitInitialization();
539*0b57cec5SDimitry Andric   return true;
540*0b57cec5SDimitry Andric }
541*0b57cec5SDimitry Andric 
542*0b57cec5SDimitry Andric static FunctionCallee
543*0b57cec5SDimitry Andric getOrInsertValueProfilingCall(Module &M, const TargetLibraryInfo &TLI,
544*0b57cec5SDimitry Andric                               bool IsRange = false) {
545*0b57cec5SDimitry Andric   LLVMContext &Ctx = M.getContext();
546*0b57cec5SDimitry Andric   auto *ReturnTy = Type::getVoidTy(M.getContext());
547*0b57cec5SDimitry Andric 
548*0b57cec5SDimitry Andric   AttributeList AL;
549*0b57cec5SDimitry Andric   if (auto AK = TLI.getExtAttrForI32Param(false))
550*0b57cec5SDimitry Andric     AL = AL.addParamAttribute(M.getContext(), 2, AK);
551*0b57cec5SDimitry Andric 
552*0b57cec5SDimitry Andric   if (!IsRange) {
553*0b57cec5SDimitry Andric     Type *ParamTypes[] = {
554*0b57cec5SDimitry Andric #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
555*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
556*0b57cec5SDimitry Andric     };
557*0b57cec5SDimitry Andric     auto *ValueProfilingCallTy =
558*0b57cec5SDimitry Andric         FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
559*0b57cec5SDimitry Andric     return M.getOrInsertFunction(getInstrProfValueProfFuncName(),
560*0b57cec5SDimitry Andric                                  ValueProfilingCallTy, AL);
561*0b57cec5SDimitry Andric   } else {
562*0b57cec5SDimitry Andric     Type *RangeParamTypes[] = {
563*0b57cec5SDimitry Andric #define VALUE_RANGE_PROF 1
564*0b57cec5SDimitry Andric #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
565*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
566*0b57cec5SDimitry Andric #undef VALUE_RANGE_PROF
567*0b57cec5SDimitry Andric     };
568*0b57cec5SDimitry Andric     auto *ValueRangeProfilingCallTy =
569*0b57cec5SDimitry Andric         FunctionType::get(ReturnTy, makeArrayRef(RangeParamTypes), false);
570*0b57cec5SDimitry Andric     return M.getOrInsertFunction(getInstrProfValueRangeProfFuncName(),
571*0b57cec5SDimitry Andric                                  ValueRangeProfilingCallTy, AL);
572*0b57cec5SDimitry Andric   }
573*0b57cec5SDimitry Andric }
574*0b57cec5SDimitry Andric 
575*0b57cec5SDimitry Andric void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
576*0b57cec5SDimitry Andric   GlobalVariable *Name = Ind->getName();
577*0b57cec5SDimitry Andric   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
578*0b57cec5SDimitry Andric   uint64_t Index = Ind->getIndex()->getZExtValue();
579*0b57cec5SDimitry Andric   auto It = ProfileDataMap.find(Name);
580*0b57cec5SDimitry Andric   if (It == ProfileDataMap.end()) {
581*0b57cec5SDimitry Andric     PerFunctionProfileData PD;
582*0b57cec5SDimitry Andric     PD.NumValueSites[ValueKind] = Index + 1;
583*0b57cec5SDimitry Andric     ProfileDataMap[Name] = PD;
584*0b57cec5SDimitry Andric   } else if (It->second.NumValueSites[ValueKind] <= Index)
585*0b57cec5SDimitry Andric     It->second.NumValueSites[ValueKind] = Index + 1;
586*0b57cec5SDimitry Andric }
587*0b57cec5SDimitry Andric 
588*0b57cec5SDimitry Andric void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
589*0b57cec5SDimitry Andric   GlobalVariable *Name = Ind->getName();
590*0b57cec5SDimitry Andric   auto It = ProfileDataMap.find(Name);
591*0b57cec5SDimitry Andric   assert(It != ProfileDataMap.end() && It->second.DataVar &&
592*0b57cec5SDimitry Andric          "value profiling detected in function with no counter incerement");
593*0b57cec5SDimitry Andric 
594*0b57cec5SDimitry Andric   GlobalVariable *DataVar = It->second.DataVar;
595*0b57cec5SDimitry Andric   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
596*0b57cec5SDimitry Andric   uint64_t Index = Ind->getIndex()->getZExtValue();
597*0b57cec5SDimitry Andric   for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
598*0b57cec5SDimitry Andric     Index += It->second.NumValueSites[Kind];
599*0b57cec5SDimitry Andric 
600*0b57cec5SDimitry Andric   IRBuilder<> Builder(Ind);
601*0b57cec5SDimitry Andric   bool IsRange = (Ind->getValueKind()->getZExtValue() ==
602*0b57cec5SDimitry Andric                   llvm::InstrProfValueKind::IPVK_MemOPSize);
603*0b57cec5SDimitry Andric   CallInst *Call = nullptr;
604*0b57cec5SDimitry Andric   if (!IsRange) {
605*0b57cec5SDimitry Andric     Value *Args[3] = {Ind->getTargetValue(),
606*0b57cec5SDimitry Andric                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
607*0b57cec5SDimitry Andric                       Builder.getInt32(Index)};
608*0b57cec5SDimitry Andric     Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args);
609*0b57cec5SDimitry Andric   } else {
610*0b57cec5SDimitry Andric     Value *Args[6] = {
611*0b57cec5SDimitry Andric         Ind->getTargetValue(),
612*0b57cec5SDimitry Andric         Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
613*0b57cec5SDimitry Andric         Builder.getInt32(Index),
614*0b57cec5SDimitry Andric         Builder.getInt64(MemOPSizeRangeStart),
615*0b57cec5SDimitry Andric         Builder.getInt64(MemOPSizeRangeLast),
616*0b57cec5SDimitry Andric         Builder.getInt64(MemOPSizeLarge == 0 ? INT64_MIN : MemOPSizeLarge)};
617*0b57cec5SDimitry Andric     Call =
618*0b57cec5SDimitry Andric         Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI, true), Args);
619*0b57cec5SDimitry Andric   }
620*0b57cec5SDimitry Andric   if (auto AK = TLI->getExtAttrForI32Param(false))
621*0b57cec5SDimitry Andric     Call->addParamAttr(2, AK);
622*0b57cec5SDimitry Andric   Ind->replaceAllUsesWith(Call);
623*0b57cec5SDimitry Andric   Ind->eraseFromParent();
624*0b57cec5SDimitry Andric }
625*0b57cec5SDimitry Andric 
626*0b57cec5SDimitry Andric void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
627*0b57cec5SDimitry Andric   GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
628*0b57cec5SDimitry Andric 
629*0b57cec5SDimitry Andric   IRBuilder<> Builder(Inc);
630*0b57cec5SDimitry Andric   uint64_t Index = Inc->getIndex()->getZExtValue();
631*0b57cec5SDimitry Andric   Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters->getValueType(),
632*0b57cec5SDimitry Andric                                                    Counters, 0, Index);
633*0b57cec5SDimitry Andric 
634*0b57cec5SDimitry Andric   if (Options.Atomic || AtomicCounterUpdateAll) {
635*0b57cec5SDimitry Andric     Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
636*0b57cec5SDimitry Andric                             AtomicOrdering::Monotonic);
637*0b57cec5SDimitry Andric   } else {
638*0b57cec5SDimitry Andric     Value *IncStep = Inc->getStep();
639*0b57cec5SDimitry Andric     Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
640*0b57cec5SDimitry Andric     auto *Count = Builder.CreateAdd(Load, Inc->getStep());
641*0b57cec5SDimitry Andric     auto *Store = Builder.CreateStore(Count, Addr);
642*0b57cec5SDimitry Andric     if (isCounterPromotionEnabled())
643*0b57cec5SDimitry Andric       PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
644*0b57cec5SDimitry Andric   }
645*0b57cec5SDimitry Andric   Inc->eraseFromParent();
646*0b57cec5SDimitry Andric }
647*0b57cec5SDimitry Andric 
648*0b57cec5SDimitry Andric void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
649*0b57cec5SDimitry Andric   ConstantArray *Names =
650*0b57cec5SDimitry Andric       cast<ConstantArray>(CoverageNamesVar->getInitializer());
651*0b57cec5SDimitry Andric   for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
652*0b57cec5SDimitry Andric     Constant *NC = Names->getOperand(I);
653*0b57cec5SDimitry Andric     Value *V = NC->stripPointerCasts();
654*0b57cec5SDimitry Andric     assert(isa<GlobalVariable>(V) && "Missing reference to function name");
655*0b57cec5SDimitry Andric     GlobalVariable *Name = cast<GlobalVariable>(V);
656*0b57cec5SDimitry Andric 
657*0b57cec5SDimitry Andric     Name->setLinkage(GlobalValue::PrivateLinkage);
658*0b57cec5SDimitry Andric     ReferencedNames.push_back(Name);
659*0b57cec5SDimitry Andric     NC->dropAllReferences();
660*0b57cec5SDimitry Andric   }
661*0b57cec5SDimitry Andric   CoverageNamesVar->eraseFromParent();
662*0b57cec5SDimitry Andric }
663*0b57cec5SDimitry Andric 
664*0b57cec5SDimitry Andric /// Get the name of a profiling variable for a particular function.
665*0b57cec5SDimitry Andric static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
666*0b57cec5SDimitry Andric   StringRef NamePrefix = getInstrProfNameVarPrefix();
667*0b57cec5SDimitry Andric   StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
668*0b57cec5SDimitry Andric   Function *F = Inc->getParent()->getParent();
669*0b57cec5SDimitry Andric   Module *M = F->getParent();
670*0b57cec5SDimitry Andric   if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
671*0b57cec5SDimitry Andric       !canRenameComdatFunc(*F))
672*0b57cec5SDimitry Andric     return (Prefix + Name).str();
673*0b57cec5SDimitry Andric   uint64_t FuncHash = Inc->getHash()->getZExtValue();
674*0b57cec5SDimitry Andric   SmallVector<char, 24> HashPostfix;
675*0b57cec5SDimitry Andric   if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
676*0b57cec5SDimitry Andric     return (Prefix + Name).str();
677*0b57cec5SDimitry Andric   return (Prefix + Name + "." + Twine(FuncHash)).str();
678*0b57cec5SDimitry Andric }
679*0b57cec5SDimitry Andric 
680*0b57cec5SDimitry Andric static inline bool shouldRecordFunctionAddr(Function *F) {
681*0b57cec5SDimitry Andric   // Check the linkage
682*0b57cec5SDimitry Andric   bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
683*0b57cec5SDimitry Andric   if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
684*0b57cec5SDimitry Andric       !HasAvailableExternallyLinkage)
685*0b57cec5SDimitry Andric     return true;
686*0b57cec5SDimitry Andric 
687*0b57cec5SDimitry Andric   // A function marked 'alwaysinline' with available_externally linkage can't
688*0b57cec5SDimitry Andric   // have its address taken. Doing so would create an undefined external ref to
689*0b57cec5SDimitry Andric   // the function, which would fail to link.
690*0b57cec5SDimitry Andric   if (HasAvailableExternallyLinkage &&
691*0b57cec5SDimitry Andric       F->hasFnAttribute(Attribute::AlwaysInline))
692*0b57cec5SDimitry Andric     return false;
693*0b57cec5SDimitry Andric 
694*0b57cec5SDimitry Andric   // Prohibit function address recording if the function is both internal and
695*0b57cec5SDimitry Andric   // COMDAT. This avoids the profile data variable referencing internal symbols
696*0b57cec5SDimitry Andric   // in COMDAT.
697*0b57cec5SDimitry Andric   if (F->hasLocalLinkage() && F->hasComdat())
698*0b57cec5SDimitry Andric     return false;
699*0b57cec5SDimitry Andric 
700*0b57cec5SDimitry Andric   // Check uses of this function for other than direct calls or invokes to it.
701*0b57cec5SDimitry Andric   // Inline virtual functions have linkeOnceODR linkage. When a key method
702*0b57cec5SDimitry Andric   // exists, the vtable will only be emitted in the TU where the key method
703*0b57cec5SDimitry Andric   // is defined. In a TU where vtable is not available, the function won't
704*0b57cec5SDimitry Andric   // be 'addresstaken'. If its address is not recorded here, the profile data
705*0b57cec5SDimitry Andric   // with missing address may be picked by the linker leading  to missing
706*0b57cec5SDimitry Andric   // indirect call target info.
707*0b57cec5SDimitry Andric   return F->hasAddressTaken() || F->hasLinkOnceLinkage();
708*0b57cec5SDimitry Andric }
709*0b57cec5SDimitry Andric 
710*0b57cec5SDimitry Andric static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT) {
711*0b57cec5SDimitry Andric   // Don't do this for Darwin.  compiler-rt uses linker magic.
712*0b57cec5SDimitry Andric   if (TT.isOSDarwin())
713*0b57cec5SDimitry Andric     return false;
714*0b57cec5SDimitry Andric   // Use linker script magic to get data/cnts/name start/end.
715*0b57cec5SDimitry Andric   if (TT.isOSLinux() || TT.isOSFreeBSD() || TT.isOSNetBSD() ||
716*0b57cec5SDimitry Andric       TT.isOSSolaris() || TT.isOSFuchsia() || TT.isPS4CPU() ||
717*0b57cec5SDimitry Andric       TT.isOSWindows())
718*0b57cec5SDimitry Andric     return false;
719*0b57cec5SDimitry Andric 
720*0b57cec5SDimitry Andric   return true;
721*0b57cec5SDimitry Andric }
722*0b57cec5SDimitry Andric 
723*0b57cec5SDimitry Andric GlobalVariable *
724*0b57cec5SDimitry Andric InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
725*0b57cec5SDimitry Andric   GlobalVariable *NamePtr = Inc->getName();
726*0b57cec5SDimitry Andric   auto It = ProfileDataMap.find(NamePtr);
727*0b57cec5SDimitry Andric   PerFunctionProfileData PD;
728*0b57cec5SDimitry Andric   if (It != ProfileDataMap.end()) {
729*0b57cec5SDimitry Andric     if (It->second.RegionCounters)
730*0b57cec5SDimitry Andric       return It->second.RegionCounters;
731*0b57cec5SDimitry Andric     PD = It->second;
732*0b57cec5SDimitry Andric   }
733*0b57cec5SDimitry Andric 
734*0b57cec5SDimitry Andric   // Match the linkage and visibility of the name global, except on COFF, where
735*0b57cec5SDimitry Andric   // the linkage must be local and consequentially the visibility must be
736*0b57cec5SDimitry Andric   // default.
737*0b57cec5SDimitry Andric   Function *Fn = Inc->getParent()->getParent();
738*0b57cec5SDimitry Andric   GlobalValue::LinkageTypes Linkage = NamePtr->getLinkage();
739*0b57cec5SDimitry Andric   GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
740*0b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF()) {
741*0b57cec5SDimitry Andric     Linkage = GlobalValue::InternalLinkage;
742*0b57cec5SDimitry Andric     Visibility = GlobalValue::DefaultVisibility;
743*0b57cec5SDimitry Andric   }
744*0b57cec5SDimitry Andric 
745*0b57cec5SDimitry Andric   // Move the name variable to the right section. Place them in a COMDAT group
746*0b57cec5SDimitry Andric   // if the associated function is a COMDAT. This will make sure that only one
747*0b57cec5SDimitry Andric   // copy of counters of the COMDAT function will be emitted after linking. Keep
748*0b57cec5SDimitry Andric   // in mind that this pass may run before the inliner, so we need to create a
749*0b57cec5SDimitry Andric   // new comdat group for the counters and profiling data. If we use the comdat
750*0b57cec5SDimitry Andric   // of the parent function, that will result in relocations against discarded
751*0b57cec5SDimitry Andric   // sections.
752*0b57cec5SDimitry Andric   Comdat *Cmdt = nullptr;
753*0b57cec5SDimitry Andric   GlobalValue::LinkageTypes CounterLinkage = Linkage;
754*0b57cec5SDimitry Andric   if (needsComdatForCounter(*Fn, *M)) {
755*0b57cec5SDimitry Andric     StringRef CmdtPrefix = getInstrProfComdatPrefix();
756*0b57cec5SDimitry Andric     if (TT.isOSBinFormatCOFF()) {
757*0b57cec5SDimitry Andric       // For COFF, the comdat group name must be the name of a symbol in the
758*0b57cec5SDimitry Andric       // group. Use the counter variable name, and upgrade its linkage to
759*0b57cec5SDimitry Andric       // something externally visible, like linkonce_odr.
760*0b57cec5SDimitry Andric       CmdtPrefix = getInstrProfCountersVarPrefix();
761*0b57cec5SDimitry Andric       CounterLinkage = GlobalValue::LinkOnceODRLinkage;
762*0b57cec5SDimitry Andric     }
763*0b57cec5SDimitry Andric     Cmdt = M->getOrInsertComdat(getVarName(Inc, CmdtPrefix));
764*0b57cec5SDimitry Andric   }
765*0b57cec5SDimitry Andric 
766*0b57cec5SDimitry Andric   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
767*0b57cec5SDimitry Andric   LLVMContext &Ctx = M->getContext();
768*0b57cec5SDimitry Andric   ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
769*0b57cec5SDimitry Andric 
770*0b57cec5SDimitry Andric   // Create the counters variable.
771*0b57cec5SDimitry Andric   auto *CounterPtr =
772*0b57cec5SDimitry Andric       new GlobalVariable(*M, CounterTy, false, Linkage,
773*0b57cec5SDimitry Andric                          Constant::getNullValue(CounterTy),
774*0b57cec5SDimitry Andric                          getVarName(Inc, getInstrProfCountersVarPrefix()));
775*0b57cec5SDimitry Andric   CounterPtr->setVisibility(Visibility);
776*0b57cec5SDimitry Andric   CounterPtr->setSection(
777*0b57cec5SDimitry Andric       getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
778*0b57cec5SDimitry Andric   CounterPtr->setAlignment(8);
779*0b57cec5SDimitry Andric   CounterPtr->setComdat(Cmdt);
780*0b57cec5SDimitry Andric   CounterPtr->setLinkage(CounterLinkage);
781*0b57cec5SDimitry Andric 
782*0b57cec5SDimitry Andric   auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
783*0b57cec5SDimitry Andric   // Allocate statically the array of pointers to value profile nodes for
784*0b57cec5SDimitry Andric   // the current function.
785*0b57cec5SDimitry Andric   Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
786*0b57cec5SDimitry Andric   if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(TT)) {
787*0b57cec5SDimitry Andric     uint64_t NS = 0;
788*0b57cec5SDimitry Andric     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
789*0b57cec5SDimitry Andric       NS += PD.NumValueSites[Kind];
790*0b57cec5SDimitry Andric     if (NS) {
791*0b57cec5SDimitry Andric       ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
792*0b57cec5SDimitry Andric 
793*0b57cec5SDimitry Andric       auto *ValuesVar =
794*0b57cec5SDimitry Andric           new GlobalVariable(*M, ValuesTy, false, Linkage,
795*0b57cec5SDimitry Andric                              Constant::getNullValue(ValuesTy),
796*0b57cec5SDimitry Andric                              getVarName(Inc, getInstrProfValuesVarPrefix()));
797*0b57cec5SDimitry Andric       ValuesVar->setVisibility(Visibility);
798*0b57cec5SDimitry Andric       ValuesVar->setSection(
799*0b57cec5SDimitry Andric           getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
800*0b57cec5SDimitry Andric       ValuesVar->setAlignment(8);
801*0b57cec5SDimitry Andric       ValuesVar->setComdat(Cmdt);
802*0b57cec5SDimitry Andric       ValuesPtrExpr =
803*0b57cec5SDimitry Andric           ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
804*0b57cec5SDimitry Andric     }
805*0b57cec5SDimitry Andric   }
806*0b57cec5SDimitry Andric 
807*0b57cec5SDimitry Andric   // Create data variable.
808*0b57cec5SDimitry Andric   auto *Int16Ty = Type::getInt16Ty(Ctx);
809*0b57cec5SDimitry Andric   auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
810*0b57cec5SDimitry Andric   Type *DataTypes[] = {
811*0b57cec5SDimitry Andric #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
812*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
813*0b57cec5SDimitry Andric   };
814*0b57cec5SDimitry Andric   auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
815*0b57cec5SDimitry Andric 
816*0b57cec5SDimitry Andric   Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
817*0b57cec5SDimitry Andric                                ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
818*0b57cec5SDimitry Andric                                : ConstantPointerNull::get(Int8PtrTy);
819*0b57cec5SDimitry Andric 
820*0b57cec5SDimitry Andric   Constant *Int16ArrayVals[IPVK_Last + 1];
821*0b57cec5SDimitry Andric   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
822*0b57cec5SDimitry Andric     Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
823*0b57cec5SDimitry Andric 
824*0b57cec5SDimitry Andric   Constant *DataVals[] = {
825*0b57cec5SDimitry Andric #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
826*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
827*0b57cec5SDimitry Andric   };
828*0b57cec5SDimitry Andric   auto *Data = new GlobalVariable(*M, DataTy, false, Linkage,
829*0b57cec5SDimitry Andric                                   ConstantStruct::get(DataTy, DataVals),
830*0b57cec5SDimitry Andric                                   getVarName(Inc, getInstrProfDataVarPrefix()));
831*0b57cec5SDimitry Andric   Data->setVisibility(Visibility);
832*0b57cec5SDimitry Andric   Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
833*0b57cec5SDimitry Andric   Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
834*0b57cec5SDimitry Andric   Data->setComdat(Cmdt);
835*0b57cec5SDimitry Andric 
836*0b57cec5SDimitry Andric   PD.RegionCounters = CounterPtr;
837*0b57cec5SDimitry Andric   PD.DataVar = Data;
838*0b57cec5SDimitry Andric   ProfileDataMap[NamePtr] = PD;
839*0b57cec5SDimitry Andric 
840*0b57cec5SDimitry Andric   // Mark the data variable as used so that it isn't stripped out.
841*0b57cec5SDimitry Andric   UsedVars.push_back(Data);
842*0b57cec5SDimitry Andric   // Now that the linkage set by the FE has been passed to the data and counter
843*0b57cec5SDimitry Andric   // variables, reset Name variable's linkage and visibility to private so that
844*0b57cec5SDimitry Andric   // it can be removed later by the compiler.
845*0b57cec5SDimitry Andric   NamePtr->setLinkage(GlobalValue::PrivateLinkage);
846*0b57cec5SDimitry Andric   // Collect the referenced names to be used by emitNameData.
847*0b57cec5SDimitry Andric   ReferencedNames.push_back(NamePtr);
848*0b57cec5SDimitry Andric 
849*0b57cec5SDimitry Andric   return CounterPtr;
850*0b57cec5SDimitry Andric }
851*0b57cec5SDimitry Andric 
852*0b57cec5SDimitry Andric void InstrProfiling::emitVNodes() {
853*0b57cec5SDimitry Andric   if (!ValueProfileStaticAlloc)
854*0b57cec5SDimitry Andric     return;
855*0b57cec5SDimitry Andric 
856*0b57cec5SDimitry Andric   // For now only support this on platforms that do
857*0b57cec5SDimitry Andric   // not require runtime registration to discover
858*0b57cec5SDimitry Andric   // named section start/end.
859*0b57cec5SDimitry Andric   if (needsRuntimeRegistrationOfSectionRange(TT))
860*0b57cec5SDimitry Andric     return;
861*0b57cec5SDimitry Andric 
862*0b57cec5SDimitry Andric   size_t TotalNS = 0;
863*0b57cec5SDimitry Andric   for (auto &PD : ProfileDataMap) {
864*0b57cec5SDimitry Andric     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
865*0b57cec5SDimitry Andric       TotalNS += PD.second.NumValueSites[Kind];
866*0b57cec5SDimitry Andric   }
867*0b57cec5SDimitry Andric 
868*0b57cec5SDimitry Andric   if (!TotalNS)
869*0b57cec5SDimitry Andric     return;
870*0b57cec5SDimitry Andric 
871*0b57cec5SDimitry Andric   uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
872*0b57cec5SDimitry Andric // Heuristic for small programs with very few total value sites.
873*0b57cec5SDimitry Andric // The default value of vp-counters-per-site is chosen based on
874*0b57cec5SDimitry Andric // the observation that large apps usually have a low percentage
875*0b57cec5SDimitry Andric // of value sites that actually have any profile data, and thus
876*0b57cec5SDimitry Andric // the average number of counters per site is low. For small
877*0b57cec5SDimitry Andric // apps with very few sites, this may not be true. Bump up the
878*0b57cec5SDimitry Andric // number of counters in this case.
879*0b57cec5SDimitry Andric #define INSTR_PROF_MIN_VAL_COUNTS 10
880*0b57cec5SDimitry Andric   if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
881*0b57cec5SDimitry Andric     NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
882*0b57cec5SDimitry Andric 
883*0b57cec5SDimitry Andric   auto &Ctx = M->getContext();
884*0b57cec5SDimitry Andric   Type *VNodeTypes[] = {
885*0b57cec5SDimitry Andric #define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
886*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
887*0b57cec5SDimitry Andric   };
888*0b57cec5SDimitry Andric   auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
889*0b57cec5SDimitry Andric 
890*0b57cec5SDimitry Andric   ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
891*0b57cec5SDimitry Andric   auto *VNodesVar = new GlobalVariable(
892*0b57cec5SDimitry Andric       *M, VNodesTy, false, GlobalValue::PrivateLinkage,
893*0b57cec5SDimitry Andric       Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
894*0b57cec5SDimitry Andric   VNodesVar->setSection(
895*0b57cec5SDimitry Andric       getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
896*0b57cec5SDimitry Andric   UsedVars.push_back(VNodesVar);
897*0b57cec5SDimitry Andric }
898*0b57cec5SDimitry Andric 
899*0b57cec5SDimitry Andric void InstrProfiling::emitNameData() {
900*0b57cec5SDimitry Andric   std::string UncompressedData;
901*0b57cec5SDimitry Andric 
902*0b57cec5SDimitry Andric   if (ReferencedNames.empty())
903*0b57cec5SDimitry Andric     return;
904*0b57cec5SDimitry Andric 
905*0b57cec5SDimitry Andric   std::string CompressedNameStr;
906*0b57cec5SDimitry Andric   if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
907*0b57cec5SDimitry Andric                                           DoNameCompression)) {
908*0b57cec5SDimitry Andric     report_fatal_error(toString(std::move(E)), false);
909*0b57cec5SDimitry Andric   }
910*0b57cec5SDimitry Andric 
911*0b57cec5SDimitry Andric   auto &Ctx = M->getContext();
912*0b57cec5SDimitry Andric   auto *NamesVal = ConstantDataArray::getString(
913*0b57cec5SDimitry Andric       Ctx, StringRef(CompressedNameStr), false);
914*0b57cec5SDimitry Andric   NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
915*0b57cec5SDimitry Andric                                 GlobalValue::PrivateLinkage, NamesVal,
916*0b57cec5SDimitry Andric                                 getInstrProfNamesVarName());
917*0b57cec5SDimitry Andric   NamesSize = CompressedNameStr.size();
918*0b57cec5SDimitry Andric   NamesVar->setSection(
919*0b57cec5SDimitry Andric       getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
920*0b57cec5SDimitry Andric   // On COFF, it's important to reduce the alignment down to 1 to prevent the
921*0b57cec5SDimitry Andric   // linker from inserting padding before the start of the names section or
922*0b57cec5SDimitry Andric   // between names entries.
923*0b57cec5SDimitry Andric   NamesVar->setAlignment(1);
924*0b57cec5SDimitry Andric   UsedVars.push_back(NamesVar);
925*0b57cec5SDimitry Andric 
926*0b57cec5SDimitry Andric   for (auto *NamePtr : ReferencedNames)
927*0b57cec5SDimitry Andric     NamePtr->eraseFromParent();
928*0b57cec5SDimitry Andric }
929*0b57cec5SDimitry Andric 
930*0b57cec5SDimitry Andric void InstrProfiling::emitRegistration() {
931*0b57cec5SDimitry Andric   if (!needsRuntimeRegistrationOfSectionRange(TT))
932*0b57cec5SDimitry Andric     return;
933*0b57cec5SDimitry Andric 
934*0b57cec5SDimitry Andric   // Construct the function.
935*0b57cec5SDimitry Andric   auto *VoidTy = Type::getVoidTy(M->getContext());
936*0b57cec5SDimitry Andric   auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
937*0b57cec5SDimitry Andric   auto *Int64Ty = Type::getInt64Ty(M->getContext());
938*0b57cec5SDimitry Andric   auto *RegisterFTy = FunctionType::get(VoidTy, false);
939*0b57cec5SDimitry Andric   auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
940*0b57cec5SDimitry Andric                                      getInstrProfRegFuncsName(), M);
941*0b57cec5SDimitry Andric   RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
942*0b57cec5SDimitry Andric   if (Options.NoRedZone)
943*0b57cec5SDimitry Andric     RegisterF->addFnAttr(Attribute::NoRedZone);
944*0b57cec5SDimitry Andric 
945*0b57cec5SDimitry Andric   auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
946*0b57cec5SDimitry Andric   auto *RuntimeRegisterF =
947*0b57cec5SDimitry Andric       Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
948*0b57cec5SDimitry Andric                        getInstrProfRegFuncName(), M);
949*0b57cec5SDimitry Andric 
950*0b57cec5SDimitry Andric   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
951*0b57cec5SDimitry Andric   for (Value *Data : UsedVars)
952*0b57cec5SDimitry Andric     if (Data != NamesVar && !isa<Function>(Data))
953*0b57cec5SDimitry Andric       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
954*0b57cec5SDimitry Andric 
955*0b57cec5SDimitry Andric   if (NamesVar) {
956*0b57cec5SDimitry Andric     Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
957*0b57cec5SDimitry Andric     auto *NamesRegisterTy =
958*0b57cec5SDimitry Andric         FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
959*0b57cec5SDimitry Andric     auto *NamesRegisterF =
960*0b57cec5SDimitry Andric         Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
961*0b57cec5SDimitry Andric                          getInstrProfNamesRegFuncName(), M);
962*0b57cec5SDimitry Andric     IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
963*0b57cec5SDimitry Andric                                     IRB.getInt64(NamesSize)});
964*0b57cec5SDimitry Andric   }
965*0b57cec5SDimitry Andric 
966*0b57cec5SDimitry Andric   IRB.CreateRetVoid();
967*0b57cec5SDimitry Andric }
968*0b57cec5SDimitry Andric 
969*0b57cec5SDimitry Andric bool InstrProfiling::emitRuntimeHook() {
970*0b57cec5SDimitry Andric   // We expect the linker to be invoked with -u<hook_var> flag for linux,
971*0b57cec5SDimitry Andric   // for which case there is no need to emit the user function.
972*0b57cec5SDimitry Andric   if (TT.isOSLinux())
973*0b57cec5SDimitry Andric     return false;
974*0b57cec5SDimitry Andric 
975*0b57cec5SDimitry Andric   // If the module's provided its own runtime, we don't need to do anything.
976*0b57cec5SDimitry Andric   if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
977*0b57cec5SDimitry Andric     return false;
978*0b57cec5SDimitry Andric 
979*0b57cec5SDimitry Andric   // Declare an external variable that will pull in the runtime initialization.
980*0b57cec5SDimitry Andric   auto *Int32Ty = Type::getInt32Ty(M->getContext());
981*0b57cec5SDimitry Andric   auto *Var =
982*0b57cec5SDimitry Andric       new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
983*0b57cec5SDimitry Andric                          nullptr, getInstrProfRuntimeHookVarName());
984*0b57cec5SDimitry Andric 
985*0b57cec5SDimitry Andric   // Make a function that uses it.
986*0b57cec5SDimitry Andric   auto *User = Function::Create(FunctionType::get(Int32Ty, false),
987*0b57cec5SDimitry Andric                                 GlobalValue::LinkOnceODRLinkage,
988*0b57cec5SDimitry Andric                                 getInstrProfRuntimeHookVarUseFuncName(), M);
989*0b57cec5SDimitry Andric   User->addFnAttr(Attribute::NoInline);
990*0b57cec5SDimitry Andric   if (Options.NoRedZone)
991*0b57cec5SDimitry Andric     User->addFnAttr(Attribute::NoRedZone);
992*0b57cec5SDimitry Andric   User->setVisibility(GlobalValue::HiddenVisibility);
993*0b57cec5SDimitry Andric   if (TT.supportsCOMDAT())
994*0b57cec5SDimitry Andric     User->setComdat(M->getOrInsertComdat(User->getName()));
995*0b57cec5SDimitry Andric 
996*0b57cec5SDimitry Andric   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
997*0b57cec5SDimitry Andric   auto *Load = IRB.CreateLoad(Int32Ty, Var);
998*0b57cec5SDimitry Andric   IRB.CreateRet(Load);
999*0b57cec5SDimitry Andric 
1000*0b57cec5SDimitry Andric   // Mark the user variable as used so that it isn't stripped out.
1001*0b57cec5SDimitry Andric   UsedVars.push_back(User);
1002*0b57cec5SDimitry Andric   return true;
1003*0b57cec5SDimitry Andric }
1004*0b57cec5SDimitry Andric 
1005*0b57cec5SDimitry Andric void InstrProfiling::emitUses() {
1006*0b57cec5SDimitry Andric   if (!UsedVars.empty())
1007*0b57cec5SDimitry Andric     appendToUsed(*M, UsedVars);
1008*0b57cec5SDimitry Andric }
1009*0b57cec5SDimitry Andric 
1010*0b57cec5SDimitry Andric void InstrProfiling::emitInitialization() {
1011*0b57cec5SDimitry Andric   // Create ProfileFileName variable. Don't don't this for the
1012*0b57cec5SDimitry Andric   // context-sensitive instrumentation lowering: This lowering is after
1013*0b57cec5SDimitry Andric   // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
1014*0b57cec5SDimitry Andric   // have already create the variable before LTO/ThinLTO linking.
1015*0b57cec5SDimitry Andric   if (!IsCS)
1016*0b57cec5SDimitry Andric     createProfileFileNameVar(*M, Options.InstrProfileOutput);
1017*0b57cec5SDimitry Andric   Function *RegisterF = M->getFunction(getInstrProfRegFuncsName());
1018*0b57cec5SDimitry Andric   if (!RegisterF)
1019*0b57cec5SDimitry Andric     return;
1020*0b57cec5SDimitry Andric 
1021*0b57cec5SDimitry Andric   // Create the initialization function.
1022*0b57cec5SDimitry Andric   auto *VoidTy = Type::getVoidTy(M->getContext());
1023*0b57cec5SDimitry Andric   auto *F = Function::Create(FunctionType::get(VoidTy, false),
1024*0b57cec5SDimitry Andric                              GlobalValue::InternalLinkage,
1025*0b57cec5SDimitry Andric                              getInstrProfInitFuncName(), M);
1026*0b57cec5SDimitry Andric   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1027*0b57cec5SDimitry Andric   F->addFnAttr(Attribute::NoInline);
1028*0b57cec5SDimitry Andric   if (Options.NoRedZone)
1029*0b57cec5SDimitry Andric     F->addFnAttr(Attribute::NoRedZone);
1030*0b57cec5SDimitry Andric 
1031*0b57cec5SDimitry Andric   // Add the basic block and the necessary calls.
1032*0b57cec5SDimitry Andric   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
1033*0b57cec5SDimitry Andric   IRB.CreateCall(RegisterF, {});
1034*0b57cec5SDimitry Andric   IRB.CreateRetVoid();
1035*0b57cec5SDimitry Andric 
1036*0b57cec5SDimitry Andric   appendToGlobalCtors(*M, F, 0);
1037*0b57cec5SDimitry Andric }
1038