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/Sequence.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/Analysis/EHPersonalities.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/IR/CFG.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DebugLoc.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InstIterator.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Instrumentation.h"
41 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
42 #include "llvm/Transforms/Utils/ModuleUtils.h"
43 #include <algorithm>
44 #include <memory>
45 #include <string>
46 #include <utility>
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "insert-gcov-profiling"
50 
51 static cl::opt<std::string>
52 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
53                    cl::ValueRequired);
54 static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
55                                                 cl::init(false), cl::Hidden);
56 
57 GCOVOptions GCOVOptions::getDefault() {
58   GCOVOptions Options;
59   Options.EmitNotes = true;
60   Options.EmitData = true;
61   Options.UseCfgChecksum = false;
62   Options.NoRedZone = false;
63   Options.FunctionNamesInData = true;
64   Options.ExitBlockBeforeBody = DefaultExitBlockBeforeBody;
65 
66   if (DefaultGCOVVersion.size() != 4) {
67     llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
68                              DefaultGCOVVersion);
69   }
70   memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
71   return Options;
72 }
73 
74 namespace {
75 class GCOVFunction;
76 
77 class GCOVProfiler {
78 public:
79   GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
80   GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {
81     assert((Options.EmitNotes || Options.EmitData) &&
82            "GCOVProfiler asked to do nothing?");
83     ReversedVersion[0] = Options.Version[3];
84     ReversedVersion[1] = Options.Version[2];
85     ReversedVersion[2] = Options.Version[1];
86     ReversedVersion[3] = Options.Version[0];
87     ReversedVersion[4] = '\0';
88   }
89   bool runOnModule(Module &M, const TargetLibraryInfo &TLI);
90 
91 private:
92   // Create the .gcno files for the Module based on DebugInfo.
93   void emitProfileNotes();
94 
95   // Modify the program to track transitions along edges and call into the
96   // profiling runtime to emit .gcda files when run.
97   bool emitProfileArcs();
98 
99   // Get pointers to the functions in the runtime library.
100   Constant *getStartFileFunc();
101   Constant *getEmitFunctionFunc();
102   Constant *getEmitArcsFunc();
103   Constant *getSummaryInfoFunc();
104   Constant *getEndFileFunc();
105 
106   // Add the function to write out all our counters to the global destructor
107   // list.
108   Function *
109   insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
110   Function *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
111 
112   enum class GCovFileType { GCNO, GCDA };
113   std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
114 
115   GCOVOptions Options;
116 
117   // Reversed, NUL-terminated copy of Options.Version.
118   char ReversedVersion[5];
119   // Checksum, produced by hash of EdgeDestinations
120   SmallVector<uint32_t, 4> FileChecksums;
121 
122   Module *M;
123   const TargetLibraryInfo *TLI;
124   LLVMContext *Ctx;
125   SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
126 };
127 
128 class GCOVProfilerLegacyPass : public ModulePass {
129 public:
130   static char ID;
131   GCOVProfilerLegacyPass()
132       : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
133   GCOVProfilerLegacyPass(const GCOVOptions &Opts)
134       : ModulePass(ID), Profiler(Opts) {
135     initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
136   }
137   StringRef getPassName() const override { return "GCOV Profiler"; }
138 
139   bool runOnModule(Module &M) override {
140     auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
141     return Profiler.runOnModule(M, TLI);
142   }
143 
144   void getAnalysisUsage(AnalysisUsage &AU) const override {
145     AU.addRequired<TargetLibraryInfoWrapperPass>();
146   }
147 
148 private:
149   GCOVProfiler Profiler;
150 };
151 }
152 
153 char GCOVProfilerLegacyPass::ID = 0;
154 INITIALIZE_PASS_BEGIN(
155     GCOVProfilerLegacyPass, "insert-gcov-profiling",
156     "Insert instrumentation for GCOV profiling", false, false)
157 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
158 INITIALIZE_PASS_END(
159     GCOVProfilerLegacyPass, "insert-gcov-profiling",
160     "Insert instrumentation for GCOV profiling", false, false)
161 
162 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
163   return new GCOVProfilerLegacyPass(Options);
164 }
165 
166 static StringRef getFunctionName(const DISubprogram *SP) {
167   if (!SP->getLinkageName().empty())
168     return SP->getLinkageName();
169   return SP->getName();
170 }
171 
172 namespace {
173   class GCOVRecord {
174    protected:
175     static const char *const LinesTag;
176     static const char *const FunctionTag;
177     static const char *const BlockTag;
178     static const char *const EdgeTag;
179 
180     GCOVRecord() = default;
181 
182     void writeBytes(const char *Bytes, int Size) {
183       os->write(Bytes, Size);
184     }
185 
186     void write(uint32_t i) {
187       writeBytes(reinterpret_cast<char*>(&i), 4);
188     }
189 
190     // Returns the length measured in 4-byte blocks that will be used to
191     // represent this string in a GCOV file
192     static unsigned lengthOfGCOVString(StringRef s) {
193       // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
194       // padding out to the next 4-byte word. The length is measured in 4-byte
195       // words including padding, not bytes of actual string.
196       return (s.size() / 4) + 1;
197     }
198 
199     void writeGCOVString(StringRef s) {
200       uint32_t Len = lengthOfGCOVString(s);
201       write(Len);
202       writeBytes(s.data(), s.size());
203 
204       // Write 1 to 4 bytes of NUL padding.
205       assert((unsigned)(4 - (s.size() % 4)) > 0);
206       assert((unsigned)(4 - (s.size() % 4)) <= 4);
207       writeBytes("\0\0\0\0", 4 - (s.size() % 4));
208     }
209 
210     raw_ostream *os;
211   };
212   const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
213   const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
214   const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
215   const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
216 
217   class GCOVFunction;
218   class GCOVBlock;
219 
220   // Constructed only by requesting it from a GCOVBlock, this object stores a
221   // list of line numbers and a single filename, representing lines that belong
222   // to the block.
223   class GCOVLines : public GCOVRecord {
224    public:
225     void addLine(uint32_t Line) {
226       assert(Line != 0 && "Line zero is not a valid real line number.");
227       Lines.push_back(Line);
228     }
229 
230     uint32_t length() const {
231       // Here 2 = 1 for string length + 1 for '0' id#.
232       return lengthOfGCOVString(Filename) + 2 + Lines.size();
233     }
234 
235     void writeOut() {
236       write(0);
237       writeGCOVString(Filename);
238       for (int i = 0, e = Lines.size(); i != e; ++i)
239         write(Lines[i]);
240     }
241 
242     GCOVLines(StringRef F, raw_ostream *os)
243       : Filename(F) {
244       this->os = os;
245     }
246 
247    private:
248     StringRef Filename;
249     SmallVector<uint32_t, 32> Lines;
250   };
251 
252 
253   // Represent a basic block in GCOV. Each block has a unique number in the
254   // function, number of lines belonging to each block, and a set of edges to
255   // other blocks.
256   class GCOVBlock : public GCOVRecord {
257    public:
258     GCOVLines &getFile(StringRef Filename) {
259       return LinesByFile.try_emplace(Filename, Filename, os).first->second;
260     }
261 
262     void addEdge(GCOVBlock &Successor) {
263       OutEdges.push_back(&Successor);
264     }
265 
266     void writeOut() {
267       uint32_t Len = 3;
268       SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
269       for (auto &I : LinesByFile) {
270         Len += I.second.length();
271         SortedLinesByFile.push_back(&I);
272       }
273 
274       writeBytes(LinesTag, 4);
275       write(Len);
276       write(Number);
277 
278       llvm::sort(
279           SortedLinesByFile.begin(), SortedLinesByFile.end(),
280           [](StringMapEntry<GCOVLines> *LHS, StringMapEntry<GCOVLines> *RHS) {
281             return LHS->getKey() < RHS->getKey();
282           });
283       for (auto &I : SortedLinesByFile)
284         I->getValue().writeOut();
285       write(0);
286       write(0);
287     }
288 
289     GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
290       // Only allow copy before edges and lines have been added. After that,
291       // there are inter-block pointers (eg: edges) that won't take kindly to
292       // blocks being copied or moved around.
293       assert(LinesByFile.empty());
294       assert(OutEdges.empty());
295     }
296 
297    private:
298     friend class GCOVFunction;
299 
300     GCOVBlock(uint32_t Number, raw_ostream *os)
301         : Number(Number) {
302       this->os = os;
303     }
304 
305     uint32_t Number;
306     StringMap<GCOVLines> LinesByFile;
307     SmallVector<GCOVBlock *, 4> OutEdges;
308   };
309 
310   // A function has a unique identifier, a checksum (we leave as zero) and a
311   // set of blocks and a map of edges between blocks. This is the only GCOV
312   // object users can construct, the blocks and lines will be rooted here.
313   class GCOVFunction : public GCOVRecord {
314    public:
315      GCOVFunction(const DISubprogram *SP, Function *F, raw_ostream *os,
316                   uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
317          : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
318            ReturnBlock(1, os) {
319       this->os = os;
320 
321       LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
322 
323       uint32_t i = 0;
324       for (auto &BB : *F) {
325         // Skip index 1 if it's assigned to the ReturnBlock.
326         if (i == 1 && ExitBlockBeforeBody)
327           ++i;
328         Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
329       }
330       if (!ExitBlockBeforeBody)
331         ReturnBlock.Number = i;
332 
333       std::string FunctionNameAndLine;
334       raw_string_ostream FNLOS(FunctionNameAndLine);
335       FNLOS << getFunctionName(SP) << SP->getLine();
336       FNLOS.flush();
337       FuncChecksum = hash_value(FunctionNameAndLine);
338     }
339 
340     GCOVBlock &getBlock(BasicBlock *BB) {
341       return Blocks.find(BB)->second;
342     }
343 
344     GCOVBlock &getReturnBlock() {
345       return ReturnBlock;
346     }
347 
348     std::string getEdgeDestinations() {
349       std::string EdgeDestinations;
350       raw_string_ostream EDOS(EdgeDestinations);
351       Function *F = Blocks.begin()->first->getParent();
352       for (BasicBlock &I : *F) {
353         GCOVBlock &Block = getBlock(&I);
354         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
355           EDOS << Block.OutEdges[i]->Number;
356       }
357       return EdgeDestinations;
358     }
359 
360     uint32_t getFuncChecksum() {
361       return FuncChecksum;
362     }
363 
364     void setCfgChecksum(uint32_t Checksum) {
365       CfgChecksum = Checksum;
366     }
367 
368     void writeOut() {
369       writeBytes(FunctionTag, 4);
370       uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
371                           1 + lengthOfGCOVString(SP->getFilename()) + 1;
372       if (UseCfgChecksum)
373         ++BlockLen;
374       write(BlockLen);
375       write(Ident);
376       write(FuncChecksum);
377       if (UseCfgChecksum)
378         write(CfgChecksum);
379       writeGCOVString(getFunctionName(SP));
380       writeGCOVString(SP->getFilename());
381       write(SP->getLine());
382 
383       // Emit count of blocks.
384       writeBytes(BlockTag, 4);
385       write(Blocks.size() + 1);
386       for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
387         write(0);  // No flags on our blocks.
388       }
389       LLVM_DEBUG(dbgs() << Blocks.size() << " blocks.\n");
390 
391       // Emit edges between blocks.
392       if (Blocks.empty()) return;
393       Function *F = Blocks.begin()->first->getParent();
394       for (BasicBlock &I : *F) {
395         GCOVBlock &Block = getBlock(&I);
396         if (Block.OutEdges.empty()) continue;
397 
398         writeBytes(EdgeTag, 4);
399         write(Block.OutEdges.size() * 2 + 1);
400         write(Block.Number);
401         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
402           LLVM_DEBUG(dbgs() << Block.Number << " -> "
403                             << Block.OutEdges[i]->Number << "\n");
404           write(Block.OutEdges[i]->Number);
405           write(0);  // no flags
406         }
407       }
408 
409       // Emit lines for each block.
410       for (BasicBlock &I : *F)
411         getBlock(&I).writeOut();
412     }
413 
414    private:
415      const DISubprogram *SP;
416     uint32_t Ident;
417     uint32_t FuncChecksum;
418     bool UseCfgChecksum;
419     uint32_t CfgChecksum;
420     DenseMap<BasicBlock *, GCOVBlock> Blocks;
421     GCOVBlock ReturnBlock;
422   };
423 }
424 
425 std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
426                                      GCovFileType OutputType) {
427   bool Notes = OutputType == GCovFileType::GCNO;
428 
429   if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
430     for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
431       MDNode *N = GCov->getOperand(i);
432       bool ThreeElement = N->getNumOperands() == 3;
433       if (!ThreeElement && N->getNumOperands() != 2)
434         continue;
435       if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
436         continue;
437 
438       if (ThreeElement) {
439         // These nodes have no mangling to apply, it's stored mangled in the
440         // bitcode.
441         MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
442         MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
443         if (!NotesFile || !DataFile)
444           continue;
445         return Notes ? NotesFile->getString() : DataFile->getString();
446       }
447 
448       MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
449       if (!GCovFile)
450         continue;
451 
452       SmallString<128> Filename = GCovFile->getString();
453       sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
454       return Filename.str();
455     }
456   }
457 
458   SmallString<128> Filename = CU->getFilename();
459   sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
460   StringRef FName = sys::path::filename(Filename);
461   SmallString<128> CurPath;
462   if (sys::fs::current_path(CurPath)) return FName;
463   sys::path::append(CurPath, FName);
464   return CurPath.str();
465 }
466 
467 bool GCOVProfiler::runOnModule(Module &M, const TargetLibraryInfo &TLI) {
468   this->M = &M;
469   this->TLI = &TLI;
470   Ctx = &M.getContext();
471 
472   if (Options.EmitNotes) emitProfileNotes();
473   if (Options.EmitData) return emitProfileArcs();
474   return false;
475 }
476 
477 PreservedAnalyses GCOVProfilerPass::run(Module &M,
478                                         ModuleAnalysisManager &AM) {
479 
480   GCOVProfiler Profiler(GCOVOpts);
481 
482   auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
483   if (!Profiler.runOnModule(M, TLI))
484     return PreservedAnalyses::all();
485 
486   return PreservedAnalyses::none();
487 }
488 
489 static bool functionHasLines(Function &F) {
490   // Check whether this function actually has any source lines. Not only
491   // do these waste space, they also can crash gcov.
492   for (auto &BB : F) {
493     for (auto &I : BB) {
494       // Debug intrinsic locations correspond to the location of the
495       // declaration, not necessarily any statements or expressions.
496       if (isa<DbgInfoIntrinsic>(&I)) continue;
497 
498       const DebugLoc &Loc = I.getDebugLoc();
499       if (!Loc)
500         continue;
501 
502       // Artificial lines such as calls to the global constructors.
503       if (Loc.getLine() == 0) continue;
504 
505       return true;
506     }
507   }
508   return false;
509 }
510 
511 static bool isUsingScopeBasedEH(Function &F) {
512   if (!F.hasPersonalityFn()) return false;
513 
514   EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
515   return isScopedEHPersonality(Personality);
516 }
517 
518 static bool shouldKeepInEntry(BasicBlock::iterator It) {
519 	if (isa<AllocaInst>(*It)) return true;
520 	if (isa<DbgInfoIntrinsic>(*It)) return true;
521 	if (auto *II = dyn_cast<IntrinsicInst>(It)) {
522 		if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
523 	}
524 
525 	return false;
526 }
527 
528 void GCOVProfiler::emitProfileNotes() {
529   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
530   if (!CU_Nodes) return;
531 
532   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
533     // Each compile unit gets its own .gcno file. This means that whether we run
534     // this pass over the original .o's as they're produced, or run it after
535     // LTO, we'll generate the same .gcno files.
536 
537     auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
538 
539     // Skip module skeleton (and module) CUs.
540     if (CU->getDWOId())
541       continue;
542 
543     std::error_code EC;
544     raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC, sys::fs::F_None);
545     if (EC) {
546       Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
547                      EC.message());
548       continue;
549     }
550 
551     std::string EdgeDestinations;
552 
553     unsigned FunctionIdent = 0;
554     for (auto &F : M->functions()) {
555       DISubprogram *SP = F.getSubprogram();
556       if (!SP) continue;
557       if (!functionHasLines(F)) continue;
558       // TODO: Functions using scope-based EH are currently not supported.
559       if (isUsingScopeBasedEH(F)) continue;
560 
561       // gcov expects every function to start with an entry block that has a
562       // single successor, so split the entry block to make sure of that.
563       BasicBlock &EntryBlock = F.getEntryBlock();
564       BasicBlock::iterator It = EntryBlock.begin();
565       while (shouldKeepInEntry(It))
566         ++It;
567       EntryBlock.splitBasicBlock(It);
568 
569       Funcs.push_back(make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
570                                                 Options.UseCfgChecksum,
571                                                 Options.ExitBlockBeforeBody));
572       GCOVFunction &Func = *Funcs.back();
573 
574       for (auto &BB : F) {
575         GCOVBlock &Block = Func.getBlock(&BB);
576         TerminatorInst *TI = BB.getTerminator();
577         if (int successors = TI->getNumSuccessors()) {
578           for (int i = 0; i != successors; ++i) {
579             Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
580           }
581         } else if (isa<ReturnInst>(TI)) {
582           Block.addEdge(Func.getReturnBlock());
583         }
584 
585         uint32_t Line = 0;
586         for (auto &I : BB) {
587           // Debug intrinsic locations correspond to the location of the
588           // declaration, not necessarily any statements or expressions.
589           if (isa<DbgInfoIntrinsic>(&I)) continue;
590 
591           const DebugLoc &Loc = I.getDebugLoc();
592           if (!Loc)
593             continue;
594 
595           // Artificial lines such as calls to the global constructors.
596           if (Loc.getLine() == 0 || Loc.isImplicitCode())
597             continue;
598 
599           if (Line == Loc.getLine()) continue;
600           Line = Loc.getLine();
601           if (SP != getDISubprogram(Loc.getScope()))
602             continue;
603 
604           GCOVLines &Lines = Block.getFile(SP->getFilename());
605           Lines.addLine(Loc.getLine());
606         }
607       }
608       EdgeDestinations += Func.getEdgeDestinations();
609     }
610 
611     FileChecksums.push_back(hash_value(EdgeDestinations));
612     out.write("oncg", 4);
613     out.write(ReversedVersion, 4);
614     out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
615 
616     for (auto &Func : Funcs) {
617       Func->setCfgChecksum(FileChecksums.back());
618       Func->writeOut();
619     }
620 
621     out.write("\0\0\0\0\0\0\0\0", 8);  // EOF
622     out.close();
623   }
624 }
625 
626 bool GCOVProfiler::emitProfileArcs() {
627   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
628   if (!CU_Nodes) return false;
629 
630   bool Result = false;
631   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
632     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
633     for (auto &F : M->functions()) {
634       DISubprogram *SP = F.getSubprogram();
635       if (!SP) continue;
636       if (!functionHasLines(F)) continue;
637       // TODO: Functions using scope-based EH are currently not supported.
638       if (isUsingScopeBasedEH(F)) continue;
639       if (!Result) Result = true;
640 
641       DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter;
642       unsigned Edges = 0;
643       for (auto &BB : F) {
644         TerminatorInst *TI = BB.getTerminator();
645         if (isa<ReturnInst>(TI)) {
646           EdgeToCounter[{&BB, nullptr}] = Edges++;
647         } else {
648           for (BasicBlock *Succ : successors(TI)) {
649             EdgeToCounter[{&BB, Succ}] = Edges++;
650           }
651         }
652       }
653 
654       ArrayType *CounterTy =
655         ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
656       GlobalVariable *Counters =
657         new GlobalVariable(*M, CounterTy, false,
658                            GlobalValue::InternalLinkage,
659                            Constant::getNullValue(CounterTy),
660                            "__llvm_gcov_ctr");
661       CountersBySP.push_back(std::make_pair(Counters, SP));
662 
663       // If a BB has several predecessors, use a PHINode to select
664       // the correct counter.
665       for (auto &BB : F) {
666         const unsigned EdgeCount =
667             std::distance(pred_begin(&BB), pred_end(&BB));
668         if (EdgeCount) {
669           // The phi node must be at the begin of the BB.
670           IRBuilder<> BuilderForPhi(&*BB.begin());
671           Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
672           PHINode *Phi = BuilderForPhi.CreatePHI(Int64PtrTy, EdgeCount);
673           for (BasicBlock *Pred : predecessors(&BB)) {
674             auto It = EdgeToCounter.find({Pred, &BB});
675             assert(It != EdgeToCounter.end());
676             const unsigned Edge = It->second;
677             Value *EdgeCounter =
678                 BuilderForPhi.CreateConstInBoundsGEP2_64(Counters, 0, Edge);
679             Phi->addIncoming(EdgeCounter, Pred);
680           }
681 
682           // Skip phis, landingpads.
683           IRBuilder<> Builder(&*BB.getFirstInsertionPt());
684           Value *Count = Builder.CreateLoad(Phi);
685           Count = Builder.CreateAdd(Count, Builder.getInt64(1));
686           Builder.CreateStore(Count, Phi);
687 
688           TerminatorInst *TI = BB.getTerminator();
689           if (isa<ReturnInst>(TI)) {
690             auto It = EdgeToCounter.find({&BB, nullptr});
691             assert(It != EdgeToCounter.end());
692             const unsigned Edge = It->second;
693             Value *Counter =
694                 Builder.CreateConstInBoundsGEP2_64(Counters, 0, Edge);
695             Value *Count = Builder.CreateLoad(Counter);
696             Count = Builder.CreateAdd(Count, Builder.getInt64(1));
697             Builder.CreateStore(Count, Counter);
698           }
699         }
700       }
701     }
702 
703     Function *WriteoutF = insertCounterWriteout(CountersBySP);
704     Function *FlushF = insertFlush(CountersBySP);
705 
706     // Create a small bit of code that registers the "__llvm_gcov_writeout" to
707     // be executed at exit and the "__llvm_gcov_flush" function to be executed
708     // when "__gcov_flush" is called.
709     FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
710     Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
711                                    "__llvm_gcov_init", M);
712     F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
713     F->setLinkage(GlobalValue::InternalLinkage);
714     F->addFnAttr(Attribute::NoInline);
715     if (Options.NoRedZone)
716       F->addFnAttr(Attribute::NoRedZone);
717 
718     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
719     IRBuilder<> Builder(BB);
720 
721     FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
722     Type *Params[] = {
723       PointerType::get(FTy, 0),
724       PointerType::get(FTy, 0)
725     };
726     FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
727 
728     // Initialize the environment and register the local writeout and flush
729     // functions.
730     Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
731     Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
732     Builder.CreateRetVoid();
733 
734     appendToGlobalCtors(*M, F, 0);
735   }
736 
737   return Result;
738 }
739 
740 Constant *GCOVProfiler::getStartFileFunc() {
741   Type *Args[] = {
742     Type::getInt8PtrTy(*Ctx),  // const char *orig_filename
743     Type::getInt8PtrTy(*Ctx),  // const char version[4]
744     Type::getInt32Ty(*Ctx),    // uint32_t checksum
745   };
746   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
747   auto *Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy);
748   if (Function *FunRes = dyn_cast<Function>(Res))
749     if (auto AK = TLI->getExtAttrForI32Param(false))
750       FunRes->addParamAttr(2, AK);
751   return Res;
752 
753 }
754 
755 Constant *GCOVProfiler::getEmitFunctionFunc() {
756   Type *Args[] = {
757     Type::getInt32Ty(*Ctx),    // uint32_t ident
758     Type::getInt8PtrTy(*Ctx),  // const char *function_name
759     Type::getInt32Ty(*Ctx),    // uint32_t func_checksum
760     Type::getInt8Ty(*Ctx),     // uint8_t use_extra_checksum
761     Type::getInt32Ty(*Ctx),    // uint32_t cfg_checksum
762   };
763   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
764   auto *Res = M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
765   if (Function *FunRes = dyn_cast<Function>(Res))
766     if (auto AK = TLI->getExtAttrForI32Param(false)) {
767       FunRes->addParamAttr(0, AK);
768       FunRes->addParamAttr(2, AK);
769       FunRes->addParamAttr(3, AK);
770       FunRes->addParamAttr(4, AK);
771     }
772   return Res;
773 }
774 
775 Constant *GCOVProfiler::getEmitArcsFunc() {
776   Type *Args[] = {
777     Type::getInt32Ty(*Ctx),     // uint32_t num_counters
778     Type::getInt64PtrTy(*Ctx),  // uint64_t *counters
779   };
780   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
781   auto *Res = M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
782   if (Function *FunRes = dyn_cast<Function>(Res))
783     if (auto AK = TLI->getExtAttrForI32Param(false))
784       FunRes->addParamAttr(0, AK);
785   return Res;
786 }
787 
788 Constant *GCOVProfiler::getSummaryInfoFunc() {
789   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
790   return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
791 }
792 
793 Constant *GCOVProfiler::getEndFileFunc() {
794   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
795   return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
796 }
797 
798 Function *GCOVProfiler::insertCounterWriteout(
799     ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
800   FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
801   Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
802   if (!WriteoutF)
803     WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
804                                  "__llvm_gcov_writeout", M);
805   WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
806   WriteoutF->addFnAttr(Attribute::NoInline);
807   if (Options.NoRedZone)
808     WriteoutF->addFnAttr(Attribute::NoRedZone);
809 
810   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
811   IRBuilder<> Builder(BB);
812 
813   Constant *StartFile = getStartFileFunc();
814   Constant *EmitFunction = getEmitFunctionFunc();
815   Constant *EmitArcs = getEmitArcsFunc();
816   Constant *SummaryInfo = getSummaryInfoFunc();
817   Constant *EndFile = getEndFileFunc();
818 
819   NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
820   if (!CUNodes) {
821     Builder.CreateRetVoid();
822     return WriteoutF;
823   }
824 
825   // Collect the relevant data into a large constant data structure that we can
826   // walk to write out everything.
827   StructType *StartFileCallArgsTy = StructType::create(
828       {Builder.getInt8PtrTy(), Builder.getInt8PtrTy(), Builder.getInt32Ty()});
829   StructType *EmitFunctionCallArgsTy = StructType::create(
830       {Builder.getInt32Ty(), Builder.getInt8PtrTy(), Builder.getInt32Ty(),
831        Builder.getInt8Ty(), Builder.getInt32Ty()});
832   StructType *EmitArcsCallArgsTy = StructType::create(
833       {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
834   StructType *FileInfoTy =
835       StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
836                           EmitFunctionCallArgsTy->getPointerTo(),
837                           EmitArcsCallArgsTy->getPointerTo()});
838 
839   Constant *Zero32 = Builder.getInt32(0);
840   // Build an explicit array of two zeros for use in ConstantExpr GEP building.
841   Constant *TwoZero32s[] = {Zero32, Zero32};
842 
843   SmallVector<Constant *, 8> FileInfos;
844   for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
845     auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
846 
847     // Skip module skeleton (and module) CUs.
848     if (CU->getDWOId())
849       continue;
850 
851     std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
852     uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
853     auto *StartFileCallArgs = ConstantStruct::get(
854         StartFileCallArgsTy, {Builder.CreateGlobalStringPtr(FilenameGcda),
855                               Builder.CreateGlobalStringPtr(ReversedVersion),
856                               Builder.getInt32(CfgChecksum)});
857 
858     SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
859     SmallVector<Constant *, 8> EmitArcsCallArgsArray;
860     for (int j : llvm::seq<int>(0, CountersBySP.size())) {
861       auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
862       uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
863       EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
864           EmitFunctionCallArgsTy,
865           {Builder.getInt32(j),
866            Options.FunctionNamesInData
867                ? Builder.CreateGlobalStringPtr(getFunctionName(SP))
868                : Constant::getNullValue(Builder.getInt8PtrTy()),
869            Builder.getInt32(FuncChecksum),
870            Builder.getInt8(Options.UseCfgChecksum),
871            Builder.getInt32(CfgChecksum)}));
872 
873       GlobalVariable *GV = CountersBySP[j].first;
874       unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
875       EmitArcsCallArgsArray.push_back(ConstantStruct::get(
876           EmitArcsCallArgsTy,
877           {Builder.getInt32(Arcs), ConstantExpr::getInBoundsGetElementPtr(
878                                        GV->getValueType(), GV, TwoZero32s)}));
879     }
880     // Create global arrays for the two emit calls.
881     int CountersSize = CountersBySP.size();
882     assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
883            "Mismatched array size!");
884     assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
885            "Mismatched array size!");
886     auto *EmitFunctionCallArgsArrayTy =
887         ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
888     auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
889         *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
890         GlobalValue::InternalLinkage,
891         ConstantArray::get(EmitFunctionCallArgsArrayTy,
892                            EmitFunctionCallArgsArray),
893         Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
894     auto *EmitArcsCallArgsArrayTy =
895         ArrayType::get(EmitArcsCallArgsTy, CountersSize);
896     EmitFunctionCallArgsArrayGV->setUnnamedAddr(
897         GlobalValue::UnnamedAddr::Global);
898     auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
899         *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
900         GlobalValue::InternalLinkage,
901         ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
902         Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
903     EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
904 
905     FileInfos.push_back(ConstantStruct::get(
906         FileInfoTy,
907         {StartFileCallArgs, Builder.getInt32(CountersSize),
908          ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy,
909                                                 EmitFunctionCallArgsArrayGV,
910                                                 TwoZero32s),
911          ConstantExpr::getInBoundsGetElementPtr(
912              EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)}));
913   }
914 
915   // If we didn't find anything to actually emit, bail on out.
916   if (FileInfos.empty()) {
917     Builder.CreateRetVoid();
918     return WriteoutF;
919   }
920 
921   // To simplify code, we cap the number of file infos we write out to fit
922   // easily in a 32-bit signed integer. This gives consistent behavior between
923   // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
924   // operations on 32-bit systems. It also seems unreasonable to try to handle
925   // more than 2 billion files.
926   if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
927     FileInfos.resize(INT_MAX);
928 
929   // Create a global for the entire data structure so we can walk it more
930   // easily.
931   auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
932   auto *FileInfoArrayGV = new GlobalVariable(
933       *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
934       ConstantArray::get(FileInfoArrayTy, FileInfos),
935       "__llvm_internal_gcov_emit_file_info");
936   FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
937 
938   // Create the CFG for walking this data structure.
939   auto *FileLoopHeader =
940       BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
941   auto *CounterLoopHeader =
942       BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
943   auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
944   auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
945 
946   // We always have at least one file, so just branch to the header.
947   Builder.CreateBr(FileLoopHeader);
948 
949   // The index into the files structure is our loop induction variable.
950   Builder.SetInsertPoint(FileLoopHeader);
951   PHINode *IV =
952       Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
953   IV->addIncoming(Builder.getInt32(0), BB);
954   auto *FileInfoPtr =
955       Builder.CreateInBoundsGEP(FileInfoArrayGV, {Builder.getInt32(0), IV});
956   auto *StartFileCallArgsPtr = Builder.CreateStructGEP(FileInfoPtr, 0);
957   auto *StartFileCall = Builder.CreateCall(
958       StartFile,
959       {Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 0)),
960        Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 1)),
961        Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 2))});
962   if (auto AK = TLI->getExtAttrForI32Param(false))
963     StartFileCall->addParamAttr(2, AK);
964   auto *NumCounters =
965       Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 1));
966   auto *EmitFunctionCallArgsArray =
967       Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 2));
968   auto *EmitArcsCallArgsArray =
969       Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 3));
970   auto *EnterCounterLoopCond =
971       Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
972   Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
973 
974   Builder.SetInsertPoint(CounterLoopHeader);
975   auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
976   JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
977   auto *EmitFunctionCallArgsPtr =
978       Builder.CreateInBoundsGEP(EmitFunctionCallArgsArray, {JV});
979   auto *EmitFunctionCall = Builder.CreateCall(
980       EmitFunction,
981       {Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 0)),
982        Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 1)),
983        Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 2)),
984        Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 3)),
985        Builder.CreateLoad(
986            Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 4))});
987   if (auto AK = TLI->getExtAttrForI32Param(false)) {
988     EmitFunctionCall->addParamAttr(0, AK);
989     EmitFunctionCall->addParamAttr(2, AK);
990     EmitFunctionCall->addParamAttr(3, AK);
991     EmitFunctionCall->addParamAttr(4, AK);
992   }
993   auto *EmitArcsCallArgsPtr =
994       Builder.CreateInBoundsGEP(EmitArcsCallArgsArray, {JV});
995   auto *EmitArcsCall = Builder.CreateCall(
996       EmitArcs,
997       {Builder.CreateLoad(Builder.CreateStructGEP(EmitArcsCallArgsPtr, 0)),
998        Builder.CreateLoad(Builder.CreateStructGEP(EmitArcsCallArgsPtr, 1))});
999   if (auto AK = TLI->getExtAttrForI32Param(false))
1000     EmitArcsCall->addParamAttr(0, AK);
1001   auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1002   auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1003   Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1004   JV->addIncoming(NextJV, CounterLoopHeader);
1005 
1006   Builder.SetInsertPoint(FileLoopLatch);
1007   Builder.CreateCall(SummaryInfo, {});
1008   Builder.CreateCall(EndFile, {});
1009   auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1010   auto *FileLoopCond =
1011       Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1012   Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1013   IV->addIncoming(NextIV, FileLoopLatch);
1014 
1015   Builder.SetInsertPoint(ExitBB);
1016   Builder.CreateRetVoid();
1017 
1018   return WriteoutF;
1019 }
1020 
1021 Function *GCOVProfiler::
1022 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
1023   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1024   Function *FlushF = M->getFunction("__llvm_gcov_flush");
1025   if (!FlushF)
1026     FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
1027                               "__llvm_gcov_flush", M);
1028   else
1029     FlushF->setLinkage(GlobalValue::InternalLinkage);
1030   FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1031   FlushF->addFnAttr(Attribute::NoInline);
1032   if (Options.NoRedZone)
1033     FlushF->addFnAttr(Attribute::NoRedZone);
1034 
1035   BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
1036 
1037   // Write out the current counters.
1038   Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1039   assert(WriteoutF && "Need to create the writeout function first!");
1040 
1041   IRBuilder<> Builder(Entry);
1042   Builder.CreateCall(WriteoutF, {});
1043 
1044   // Zero out the counters.
1045   for (const auto &I : CountersBySP) {
1046     GlobalVariable *GV = I.first;
1047     Constant *Null = Constant::getNullValue(GV->getValueType());
1048     Builder.CreateStore(Null, GV);
1049   }
1050 
1051   Type *RetTy = FlushF->getReturnType();
1052   if (RetTy == Type::getVoidTy(*Ctx))
1053     Builder.CreateRetVoid();
1054   else if (RetTy->isIntegerTy())
1055     // Used if __llvm_gcov_flush was implicitly declared.
1056     Builder.CreateRet(ConstantInt::get(RetTy, 0));
1057   else
1058     report_fatal_error("invalid return type for __llvm_gcov_flush");
1059 
1060   return FlushF;
1061 }
1062