1 //===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
2 //
3 //                      The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements GCOV-style profiling. When this pass is run it emits
11 // "gcno" files next to the existing source, and instruments the code that runs
12 // to records the edges between blocks that run and emit a complementary "gcda"
13 // file on exit.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/UniqueVector.h"
24 #include "llvm/IR/DebugInfo.h"
25 #include "llvm/IR/DebugLoc.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InstIterator.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Transforms/GCOVProfiler.h"
38 #include "llvm/Transforms/Instrumentation.h"
39 #include "llvm/Transforms/Utils/ModuleUtils.h"
40 #include <algorithm>
41 #include <memory>
42 #include <string>
43 #include <utility>
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "insert-gcov-profiling"
47 
48 static cl::opt<std::string>
49 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
50                    cl::ValueRequired);
51 static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
52                                                 cl::init(false), cl::Hidden);
53 
54 GCOVOptions GCOVOptions::getDefault() {
55   GCOVOptions Options;
56   Options.EmitNotes = true;
57   Options.EmitData = true;
58   Options.UseCfgChecksum = false;
59   Options.NoRedZone = false;
60   Options.FunctionNamesInData = true;
61   Options.ExitBlockBeforeBody = DefaultExitBlockBeforeBody;
62 
63   if (DefaultGCOVVersion.size() != 4) {
64     llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
65                              DefaultGCOVVersion);
66   }
67   memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
68   return Options;
69 }
70 
71 namespace {
72 class GCOVFunction;
73 
74 class GCOVProfiler {
75 public:
76   GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
77   GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {
78     assert((Options.EmitNotes || Options.EmitData) &&
79            "GCOVProfiler asked to do nothing?");
80     ReversedVersion[0] = Options.Version[3];
81     ReversedVersion[1] = Options.Version[2];
82     ReversedVersion[2] = Options.Version[1];
83     ReversedVersion[3] = Options.Version[0];
84     ReversedVersion[4] = '\0';
85   }
86   bool runOnModule(Module &M);
87 
88 private:
89   // Create the .gcno files for the Module based on DebugInfo.
90   void emitProfileNotes();
91 
92   // Modify the program to track transitions along edges and call into the
93   // profiling runtime to emit .gcda files when run.
94   bool emitProfileArcs();
95 
96   // Get pointers to the functions in the runtime library.
97   Constant *getStartFileFunc();
98   Constant *getIncrementIndirectCounterFunc();
99   Constant *getEmitFunctionFunc();
100   Constant *getEmitArcsFunc();
101   Constant *getSummaryInfoFunc();
102   Constant *getEndFileFunc();
103 
104   // Create or retrieve an i32 state value that is used to represent the
105   // pred block number for certain non-trivial edges.
106   GlobalVariable *getEdgeStateValue();
107 
108   // Produce a table of pointers to counters, by predecessor and successor
109   // block number.
110   GlobalVariable *buildEdgeLookupTable(Function *F, GlobalVariable *Counter,
111                                        const UniqueVector<BasicBlock *> &Preds,
112                                        const UniqueVector<BasicBlock *> &Succs);
113 
114   // Add the function to write out all our counters to the global destructor
115   // list.
116   Function *
117   insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
118   Function *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
119   void insertIndirectCounterIncrement();
120 
121   std::string mangleName(const DICompileUnit *CU, const char *NewStem);
122 
123   GCOVOptions Options;
124 
125   // Reversed, NUL-terminated copy of Options.Version.
126   char ReversedVersion[5];
127   // Checksum, produced by hash of EdgeDestinations
128   SmallVector<uint32_t, 4> FileChecksums;
129 
130   Module *M;
131   LLVMContext *Ctx;
132   SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
133 };
134 
135 class GCOVProfilerLegacyPass : public ModulePass {
136 public:
137   static char ID;
138   GCOVProfilerLegacyPass()
139       : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
140   GCOVProfilerLegacyPass(const GCOVOptions &Opts)
141       : ModulePass(ID), Profiler(Opts) {
142     initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
143   }
144   const char *getPassName() const override { return "GCOV Profiler"; }
145 
146   bool runOnModule(Module &M) override { return Profiler.runOnModule(M); }
147 
148 private:
149   GCOVProfiler Profiler;
150 };
151 }
152 
153 char GCOVProfilerLegacyPass::ID = 0;
154 INITIALIZE_PASS(GCOVProfilerLegacyPass, "insert-gcov-profiling",
155                 "Insert instrumentation for GCOV profiling", false, false)
156 
157 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
158   return new GCOVProfilerLegacyPass(Options);
159 }
160 
161 static StringRef getFunctionName(const DISubprogram *SP) {
162   if (!SP->getLinkageName().empty())
163     return SP->getLinkageName();
164   return SP->getName();
165 }
166 
167 namespace {
168   class GCOVRecord {
169    protected:
170     static const char *const LinesTag;
171     static const char *const FunctionTag;
172     static const char *const BlockTag;
173     static const char *const EdgeTag;
174 
175     GCOVRecord() = default;
176 
177     void writeBytes(const char *Bytes, int Size) {
178       os->write(Bytes, Size);
179     }
180 
181     void write(uint32_t i) {
182       writeBytes(reinterpret_cast<char*>(&i), 4);
183     }
184 
185     // Returns the length measured in 4-byte blocks that will be used to
186     // represent this string in a GCOV file
187     static unsigned lengthOfGCOVString(StringRef s) {
188       // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
189       // padding out to the next 4-byte word. The length is measured in 4-byte
190       // words including padding, not bytes of actual string.
191       return (s.size() / 4) + 1;
192     }
193 
194     void writeGCOVString(StringRef s) {
195       uint32_t Len = lengthOfGCOVString(s);
196       write(Len);
197       writeBytes(s.data(), s.size());
198 
199       // Write 1 to 4 bytes of NUL padding.
200       assert((unsigned)(4 - (s.size() % 4)) > 0);
201       assert((unsigned)(4 - (s.size() % 4)) <= 4);
202       writeBytes("\0\0\0\0", 4 - (s.size() % 4));
203     }
204 
205     raw_ostream *os;
206   };
207   const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
208   const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
209   const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
210   const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
211 
212   class GCOVFunction;
213   class GCOVBlock;
214 
215   // Constructed only by requesting it from a GCOVBlock, this object stores a
216   // list of line numbers and a single filename, representing lines that belong
217   // to the block.
218   class GCOVLines : public GCOVRecord {
219    public:
220     void addLine(uint32_t Line) {
221       assert(Line != 0 && "Line zero is not a valid real line number.");
222       Lines.push_back(Line);
223     }
224 
225     uint32_t length() const {
226       // Here 2 = 1 for string length + 1 for '0' id#.
227       return lengthOfGCOVString(Filename) + 2 + Lines.size();
228     }
229 
230     void writeOut() {
231       write(0);
232       writeGCOVString(Filename);
233       for (int i = 0, e = Lines.size(); i != e; ++i)
234         write(Lines[i]);
235     }
236 
237     GCOVLines(StringRef F, raw_ostream *os)
238       : Filename(F) {
239       this->os = os;
240     }
241 
242    private:
243     StringRef Filename;
244     SmallVector<uint32_t, 32> Lines;
245   };
246 
247 
248   // Represent a basic block in GCOV. Each block has a unique number in the
249   // function, number of lines belonging to each block, and a set of edges to
250   // other blocks.
251   class GCOVBlock : public GCOVRecord {
252    public:
253     GCOVLines &getFile(StringRef Filename) {
254       return LinesByFile.try_emplace(Filename, Filename, os).first->second;
255     }
256 
257     void addEdge(GCOVBlock &Successor) {
258       OutEdges.push_back(&Successor);
259     }
260 
261     void writeOut() {
262       uint32_t Len = 3;
263       SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
264       for (auto &I : LinesByFile) {
265         Len += I.second.length();
266         SortedLinesByFile.push_back(&I);
267       }
268 
269       writeBytes(LinesTag, 4);
270       write(Len);
271       write(Number);
272 
273       std::sort(
274           SortedLinesByFile.begin(), SortedLinesByFile.end(),
275           [](StringMapEntry<GCOVLines> *LHS, StringMapEntry<GCOVLines> *RHS) {
276             return LHS->getKey() < RHS->getKey();
277           });
278       for (auto &I : SortedLinesByFile)
279         I->getValue().writeOut();
280       write(0);
281       write(0);
282     }
283 
284     GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
285       // Only allow copy before edges and lines have been added. After that,
286       // there are inter-block pointers (eg: edges) that won't take kindly to
287       // blocks being copied or moved around.
288       assert(LinesByFile.empty());
289       assert(OutEdges.empty());
290     }
291 
292    private:
293     friend class GCOVFunction;
294 
295     GCOVBlock(uint32_t Number, raw_ostream *os)
296         : Number(Number) {
297       this->os = os;
298     }
299 
300     uint32_t Number;
301     StringMap<GCOVLines> LinesByFile;
302     SmallVector<GCOVBlock *, 4> OutEdges;
303   };
304 
305   // A function has a unique identifier, a checksum (we leave as zero) and a
306   // set of blocks and a map of edges between blocks. This is the only GCOV
307   // object users can construct, the blocks and lines will be rooted here.
308   class GCOVFunction : public GCOVRecord {
309    public:
310      GCOVFunction(const DISubprogram *SP, Function *F, raw_ostream *os,
311                   uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
312          : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
313            ReturnBlock(1, os) {
314       this->os = os;
315 
316       DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
317 
318       uint32_t i = 0;
319       for (auto &BB : *F) {
320         // Skip index 1 if it's assigned to the ReturnBlock.
321         if (i == 1 && ExitBlockBeforeBody)
322           ++i;
323         Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
324       }
325       if (!ExitBlockBeforeBody)
326         ReturnBlock.Number = i;
327 
328       std::string FunctionNameAndLine;
329       raw_string_ostream FNLOS(FunctionNameAndLine);
330       FNLOS << getFunctionName(SP) << SP->getLine();
331       FNLOS.flush();
332       FuncChecksum = hash_value(FunctionNameAndLine);
333     }
334 
335     GCOVBlock &getBlock(BasicBlock *BB) {
336       return Blocks.find(BB)->second;
337     }
338 
339     GCOVBlock &getReturnBlock() {
340       return ReturnBlock;
341     }
342 
343     std::string getEdgeDestinations() {
344       std::string EdgeDestinations;
345       raw_string_ostream EDOS(EdgeDestinations);
346       Function *F = Blocks.begin()->first->getParent();
347       for (BasicBlock &I : *F) {
348         GCOVBlock &Block = getBlock(&I);
349         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
350           EDOS << Block.OutEdges[i]->Number;
351       }
352       return EdgeDestinations;
353     }
354 
355     uint32_t getFuncChecksum() {
356       return FuncChecksum;
357     }
358 
359     void setCfgChecksum(uint32_t Checksum) {
360       CfgChecksum = Checksum;
361     }
362 
363     void writeOut() {
364       writeBytes(FunctionTag, 4);
365       uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
366                           1 + lengthOfGCOVString(SP->getFilename()) + 1;
367       if (UseCfgChecksum)
368         ++BlockLen;
369       write(BlockLen);
370       write(Ident);
371       write(FuncChecksum);
372       if (UseCfgChecksum)
373         write(CfgChecksum);
374       writeGCOVString(getFunctionName(SP));
375       writeGCOVString(SP->getFilename());
376       write(SP->getLine());
377 
378       // Emit count of blocks.
379       writeBytes(BlockTag, 4);
380       write(Blocks.size() + 1);
381       for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
382         write(0);  // No flags on our blocks.
383       }
384       DEBUG(dbgs() << Blocks.size() << " blocks.\n");
385 
386       // Emit edges between blocks.
387       if (Blocks.empty()) return;
388       Function *F = Blocks.begin()->first->getParent();
389       for (BasicBlock &I : *F) {
390         GCOVBlock &Block = getBlock(&I);
391         if (Block.OutEdges.empty()) continue;
392 
393         writeBytes(EdgeTag, 4);
394         write(Block.OutEdges.size() * 2 + 1);
395         write(Block.Number);
396         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
397           DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
398                        << "\n");
399           write(Block.OutEdges[i]->Number);
400           write(0);  // no flags
401         }
402       }
403 
404       // Emit lines for each block.
405       for (BasicBlock &I : *F)
406         getBlock(&I).writeOut();
407     }
408 
409    private:
410      const DISubprogram *SP;
411     uint32_t Ident;
412     uint32_t FuncChecksum;
413     bool UseCfgChecksum;
414     uint32_t CfgChecksum;
415     DenseMap<BasicBlock *, GCOVBlock> Blocks;
416     GCOVBlock ReturnBlock;
417   };
418 }
419 
420 std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
421                                      const char *NewStem) {
422   if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
423     for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
424       MDNode *N = GCov->getOperand(i);
425       if (N->getNumOperands() != 2) continue;
426       MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
427       MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
428       if (!GCovFile || !CompileUnit) continue;
429       if (CompileUnit == CU) {
430         SmallString<128> Filename = GCovFile->getString();
431         sys::path::replace_extension(Filename, NewStem);
432         return Filename.str();
433       }
434     }
435   }
436 
437   SmallString<128> Filename = CU->getFilename();
438   sys::path::replace_extension(Filename, NewStem);
439   StringRef FName = sys::path::filename(Filename);
440   SmallString<128> CurPath;
441   if (sys::fs::current_path(CurPath)) return FName;
442   sys::path::append(CurPath, FName);
443   return CurPath.str();
444 }
445 
446 bool GCOVProfiler::runOnModule(Module &M) {
447   this->M = &M;
448   Ctx = &M.getContext();
449 
450   if (Options.EmitNotes) emitProfileNotes();
451   if (Options.EmitData) return emitProfileArcs();
452   return false;
453 }
454 
455 PreservedAnalyses GCOVProfilerPass::run(Module &M,
456                                         AnalysisManager<Module> &AM) {
457 
458   GCOVProfiler Profiler(GCOVOpts);
459 
460   if (!Profiler.runOnModule(M))
461     return PreservedAnalyses::all();
462 
463   return PreservedAnalyses::none();
464 }
465 
466 static bool functionHasLines(Function &F) {
467   // Check whether this function actually has any source lines. Not only
468   // do these waste space, they also can crash gcov.
469   for (auto &BB : F) {
470     for (auto &I : BB) {
471       // Debug intrinsic locations correspond to the location of the
472       // declaration, not necessarily any statements or expressions.
473       if (isa<DbgInfoIntrinsic>(&I)) continue;
474 
475       const DebugLoc &Loc = I.getDebugLoc();
476       if (!Loc)
477         continue;
478 
479       // Artificial lines such as calls to the global constructors.
480       if (Loc.getLine() == 0) continue;
481 
482       return true;
483     }
484   }
485   return false;
486 }
487 
488 void GCOVProfiler::emitProfileNotes() {
489   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
490   if (!CU_Nodes) return;
491 
492   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
493     // Each compile unit gets its own .gcno file. This means that whether we run
494     // this pass over the original .o's as they're produced, or run it after
495     // LTO, we'll generate the same .gcno files.
496 
497     auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
498 
499     // Skip module skeleton (and module) CUs.
500     if (CU->getDWOId())
501       continue;
502 
503     std::error_code EC;
504     raw_fd_ostream out(mangleName(CU, "gcno"), EC, sys::fs::F_None);
505     std::string EdgeDestinations;
506 
507     unsigned FunctionIdent = 0;
508     for (auto &F : M->functions()) {
509       DISubprogram *SP = F.getSubprogram();
510       if (!SP) continue;
511       if (!functionHasLines(F)) continue;
512 
513       // gcov expects every function to start with an entry block that has a
514       // single successor, so split the entry block to make sure of that.
515       BasicBlock &EntryBlock = F.getEntryBlock();
516       BasicBlock::iterator It = EntryBlock.begin();
517       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
518         ++It;
519       EntryBlock.splitBasicBlock(It);
520 
521       Funcs.push_back(make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
522                                                 Options.UseCfgChecksum,
523                                                 Options.ExitBlockBeforeBody));
524       GCOVFunction &Func = *Funcs.back();
525 
526       for (auto &BB : F) {
527         GCOVBlock &Block = Func.getBlock(&BB);
528         TerminatorInst *TI = BB.getTerminator();
529         if (int successors = TI->getNumSuccessors()) {
530           for (int i = 0; i != successors; ++i) {
531             Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
532           }
533         } else if (isa<ReturnInst>(TI)) {
534           Block.addEdge(Func.getReturnBlock());
535         }
536 
537         uint32_t Line = 0;
538         for (auto &I : BB) {
539           // Debug intrinsic locations correspond to the location of the
540           // declaration, not necessarily any statements or expressions.
541           if (isa<DbgInfoIntrinsic>(&I)) continue;
542 
543           const DebugLoc &Loc = I.getDebugLoc();
544           if (!Loc)
545             continue;
546 
547           // Artificial lines such as calls to the global constructors.
548           if (Loc.getLine() == 0) continue;
549 
550           if (Line == Loc.getLine()) continue;
551           Line = Loc.getLine();
552           if (SP != getDISubprogram(Loc.getScope()))
553             continue;
554 
555           GCOVLines &Lines = Block.getFile(SP->getFilename());
556           Lines.addLine(Loc.getLine());
557         }
558       }
559       EdgeDestinations += Func.getEdgeDestinations();
560     }
561 
562     FileChecksums.push_back(hash_value(EdgeDestinations));
563     out.write("oncg", 4);
564     out.write(ReversedVersion, 4);
565     out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
566 
567     for (auto &Func : Funcs) {
568       Func->setCfgChecksum(FileChecksums.back());
569       Func->writeOut();
570     }
571 
572     out.write("\0\0\0\0\0\0\0\0", 8);  // EOF
573     out.close();
574   }
575 }
576 
577 bool GCOVProfiler::emitProfileArcs() {
578   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
579   if (!CU_Nodes) return false;
580 
581   bool Result = false;
582   bool InsertIndCounterIncrCode = false;
583   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
584     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
585     for (auto &F : M->functions()) {
586       DISubprogram *SP = F.getSubprogram();
587       if (!SP) continue;
588       if (!functionHasLines(F)) continue;
589       if (!Result) Result = true;
590       unsigned Edges = 0;
591       for (auto &BB : F) {
592         TerminatorInst *TI = BB.getTerminator();
593         if (isa<ReturnInst>(TI))
594           ++Edges;
595         else
596           Edges += TI->getNumSuccessors();
597       }
598 
599       ArrayType *CounterTy =
600         ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
601       GlobalVariable *Counters =
602         new GlobalVariable(*M, CounterTy, false,
603                            GlobalValue::InternalLinkage,
604                            Constant::getNullValue(CounterTy),
605                            "__llvm_gcov_ctr");
606       CountersBySP.push_back(std::make_pair(Counters, SP));
607 
608       UniqueVector<BasicBlock *> ComplexEdgePreds;
609       UniqueVector<BasicBlock *> ComplexEdgeSuccs;
610 
611       unsigned Edge = 0;
612       for (auto &BB : F) {
613         TerminatorInst *TI = BB.getTerminator();
614         int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
615         if (Successors) {
616           if (Successors == 1) {
617             IRBuilder<> Builder(&*BB.getFirstInsertionPt());
618             Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
619                                                                 Edge);
620             Value *Count = Builder.CreateLoad(Counter);
621             Count = Builder.CreateAdd(Count, Builder.getInt64(1));
622             Builder.CreateStore(Count, Counter);
623           } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
624             IRBuilder<> Builder(BI);
625             Value *Sel = Builder.CreateSelect(BI->getCondition(),
626                                               Builder.getInt64(Edge),
627                                               Builder.getInt64(Edge + 1));
628             Value *Counter = Builder.CreateInBoundsGEP(
629                 Counters->getValueType(), Counters, {Builder.getInt64(0), Sel});
630             Value *Count = Builder.CreateLoad(Counter);
631             Count = Builder.CreateAdd(Count, Builder.getInt64(1));
632             Builder.CreateStore(Count, Counter);
633           } else {
634             ComplexEdgePreds.insert(&BB);
635             for (int i = 0; i != Successors; ++i)
636               ComplexEdgeSuccs.insert(TI->getSuccessor(i));
637           }
638 
639           Edge += Successors;
640         }
641       }
642 
643       if (!ComplexEdgePreds.empty()) {
644         GlobalVariable *EdgeTable =
645           buildEdgeLookupTable(&F, Counters,
646                                ComplexEdgePreds, ComplexEdgeSuccs);
647         GlobalVariable *EdgeState = getEdgeStateValue();
648 
649         for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
650           IRBuilder<> Builder(&*ComplexEdgePreds[i + 1]->getFirstInsertionPt());
651           Builder.CreateStore(Builder.getInt32(i), EdgeState);
652         }
653 
654         for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
655           // Call runtime to perform increment.
656           IRBuilder<> Builder(&*ComplexEdgeSuccs[i + 1]->getFirstInsertionPt());
657           Value *CounterPtrArray =
658             Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
659                                                i * ComplexEdgePreds.size());
660 
661           // Build code to increment the counter.
662           InsertIndCounterIncrCode = true;
663           Builder.CreateCall(getIncrementIndirectCounterFunc(),
664                              {EdgeState, CounterPtrArray});
665         }
666       }
667     }
668 
669     Function *WriteoutF = insertCounterWriteout(CountersBySP);
670     Function *FlushF = insertFlush(CountersBySP);
671 
672     // Create a small bit of code that registers the "__llvm_gcov_writeout" to
673     // be executed at exit and the "__llvm_gcov_flush" function to be executed
674     // when "__gcov_flush" is called.
675     FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
676     Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
677                                    "__llvm_gcov_init", M);
678     F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
679     F->setLinkage(GlobalValue::InternalLinkage);
680     F->addFnAttr(Attribute::NoInline);
681     if (Options.NoRedZone)
682       F->addFnAttr(Attribute::NoRedZone);
683 
684     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
685     IRBuilder<> Builder(BB);
686 
687     FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
688     Type *Params[] = {
689       PointerType::get(FTy, 0),
690       PointerType::get(FTy, 0)
691     };
692     FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
693 
694     // Initialize the environment and register the local writeout and flush
695     // functions.
696     Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
697     Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
698     Builder.CreateRetVoid();
699 
700     appendToGlobalCtors(*M, F, 0);
701   }
702 
703   if (InsertIndCounterIncrCode)
704     insertIndirectCounterIncrement();
705 
706   return Result;
707 }
708 
709 // All edges with successors that aren't branches are "complex", because it
710 // requires complex logic to pick which counter to update.
711 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
712     Function *F,
713     GlobalVariable *Counters,
714     const UniqueVector<BasicBlock *> &Preds,
715     const UniqueVector<BasicBlock *> &Succs) {
716   // TODO: support invoke, threads. We rely on the fact that nothing can modify
717   // the whole-Module pred edge# between the time we set it and the time we next
718   // read it. Threads and invoke make this untrue.
719 
720   // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
721   size_t TableSize = Succs.size() * Preds.size();
722   Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
723   ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
724 
725   std::unique_ptr<Constant * []> EdgeTable(new Constant *[TableSize]);
726   Constant *NullValue = Constant::getNullValue(Int64PtrTy);
727   for (size_t i = 0; i != TableSize; ++i)
728     EdgeTable[i] = NullValue;
729 
730   unsigned Edge = 0;
731   for (BasicBlock &BB : *F) {
732     TerminatorInst *TI = BB.getTerminator();
733     int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
734     if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
735       for (int i = 0; i != Successors; ++i) {
736         BasicBlock *Succ = TI->getSuccessor(i);
737         IRBuilder<> Builder(Succ);
738         Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
739                                                             Edge + i);
740         EdgeTable[((Succs.idFor(Succ) - 1) * Preds.size()) +
741                   (Preds.idFor(&BB) - 1)] = cast<Constant>(Counter);
742       }
743     }
744     Edge += Successors;
745   }
746 
747   GlobalVariable *EdgeTableGV =
748       new GlobalVariable(
749           *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
750           ConstantArray::get(EdgeTableTy,
751                              makeArrayRef(&EdgeTable[0],TableSize)),
752           "__llvm_gcda_edge_table");
753   EdgeTableGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
754   return EdgeTableGV;
755 }
756 
757 Constant *GCOVProfiler::getStartFileFunc() {
758   Type *Args[] = {
759     Type::getInt8PtrTy(*Ctx),  // const char *orig_filename
760     Type::getInt8PtrTy(*Ctx),  // const char version[4]
761     Type::getInt32Ty(*Ctx),    // uint32_t checksum
762   };
763   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
764   return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
765 }
766 
767 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
768   Type *Int32Ty = Type::getInt32Ty(*Ctx);
769   Type *Int64Ty = Type::getInt64Ty(*Ctx);
770   Type *Args[] = {
771     Int32Ty->getPointerTo(),                // uint32_t *predecessor
772     Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
773   };
774   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
775   return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
776 }
777 
778 Constant *GCOVProfiler::getEmitFunctionFunc() {
779   Type *Args[] = {
780     Type::getInt32Ty(*Ctx),    // uint32_t ident
781     Type::getInt8PtrTy(*Ctx),  // const char *function_name
782     Type::getInt32Ty(*Ctx),    // uint32_t func_checksum
783     Type::getInt8Ty(*Ctx),     // uint8_t use_extra_checksum
784     Type::getInt32Ty(*Ctx),    // uint32_t cfg_checksum
785   };
786   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
787   return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
788 }
789 
790 Constant *GCOVProfiler::getEmitArcsFunc() {
791   Type *Args[] = {
792     Type::getInt32Ty(*Ctx),     // uint32_t num_counters
793     Type::getInt64PtrTy(*Ctx),  // uint64_t *counters
794   };
795   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
796   return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
797 }
798 
799 Constant *GCOVProfiler::getSummaryInfoFunc() {
800   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
801   return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
802 }
803 
804 Constant *GCOVProfiler::getEndFileFunc() {
805   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
806   return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
807 }
808 
809 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
810   GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
811   if (!GV) {
812     GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
813                             GlobalValue::InternalLinkage,
814                             ConstantInt::get(Type::getInt32Ty(*Ctx),
815                                              0xffffffff),
816                             "__llvm_gcov_global_state_pred");
817     GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
818   }
819   return GV;
820 }
821 
822 Function *GCOVProfiler::insertCounterWriteout(
823     ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
824   FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
825   Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
826   if (!WriteoutF)
827     WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
828                                  "__llvm_gcov_writeout", M);
829   WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
830   WriteoutF->addFnAttr(Attribute::NoInline);
831   if (Options.NoRedZone)
832     WriteoutF->addFnAttr(Attribute::NoRedZone);
833 
834   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
835   IRBuilder<> Builder(BB);
836 
837   Constant *StartFile = getStartFileFunc();
838   Constant *EmitFunction = getEmitFunctionFunc();
839   Constant *EmitArcs = getEmitArcsFunc();
840   Constant *SummaryInfo = getSummaryInfoFunc();
841   Constant *EndFile = getEndFileFunc();
842 
843   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
844   if (CU_Nodes) {
845     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
846       auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
847 
848       // Skip module skeleton (and module) CUs.
849       if (CU->getDWOId())
850         continue;
851 
852       std::string FilenameGcda = mangleName(CU, "gcda");
853       uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
854       Builder.CreateCall(StartFile,
855                          {Builder.CreateGlobalStringPtr(FilenameGcda),
856                           Builder.CreateGlobalStringPtr(ReversedVersion),
857                           Builder.getInt32(CfgChecksum)});
858       for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
859         auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
860         uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
861         Builder.CreateCall(
862             EmitFunction,
863             {Builder.getInt32(j),
864              Options.FunctionNamesInData
865                  ? Builder.CreateGlobalStringPtr(getFunctionName(SP))
866                  : Constant::getNullValue(Builder.getInt8PtrTy()),
867              Builder.getInt32(FuncChecksum),
868              Builder.getInt8(Options.UseCfgChecksum),
869              Builder.getInt32(CfgChecksum)});
870 
871         GlobalVariable *GV = CountersBySP[j].first;
872         unsigned Arcs =
873           cast<ArrayType>(GV->getValueType())->getNumElements();
874         Builder.CreateCall(EmitArcs, {Builder.getInt32(Arcs),
875                                       Builder.CreateConstGEP2_64(GV, 0, 0)});
876       }
877       Builder.CreateCall(SummaryInfo, {});
878       Builder.CreateCall(EndFile, {});
879     }
880   }
881 
882   Builder.CreateRetVoid();
883   return WriteoutF;
884 }
885 
886 void GCOVProfiler::insertIndirectCounterIncrement() {
887   Function *Fn =
888     cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
889   Fn->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
890   Fn->setLinkage(GlobalValue::InternalLinkage);
891   Fn->addFnAttr(Attribute::NoInline);
892   if (Options.NoRedZone)
893     Fn->addFnAttr(Attribute::NoRedZone);
894 
895   // Create basic blocks for function.
896   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
897   IRBuilder<> Builder(BB);
898 
899   BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
900   BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
901   BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
902 
903   // uint32_t pred = *predecessor;
904   // if (pred == 0xffffffff) return;
905   Argument *Arg = &*Fn->arg_begin();
906   Arg->setName("predecessor");
907   Value *Pred = Builder.CreateLoad(Arg, "pred");
908   Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
909   BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
910 
911   Builder.SetInsertPoint(PredNotNegOne);
912 
913   // uint64_t *counter = counters[pred];
914   // if (!counter) return;
915   Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
916   Arg = &*std::next(Fn->arg_begin());
917   Arg->setName("counters");
918   Value *GEP = Builder.CreateGEP(Type::getInt64PtrTy(*Ctx), Arg, ZExtPred);
919   Value *Counter = Builder.CreateLoad(GEP, "counter");
920   Cond = Builder.CreateICmpEQ(Counter,
921                               Constant::getNullValue(
922                                   Builder.getInt64Ty()->getPointerTo()));
923   Builder.CreateCondBr(Cond, Exit, CounterEnd);
924 
925   // ++*counter;
926   Builder.SetInsertPoint(CounterEnd);
927   Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
928                                  Builder.getInt64(1));
929   Builder.CreateStore(Add, Counter);
930   Builder.CreateBr(Exit);
931 
932   // Fill in the exit block.
933   Builder.SetInsertPoint(Exit);
934   Builder.CreateRetVoid();
935 }
936 
937 Function *GCOVProfiler::
938 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
939   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
940   Function *FlushF = M->getFunction("__llvm_gcov_flush");
941   if (!FlushF)
942     FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
943                               "__llvm_gcov_flush", M);
944   else
945     FlushF->setLinkage(GlobalValue::InternalLinkage);
946   FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
947   FlushF->addFnAttr(Attribute::NoInline);
948   if (Options.NoRedZone)
949     FlushF->addFnAttr(Attribute::NoRedZone);
950 
951   BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
952 
953   // Write out the current counters.
954   Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
955   assert(WriteoutF && "Need to create the writeout function first!");
956 
957   IRBuilder<> Builder(Entry);
958   Builder.CreateCall(WriteoutF, {});
959 
960   // Zero out the counters.
961   for (const auto &I : CountersBySP) {
962     GlobalVariable *GV = I.first;
963     Constant *Null = Constant::getNullValue(GV->getValueType());
964     Builder.CreateStore(Null, GV);
965   }
966 
967   Type *RetTy = FlushF->getReturnType();
968   if (RetTy == Type::getVoidTy(*Ctx))
969     Builder.CreateRetVoid();
970   else if (RetTy->isIntegerTy())
971     // Used if __llvm_gcov_flush was implicitly declared.
972     Builder.CreateRet(ConstantInt::get(RetTy, 0));
973   else
974     report_fatal_error("invalid return type for __llvm_gcov_flush");
975 
976   return FlushF;
977 }
978