1 //===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements GCOV-style profiling. When this pass is run it emits
10 // "gcno" files next to the existing source, and instruments the code that runs
11 // to records the edges between blocks that run and emit a complementary "gcda"
12 // file on exit.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/Hashing.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/Sequence.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/Analysis/EHPersonalities.h"
24 #include "llvm/Analysis/TargetLibraryInfo.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/InstIterator.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/InitializePasses.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/Regex.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Transforms/Instrumentation.h"
42 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
43 #include "llvm/Transforms/Utils/ModuleUtils.h"
44 #include <algorithm>
45 #include <memory>
46 #include <string>
47 #include <utility>
48 
49 using namespace llvm;
50 namespace endian = llvm::support::endian;
51 
52 #define DEBUG_TYPE "insert-gcov-profiling"
53 
54 enum : uint32_t {
55   GCOV_TAG_FUNCTION = 0x01000000,
56   GCOV_TAG_BLOCKS = 0x01410000,
57   GCOV_TAG_ARCS = 0x01430000,
58   GCOV_TAG_LINES = 0x01450000,
59 };
60 
61 static cl::opt<std::string> DefaultGCOVVersion("default-gcov-version",
62                                                cl::init("408*"), cl::Hidden,
63                                                cl::ValueRequired);
64 
65 // Returns the number of words which will be used to represent this string.
66 static unsigned wordsOfString(StringRef s) {
67   // Length + NUL-terminated string + 0~3 padding NULs.
68   return (s.size() / 4) + 2;
69 }
70 
71 GCOVOptions GCOVOptions::getDefault() {
72   GCOVOptions Options;
73   Options.EmitNotes = true;
74   Options.EmitData = true;
75   Options.NoRedZone = false;
76 
77   if (DefaultGCOVVersion.size() != 4) {
78     llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
79                              DefaultGCOVVersion);
80   }
81   memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
82   return Options;
83 }
84 
85 namespace {
86 class GCOVFunction;
87 
88 class GCOVProfiler {
89 public:
90   GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
91   GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {}
92   bool
93   runOnModule(Module &M,
94               std::function<const TargetLibraryInfo &(Function &F)> GetTLI);
95 
96   void write(uint32_t i) {
97     char Bytes[4];
98     endian::write32(Bytes, i, Endian);
99     os->write(Bytes, 4);
100   }
101   void writeString(StringRef s) {
102     write(wordsOfString(s) - 1);
103     os->write(s.data(), s.size());
104     os->write_zeros(4 - s.size() % 4);
105   }
106   void writeBytes(const char *Bytes, int Size) { os->write(Bytes, Size); }
107 
108 private:
109   // Create the .gcno files for the Module based on DebugInfo.
110   void emitProfileNotes();
111 
112   // Modify the program to track transitions along edges and call into the
113   // profiling runtime to emit .gcda files when run.
114   bool emitProfileArcs();
115 
116   bool isFunctionInstrumented(const Function &F);
117   std::vector<Regex> createRegexesFromString(StringRef RegexesStr);
118   static bool doesFilenameMatchARegex(StringRef Filename,
119                                       std::vector<Regex> &Regexes);
120 
121   // Get pointers to the functions in the runtime library.
122   FunctionCallee getStartFileFunc(const TargetLibraryInfo *TLI);
123   FunctionCallee getEmitFunctionFunc(const TargetLibraryInfo *TLI);
124   FunctionCallee getEmitArcsFunc(const TargetLibraryInfo *TLI);
125   FunctionCallee getSummaryInfoFunc();
126   FunctionCallee getEndFileFunc();
127 
128   // Add the function to write out all our counters to the global destructor
129   // list.
130   Function *
131   insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
132   Function *insertReset(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
133 
134   bool AddFlushBeforeForkAndExec();
135 
136   enum class GCovFileType { GCNO, GCDA };
137   std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
138 
139   GCOVOptions Options;
140   support::endianness Endian;
141   raw_ostream *os;
142 
143   // Checksum, produced by hash of EdgeDestinations
144   SmallVector<uint32_t, 4> FileChecksums;
145 
146   Module *M = nullptr;
147   std::function<const TargetLibraryInfo &(Function &F)> GetTLI;
148   LLVMContext *Ctx = nullptr;
149   SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
150   std::vector<Regex> FilterRe;
151   std::vector<Regex> ExcludeRe;
152   StringMap<bool> InstrumentedFiles;
153 };
154 
155 class GCOVProfilerLegacyPass : public ModulePass {
156 public:
157   static char ID;
158   GCOVProfilerLegacyPass()
159       : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
160   GCOVProfilerLegacyPass(const GCOVOptions &Opts)
161       : ModulePass(ID), Profiler(Opts) {
162     initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
163   }
164   StringRef getPassName() const override { return "GCOV Profiler"; }
165 
166   bool runOnModule(Module &M) override {
167     return Profiler.runOnModule(M, [this](Function &F) -> TargetLibraryInfo & {
168       return getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
169     });
170   }
171 
172   void getAnalysisUsage(AnalysisUsage &AU) const override {
173     AU.addRequired<TargetLibraryInfoWrapperPass>();
174   }
175 
176 private:
177   GCOVProfiler Profiler;
178 };
179 }
180 
181 char GCOVProfilerLegacyPass::ID = 0;
182 INITIALIZE_PASS_BEGIN(
183     GCOVProfilerLegacyPass, "insert-gcov-profiling",
184     "Insert instrumentation for GCOV profiling", false, false)
185 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
186 INITIALIZE_PASS_END(
187     GCOVProfilerLegacyPass, "insert-gcov-profiling",
188     "Insert instrumentation for GCOV profiling", false, false)
189 
190 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
191   return new GCOVProfilerLegacyPass(Options);
192 }
193 
194 static StringRef getFunctionName(const DISubprogram *SP) {
195   if (!SP->getLinkageName().empty())
196     return SP->getLinkageName();
197   return SP->getName();
198 }
199 
200 /// Extract a filename for a DISubprogram.
201 ///
202 /// Prefer relative paths in the coverage notes. Clang also may split
203 /// up absolute paths into a directory and filename component. When
204 /// the relative path doesn't exist, reconstruct the absolute path.
205 static SmallString<128> getFilename(const DISubprogram *SP) {
206   SmallString<128> Path;
207   StringRef RelPath = SP->getFilename();
208   if (sys::fs::exists(RelPath))
209     Path = RelPath;
210   else
211     sys::path::append(Path, SP->getDirectory(), SP->getFilename());
212   return Path;
213 }
214 
215 namespace {
216   class GCOVRecord {
217   protected:
218     GCOVProfiler *P;
219 
220     GCOVRecord(GCOVProfiler *P) : P(P) {}
221 
222     void write(uint32_t i) { P->write(i); }
223     void writeString(StringRef s) { P->writeString(s); }
224     void writeBytes(const char *Bytes, int Size) { P->writeBytes(Bytes, Size); }
225   };
226 
227   class GCOVFunction;
228   class GCOVBlock;
229 
230   // Constructed only by requesting it from a GCOVBlock, this object stores a
231   // list of line numbers and a single filename, representing lines that belong
232   // to the block.
233   class GCOVLines : public GCOVRecord {
234    public:
235     void addLine(uint32_t Line) {
236       assert(Line != 0 && "Line zero is not a valid real line number.");
237       Lines.push_back(Line);
238     }
239 
240     uint32_t length() const {
241       return 1 + wordsOfString(Filename) + Lines.size();
242     }
243 
244     void writeOut() {
245       write(0);
246       writeString(Filename);
247       for (int i = 0, e = Lines.size(); i != e; ++i)
248         write(Lines[i]);
249     }
250 
251     GCOVLines(GCOVProfiler *P, StringRef F)
252         : GCOVRecord(P), Filename(std::string(F)) {}
253 
254   private:
255     std::string Filename;
256     SmallVector<uint32_t, 32> Lines;
257   };
258 
259 
260   // Represent a basic block in GCOV. Each block has a unique number in the
261   // function, number of lines belonging to each block, and a set of edges to
262   // other blocks.
263   class GCOVBlock : public GCOVRecord {
264    public:
265     GCOVLines &getFile(StringRef Filename) {
266       return LinesByFile.try_emplace(Filename, P, Filename).first->second;
267     }
268 
269     void addEdge(GCOVBlock &Successor) {
270       OutEdges.push_back(&Successor);
271     }
272 
273     void writeOut() {
274       uint32_t Len = 3;
275       SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
276       for (auto &I : LinesByFile) {
277         Len += I.second.length();
278         SortedLinesByFile.push_back(&I);
279       }
280 
281       write(GCOV_TAG_LINES);
282       write(Len);
283       write(Number);
284 
285       llvm::sort(SortedLinesByFile, [](StringMapEntry<GCOVLines> *LHS,
286                                        StringMapEntry<GCOVLines> *RHS) {
287         return LHS->getKey() < RHS->getKey();
288       });
289       for (auto &I : SortedLinesByFile)
290         I->getValue().writeOut();
291       write(0);
292       write(0);
293     }
294 
295     GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
296       // Only allow copy before edges and lines have been added. After that,
297       // there are inter-block pointers (eg: edges) that won't take kindly to
298       // blocks being copied or moved around.
299       assert(LinesByFile.empty());
300       assert(OutEdges.empty());
301     }
302 
303    private:
304     friend class GCOVFunction;
305 
306     GCOVBlock(GCOVProfiler *P, uint32_t Number)
307         : GCOVRecord(P), Number(Number) {}
308 
309     uint32_t Number;
310     StringMap<GCOVLines> LinesByFile;
311     SmallVector<GCOVBlock *, 4> OutEdges;
312   };
313 
314   // A function has a unique identifier, a checksum (we leave as zero) and a
315   // set of blocks and a map of edges between blocks. This is the only GCOV
316   // object users can construct, the blocks and lines will be rooted here.
317   class GCOVFunction : public GCOVRecord {
318   public:
319     GCOVFunction(GCOVProfiler *P, Function *F, const DISubprogram *SP,
320                  unsigned EndLine, uint32_t Ident, int Version)
321         : GCOVRecord(P), SP(SP), EndLine(EndLine), Ident(Ident),
322           Version(Version), ReturnBlock(P, 1) {
323       LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
324       bool ExitBlockBeforeBody = Version >= 48;
325       uint32_t i = 0;
326       for (auto &BB : *F) {
327         // Skip index 1 if it's assigned to the ReturnBlock.
328         if (i == 1 && ExitBlockBeforeBody)
329           ++i;
330         Blocks.insert(std::make_pair(&BB, GCOVBlock(P, i++)));
331       }
332       if (!ExitBlockBeforeBody)
333         ReturnBlock.Number = i;
334 
335       std::string FunctionNameAndLine;
336       raw_string_ostream FNLOS(FunctionNameAndLine);
337       FNLOS << getFunctionName(SP) << SP->getLine();
338       FNLOS.flush();
339       FuncChecksum = hash_value(FunctionNameAndLine);
340     }
341 
342     GCOVBlock &getBlock(BasicBlock *BB) {
343       return Blocks.find(BB)->second;
344     }
345 
346     GCOVBlock &getReturnBlock() {
347       return ReturnBlock;
348     }
349 
350     std::string getEdgeDestinations() {
351       std::string EdgeDestinations;
352       raw_string_ostream EDOS(EdgeDestinations);
353       Function *F = Blocks.begin()->first->getParent();
354       for (BasicBlock &I : *F) {
355         GCOVBlock &Block = getBlock(&I);
356         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
357           EDOS << Block.OutEdges[i]->Number;
358       }
359       return EdgeDestinations;
360     }
361 
362     uint32_t getFuncChecksum() const {
363       return FuncChecksum;
364     }
365 
366     void writeOut(uint32_t CfgChecksum) {
367       write(GCOV_TAG_FUNCTION);
368       SmallString<128> Filename = getFilename(SP);
369       uint32_t BlockLen =
370           2 + (Version >= 47) + wordsOfString(getFunctionName(SP));
371       if (Version < 80)
372         BlockLen += wordsOfString(Filename) + 1;
373       else
374         BlockLen += 1 + wordsOfString(Filename) + 3 + (Version >= 90);
375 
376       write(BlockLen);
377       write(Ident);
378       write(FuncChecksum);
379       if (Version >= 47)
380         write(CfgChecksum);
381       writeString(getFunctionName(SP));
382       if (Version < 80) {
383         writeString(Filename);
384         write(SP->getLine());
385       } else {
386         write(SP->isArtificial()); // artificial
387         writeString(Filename);
388         write(SP->getLine()); // start_line
389         write(0);             // start_column
390         // EndLine is the last line with !dbg. It is not the } line as in GCC,
391         // but good enough.
392         write(EndLine);
393         if (Version >= 90)
394           write(0); // end_column
395       }
396 
397       // Emit count of blocks.
398       write(GCOV_TAG_BLOCKS);
399       if (Version < 80) {
400         write(Blocks.size() + 1);
401         for (int i = Blocks.size() + 1; i; --i)
402           write(0);
403       } else {
404         write(1);
405         write(Blocks.size() + 1);
406       }
407       LLVM_DEBUG(dbgs() << (Blocks.size() + 1) << " blocks\n");
408 
409       // Emit edges between blocks.
410       Function *F = Blocks.begin()->first->getParent();
411       for (BasicBlock &I : *F) {
412         GCOVBlock &Block = getBlock(&I);
413         if (Block.OutEdges.empty()) continue;
414 
415         write(GCOV_TAG_ARCS);
416         write(Block.OutEdges.size() * 2 + 1);
417         write(Block.Number);
418         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
419           LLVM_DEBUG(dbgs() << Block.Number << " -> "
420                             << Block.OutEdges[i]->Number << "\n");
421           write(Block.OutEdges[i]->Number);
422           write(0);  // no flags
423         }
424       }
425 
426       // Emit lines for each block.
427       for (BasicBlock &I : *F)
428         getBlock(&I).writeOut();
429     }
430 
431   private:
432     const DISubprogram *SP;
433     unsigned EndLine;
434     uint32_t Ident;
435     uint32_t FuncChecksum;
436     int Version;
437     DenseMap<BasicBlock *, GCOVBlock> Blocks;
438     GCOVBlock ReturnBlock;
439   };
440 }
441 
442 // RegexesStr is a string containing differents regex separated by a semi-colon.
443 // For example "foo\..*$;bar\..*$".
444 std::vector<Regex> GCOVProfiler::createRegexesFromString(StringRef RegexesStr) {
445   std::vector<Regex> Regexes;
446   while (!RegexesStr.empty()) {
447     std::pair<StringRef, StringRef> HeadTail = RegexesStr.split(';');
448     if (!HeadTail.first.empty()) {
449       Regex Re(HeadTail.first);
450       std::string Err;
451       if (!Re.isValid(Err)) {
452         Ctx->emitError(Twine("Regex ") + HeadTail.first +
453                        " is not valid: " + Err);
454       }
455       Regexes.emplace_back(std::move(Re));
456     }
457     RegexesStr = HeadTail.second;
458   }
459   return Regexes;
460 }
461 
462 bool GCOVProfiler::doesFilenameMatchARegex(StringRef Filename,
463                                            std::vector<Regex> &Regexes) {
464   for (Regex &Re : Regexes)
465     if (Re.match(Filename))
466       return true;
467   return false;
468 }
469 
470 bool GCOVProfiler::isFunctionInstrumented(const Function &F) {
471   if (FilterRe.empty() && ExcludeRe.empty()) {
472     return true;
473   }
474   SmallString<128> Filename = getFilename(F.getSubprogram());
475   auto It = InstrumentedFiles.find(Filename);
476   if (It != InstrumentedFiles.end()) {
477     return It->second;
478   }
479 
480   SmallString<256> RealPath;
481   StringRef RealFilename;
482 
483   // Path can be
484   // /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/*.h so for
485   // such a case we must get the real_path.
486   if (sys::fs::real_path(Filename, RealPath)) {
487     // real_path can fail with path like "foo.c".
488     RealFilename = Filename;
489   } else {
490     RealFilename = RealPath;
491   }
492 
493   bool ShouldInstrument;
494   if (FilterRe.empty()) {
495     ShouldInstrument = !doesFilenameMatchARegex(RealFilename, ExcludeRe);
496   } else if (ExcludeRe.empty()) {
497     ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe);
498   } else {
499     ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe) &&
500                        !doesFilenameMatchARegex(RealFilename, ExcludeRe);
501   }
502   InstrumentedFiles[Filename] = ShouldInstrument;
503   return ShouldInstrument;
504 }
505 
506 std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
507                                      GCovFileType OutputType) {
508   bool Notes = OutputType == GCovFileType::GCNO;
509 
510   if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
511     for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
512       MDNode *N = GCov->getOperand(i);
513       bool ThreeElement = N->getNumOperands() == 3;
514       if (!ThreeElement && N->getNumOperands() != 2)
515         continue;
516       if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
517         continue;
518 
519       if (ThreeElement) {
520         // These nodes have no mangling to apply, it's stored mangled in the
521         // bitcode.
522         MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
523         MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
524         if (!NotesFile || !DataFile)
525           continue;
526         return std::string(Notes ? NotesFile->getString()
527                                  : DataFile->getString());
528       }
529 
530       MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
531       if (!GCovFile)
532         continue;
533 
534       SmallString<128> Filename = GCovFile->getString();
535       sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
536       return std::string(Filename.str());
537     }
538   }
539 
540   SmallString<128> Filename = CU->getFilename();
541   sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
542   StringRef FName = sys::path::filename(Filename);
543   SmallString<128> CurPath;
544   if (sys::fs::current_path(CurPath))
545     return std::string(FName);
546   sys::path::append(CurPath, FName);
547   return std::string(CurPath.str());
548 }
549 
550 bool GCOVProfiler::runOnModule(
551     Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
552   this->M = &M;
553   this->GetTLI = std::move(GetTLI);
554   Ctx = &M.getContext();
555 
556   bool Modified = AddFlushBeforeForkAndExec();
557 
558   FilterRe = createRegexesFromString(Options.Filter);
559   ExcludeRe = createRegexesFromString(Options.Exclude);
560 
561   if (Options.EmitNotes) emitProfileNotes();
562   if (Options.EmitData)
563     Modified |= emitProfileArcs();
564   return Modified;
565 }
566 
567 PreservedAnalyses GCOVProfilerPass::run(Module &M,
568                                         ModuleAnalysisManager &AM) {
569 
570   GCOVProfiler Profiler(GCOVOpts);
571   FunctionAnalysisManager &FAM =
572       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
573 
574   if (!Profiler.runOnModule(M, [&](Function &F) -> TargetLibraryInfo & {
575         return FAM.getResult<TargetLibraryAnalysis>(F);
576       }))
577     return PreservedAnalyses::all();
578 
579   return PreservedAnalyses::none();
580 }
581 
582 static bool functionHasLines(const Function &F, unsigned &EndLine) {
583   // Check whether this function actually has any source lines. Not only
584   // do these waste space, they also can crash gcov.
585   EndLine = 0;
586   for (auto &BB : F) {
587     for (auto &I : BB) {
588       // Debug intrinsic locations correspond to the location of the
589       // declaration, not necessarily any statements or expressions.
590       if (isa<DbgInfoIntrinsic>(&I)) continue;
591 
592       const DebugLoc &Loc = I.getDebugLoc();
593       if (!Loc)
594         continue;
595 
596       // Artificial lines such as calls to the global constructors.
597       if (Loc.getLine() == 0) continue;
598       EndLine = std::max(EndLine, Loc.getLine());
599 
600       return true;
601     }
602   }
603   return false;
604 }
605 
606 static bool isUsingScopeBasedEH(Function &F) {
607   if (!F.hasPersonalityFn()) return false;
608 
609   EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
610   return isScopedEHPersonality(Personality);
611 }
612 
613 static bool shouldKeepInEntry(BasicBlock::iterator It) {
614 	if (isa<AllocaInst>(*It)) return true;
615 	if (isa<DbgInfoIntrinsic>(*It)) return true;
616 	if (auto *II = dyn_cast<IntrinsicInst>(It)) {
617 		if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
618 	}
619 
620 	return false;
621 }
622 
623 bool GCOVProfiler::AddFlushBeforeForkAndExec() {
624   SmallVector<CallInst *, 2> Forks;
625   SmallVector<CallInst *, 2> Execs;
626   for (auto &F : M->functions()) {
627     auto *TLI = &GetTLI(F);
628     for (auto &I : instructions(F)) {
629       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
630         if (Function *Callee = CI->getCalledFunction()) {
631           LibFunc LF;
632           if (TLI->getLibFunc(*Callee, LF)) {
633             if (LF == LibFunc_fork) {
634 #if !defined(_WIN32)
635               Forks.push_back(CI);
636 #endif
637             } else if (LF == LibFunc_execl || LF == LibFunc_execle ||
638                        LF == LibFunc_execlp || LF == LibFunc_execv ||
639                        LF == LibFunc_execvp || LF == LibFunc_execve ||
640                        LF == LibFunc_execvpe || LF == LibFunc_execvP) {
641               Execs.push_back(CI);
642             }
643           }
644         }
645       }
646     }
647   }
648 
649   for (auto F : Forks) {
650     IRBuilder<> Builder(F);
651     BasicBlock *Parent = F->getParent();
652     auto NextInst = ++F->getIterator();
653 
654     // We've a fork so just reset the counters in the child process
655     FunctionType *FTy = FunctionType::get(Builder.getInt32Ty(), {}, false);
656     FunctionCallee GCOVFork = M->getOrInsertFunction("__gcov_fork", FTy);
657     F->setCalledFunction(GCOVFork);
658 
659     // We split just after the fork to have a counter for the lines after
660     // Anyway there's a bug:
661     // void foo() { fork(); }
662     // void bar() { foo(); blah(); }
663     // then "blah();" will be called 2 times but showed as 1
664     // because "blah()" belongs to the same block as "foo();"
665     Parent->splitBasicBlock(NextInst);
666 
667     // back() is a br instruction with a debug location
668     // equals to the one from NextAfterFork
669     // So to avoid to have two debug locs on two blocks just change it
670     DebugLoc Loc = F->getDebugLoc();
671     Parent->back().setDebugLoc(Loc);
672   }
673 
674   for (auto E : Execs) {
675     IRBuilder<> Builder(E);
676     BasicBlock *Parent = E->getParent();
677     auto NextInst = ++E->getIterator();
678 
679     // Since the process is replaced by a new one we need to write out gcdas
680     // No need to reset the counters since they'll be lost after the exec**
681     FunctionType *FTy = FunctionType::get(Builder.getVoidTy(), {}, false);
682     FunctionCallee WriteoutF =
683         M->getOrInsertFunction("llvm_writeout_files", FTy);
684     Builder.CreateCall(WriteoutF);
685 
686     DebugLoc Loc = E->getDebugLoc();
687     Builder.SetInsertPoint(&*NextInst);
688     // If the exec** fails we must reset the counters since they've been
689     // dumped
690     FunctionCallee ResetF = M->getOrInsertFunction("llvm_reset_counters", FTy);
691     Builder.CreateCall(ResetF)->setDebugLoc(Loc);
692     Parent->splitBasicBlock(NextInst);
693     Parent->back().setDebugLoc(Loc);
694   }
695 
696   return !Forks.empty() || !Execs.empty();
697 }
698 
699 void GCOVProfiler::emitProfileNotes() {
700   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
701   if (!CU_Nodes) return;
702 
703   int Version;
704   {
705     uint8_t c3 = Options.Version[0];
706     uint8_t c2 = Options.Version[1];
707     uint8_t c1 = Options.Version[2];
708     Version = c3 >= 'A' ? (c3 - 'A') * 100 + (c2 - '0') * 10 + c1 - '0'
709                         : (c3 - '0') * 10 + c1 - '0';
710   }
711 
712   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
713     // Each compile unit gets its own .gcno file. This means that whether we run
714     // this pass over the original .o's as they're produced, or run it after
715     // LTO, we'll generate the same .gcno files.
716 
717     auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
718 
719     // Skip module skeleton (and module) CUs.
720     if (CU->getDWOId())
721       continue;
722 
723     std::error_code EC;
724     raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC,
725                        sys::fs::OF_None);
726     if (EC) {
727       Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
728                      EC.message());
729       continue;
730     }
731 
732     std::string EdgeDestinations;
733 
734     Endian = M->getDataLayout().isLittleEndian() ? support::endianness::little
735                                                  : support::endianness::big;
736     unsigned FunctionIdent = 0;
737     for (auto &F : M->functions()) {
738       DISubprogram *SP = F.getSubprogram();
739       unsigned EndLine;
740       if (!SP) continue;
741       if (!functionHasLines(F, EndLine) || !isFunctionInstrumented(F))
742         continue;
743       // TODO: Functions using scope-based EH are currently not supported.
744       if (isUsingScopeBasedEH(F)) continue;
745 
746       // gcov expects every function to start with an entry block that has a
747       // single successor, so split the entry block to make sure of that.
748       BasicBlock &EntryBlock = F.getEntryBlock();
749       BasicBlock::iterator It = EntryBlock.begin();
750       while (shouldKeepInEntry(It))
751         ++It;
752       EntryBlock.splitBasicBlock(It);
753 
754       Funcs.push_back(std::make_unique<GCOVFunction>(this, &F, SP, EndLine,
755                                                      FunctionIdent++, Version));
756       GCOVFunction &Func = *Funcs.back();
757 
758       // Add the function line number to the lines of the entry block
759       // to have a counter for the function definition.
760       uint32_t Line = SP->getLine();
761       auto Filename = getFilename(SP);
762 
763       // Artificial functions such as global initializers
764       if (!SP->isArtificial())
765         Func.getBlock(&EntryBlock).getFile(Filename).addLine(Line);
766 
767       for (auto &BB : F) {
768         GCOVBlock &Block = Func.getBlock(&BB);
769         Instruction *TI = BB.getTerminator();
770         if (int successors = TI->getNumSuccessors()) {
771           for (int i = 0; i != successors; ++i) {
772             Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
773           }
774         } else if (isa<ReturnInst>(TI)) {
775           Block.addEdge(Func.getReturnBlock());
776         }
777 
778         for (auto &I : BB) {
779           // Debug intrinsic locations correspond to the location of the
780           // declaration, not necessarily any statements or expressions.
781           if (isa<DbgInfoIntrinsic>(&I)) continue;
782 
783           const DebugLoc &Loc = I.getDebugLoc();
784           if (!Loc)
785             continue;
786 
787           // Artificial lines such as calls to the global constructors.
788           if (Loc.getLine() == 0 || Loc.isImplicitCode())
789             continue;
790 
791           if (Line == Loc.getLine()) continue;
792           Line = Loc.getLine();
793           if (SP != getDISubprogram(Loc.getScope()))
794             continue;
795 
796           GCOVLines &Lines = Block.getFile(Filename);
797           Lines.addLine(Loc.getLine());
798         }
799         Line = 0;
800       }
801       EdgeDestinations += Func.getEdgeDestinations();
802     }
803 
804     char Tmp[4];
805     os = &out;
806     auto Stamp = static_cast<uint32_t>(hash_value(EdgeDestinations));
807     FileChecksums.push_back(Stamp);
808     if (Endian == support::endianness::big) {
809       out.write("gcno", 4);
810       out.write(Options.Version, 4);
811     } else {
812       out.write("oncg", 4);
813       std::reverse_copy(Options.Version, Options.Version + 4, Tmp);
814       out.write(Tmp, 4);
815     }
816     write(Stamp);
817     if (Version >= 90)
818       writeString(""); // unuseful current_working_directory
819     if (Version >= 80)
820       write(0); // unuseful has_unexecuted_blocks
821 
822     for (auto &Func : Funcs)
823       Func->writeOut(Stamp);
824 
825     write(0);
826     write(0);
827     out.close();
828   }
829 }
830 
831 bool GCOVProfiler::emitProfileArcs() {
832   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
833   if (!CU_Nodes) return false;
834 
835   bool Result = false;
836   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
837     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
838     for (auto &F : M->functions()) {
839       DISubprogram *SP = F.getSubprogram();
840       unsigned EndLine;
841       if (!SP) continue;
842       if (!functionHasLines(F, EndLine) || !isFunctionInstrumented(F))
843         continue;
844       // TODO: Functions using scope-based EH are currently not supported.
845       if (isUsingScopeBasedEH(F)) continue;
846 
847       DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter;
848       unsigned Edges = 0;
849       for (auto &BB : F) {
850         Instruction *TI = BB.getTerminator();
851         if (isa<ReturnInst>(TI)) {
852           EdgeToCounter[{&BB, nullptr}] = Edges++;
853         } else {
854           for (BasicBlock *Succ : successors(TI)) {
855             EdgeToCounter[{&BB, Succ}] = Edges++;
856           }
857         }
858       }
859 
860       ArrayType *CounterTy =
861         ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
862       GlobalVariable *Counters =
863         new GlobalVariable(*M, CounterTy, false,
864                            GlobalValue::InternalLinkage,
865                            Constant::getNullValue(CounterTy),
866                            "__llvm_gcov_ctr");
867       CountersBySP.push_back(std::make_pair(Counters, SP));
868 
869       // If a BB has several predecessors, use a PHINode to select
870       // the correct counter.
871       for (auto &BB : F) {
872         const unsigned EdgeCount =
873             std::distance(pred_begin(&BB), pred_end(&BB));
874         if (EdgeCount) {
875           // The phi node must be at the begin of the BB.
876           IRBuilder<> BuilderForPhi(&*BB.begin());
877           Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
878           PHINode *Phi = BuilderForPhi.CreatePHI(Int64PtrTy, EdgeCount);
879           for (BasicBlock *Pred : predecessors(&BB)) {
880             auto It = EdgeToCounter.find({Pred, &BB});
881             assert(It != EdgeToCounter.end());
882             const unsigned Edge = It->second;
883             Value *EdgeCounter = BuilderForPhi.CreateConstInBoundsGEP2_64(
884                 Counters->getValueType(), Counters, 0, Edge);
885             Phi->addIncoming(EdgeCounter, Pred);
886           }
887 
888           // Skip phis, landingpads.
889           IRBuilder<> Builder(&*BB.getFirstInsertionPt());
890           Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Phi);
891           Count = Builder.CreateAdd(Count, Builder.getInt64(1));
892           Builder.CreateStore(Count, Phi);
893 
894           Instruction *TI = BB.getTerminator();
895           if (isa<ReturnInst>(TI)) {
896             auto It = EdgeToCounter.find({&BB, nullptr});
897             assert(It != EdgeToCounter.end());
898             const unsigned Edge = It->second;
899             Value *Counter = Builder.CreateConstInBoundsGEP2_64(
900                 Counters->getValueType(), Counters, 0, Edge);
901             Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Counter);
902             Count = Builder.CreateAdd(Count, Builder.getInt64(1));
903             Builder.CreateStore(Count, Counter);
904           }
905         }
906       }
907     }
908 
909     Function *WriteoutF = insertCounterWriteout(CountersBySP);
910     Function *ResetF = insertReset(CountersBySP);
911 
912     // Create a small bit of code that registers the "__llvm_gcov_writeout" to
913     // be executed at exit and the "__llvm_gcov_flush" function to be executed
914     // when "__gcov_flush" is called.
915     FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
916     Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
917                                    "__llvm_gcov_init", M);
918     F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
919     F->setLinkage(GlobalValue::InternalLinkage);
920     F->addFnAttr(Attribute::NoInline);
921     if (Options.NoRedZone)
922       F->addFnAttr(Attribute::NoRedZone);
923 
924     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
925     IRBuilder<> Builder(BB);
926 
927     FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
928     auto *PFTy = PointerType::get(FTy, 0);
929     FTy = FunctionType::get(Builder.getVoidTy(), {PFTy, PFTy}, false);
930 
931     // Initialize the environment and register the local writeout, flush and
932     // reset functions.
933     FunctionCallee GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
934     Builder.CreateCall(GCOVInit, {WriteoutF, ResetF});
935     Builder.CreateRetVoid();
936 
937     appendToGlobalCtors(*M, F, 0);
938     Result = true;
939   }
940 
941   return Result;
942 }
943 
944 FunctionCallee GCOVProfiler::getStartFileFunc(const TargetLibraryInfo *TLI) {
945   Type *Args[] = {
946       Type::getInt8PtrTy(*Ctx), // const char *orig_filename
947       Type::getInt32Ty(*Ctx),   // uint32_t version
948       Type::getInt32Ty(*Ctx),   // uint32_t checksum
949   };
950   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
951   AttributeList AL;
952   if (auto AK = TLI->getExtAttrForI32Param(false))
953     AL = AL.addParamAttribute(*Ctx, 2, AK);
954   FunctionCallee Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy, AL);
955   return Res;
956 }
957 
958 FunctionCallee GCOVProfiler::getEmitFunctionFunc(const TargetLibraryInfo *TLI) {
959   Type *Args[] = {
960     Type::getInt32Ty(*Ctx),    // uint32_t ident
961     Type::getInt32Ty(*Ctx),    // uint32_t func_checksum
962     Type::getInt32Ty(*Ctx),    // uint32_t cfg_checksum
963   };
964   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
965   AttributeList AL;
966   if (auto AK = TLI->getExtAttrForI32Param(false)) {
967     AL = AL.addParamAttribute(*Ctx, 0, AK);
968     AL = AL.addParamAttribute(*Ctx, 1, AK);
969     AL = AL.addParamAttribute(*Ctx, 2, AK);
970   }
971   return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
972 }
973 
974 FunctionCallee GCOVProfiler::getEmitArcsFunc(const TargetLibraryInfo *TLI) {
975   Type *Args[] = {
976     Type::getInt32Ty(*Ctx),     // uint32_t num_counters
977     Type::getInt64PtrTy(*Ctx),  // uint64_t *counters
978   };
979   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
980   AttributeList AL;
981   if (auto AK = TLI->getExtAttrForI32Param(false))
982     AL = AL.addParamAttribute(*Ctx, 0, AK);
983   return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy, AL);
984 }
985 
986 FunctionCallee GCOVProfiler::getSummaryInfoFunc() {
987   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
988   return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
989 }
990 
991 FunctionCallee GCOVProfiler::getEndFileFunc() {
992   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
993   return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
994 }
995 
996 Function *GCOVProfiler::insertCounterWriteout(
997     ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
998   FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
999   Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1000   if (!WriteoutF)
1001     WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
1002                                  "__llvm_gcov_writeout", M);
1003   WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1004   WriteoutF->addFnAttr(Attribute::NoInline);
1005   if (Options.NoRedZone)
1006     WriteoutF->addFnAttr(Attribute::NoRedZone);
1007 
1008   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
1009   IRBuilder<> Builder(BB);
1010 
1011   auto *TLI = &GetTLI(*WriteoutF);
1012 
1013   FunctionCallee StartFile = getStartFileFunc(TLI);
1014   FunctionCallee EmitFunction = getEmitFunctionFunc(TLI);
1015   FunctionCallee EmitArcs = getEmitArcsFunc(TLI);
1016   FunctionCallee SummaryInfo = getSummaryInfoFunc();
1017   FunctionCallee EndFile = getEndFileFunc();
1018 
1019   NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
1020   if (!CUNodes) {
1021     Builder.CreateRetVoid();
1022     return WriteoutF;
1023   }
1024 
1025   // Collect the relevant data into a large constant data structure that we can
1026   // walk to write out everything.
1027   StructType *StartFileCallArgsTy = StructType::create(
1028       {Builder.getInt8PtrTy(), Builder.getInt32Ty(), Builder.getInt32Ty()});
1029   StructType *EmitFunctionCallArgsTy = StructType::create(
1030       {Builder.getInt32Ty(), Builder.getInt32Ty(), Builder.getInt32Ty()});
1031   StructType *EmitArcsCallArgsTy = StructType::create(
1032       {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
1033   StructType *FileInfoTy =
1034       StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
1035                           EmitFunctionCallArgsTy->getPointerTo(),
1036                           EmitArcsCallArgsTy->getPointerTo()});
1037 
1038   Constant *Zero32 = Builder.getInt32(0);
1039   // Build an explicit array of two zeros for use in ConstantExpr GEP building.
1040   Constant *TwoZero32s[] = {Zero32, Zero32};
1041 
1042   SmallVector<Constant *, 8> FileInfos;
1043   for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
1044     auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
1045 
1046     // Skip module skeleton (and module) CUs.
1047     if (CU->getDWOId())
1048       continue;
1049 
1050     std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
1051     uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
1052     auto *StartFileCallArgs = ConstantStruct::get(
1053         StartFileCallArgsTy,
1054         {Builder.CreateGlobalStringPtr(FilenameGcda),
1055          Builder.getInt32(endian::read32be(Options.Version)),
1056          Builder.getInt32(CfgChecksum)});
1057 
1058     SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
1059     SmallVector<Constant *, 8> EmitArcsCallArgsArray;
1060     for (int j : llvm::seq<int>(0, CountersBySP.size())) {
1061       uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
1062       EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
1063           EmitFunctionCallArgsTy,
1064           {Builder.getInt32(j),
1065            Builder.getInt32(FuncChecksum),
1066            Builder.getInt32(CfgChecksum)}));
1067 
1068       GlobalVariable *GV = CountersBySP[j].first;
1069       unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
1070       EmitArcsCallArgsArray.push_back(ConstantStruct::get(
1071           EmitArcsCallArgsTy,
1072           {Builder.getInt32(Arcs), ConstantExpr::getInBoundsGetElementPtr(
1073                                        GV->getValueType(), GV, TwoZero32s)}));
1074     }
1075     // Create global arrays for the two emit calls.
1076     int CountersSize = CountersBySP.size();
1077     assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
1078            "Mismatched array size!");
1079     assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
1080            "Mismatched array size!");
1081     auto *EmitFunctionCallArgsArrayTy =
1082         ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
1083     auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
1084         *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
1085         GlobalValue::InternalLinkage,
1086         ConstantArray::get(EmitFunctionCallArgsArrayTy,
1087                            EmitFunctionCallArgsArray),
1088         Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
1089     auto *EmitArcsCallArgsArrayTy =
1090         ArrayType::get(EmitArcsCallArgsTy, CountersSize);
1091     EmitFunctionCallArgsArrayGV->setUnnamedAddr(
1092         GlobalValue::UnnamedAddr::Global);
1093     auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
1094         *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
1095         GlobalValue::InternalLinkage,
1096         ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
1097         Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
1098     EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1099 
1100     FileInfos.push_back(ConstantStruct::get(
1101         FileInfoTy,
1102         {StartFileCallArgs, Builder.getInt32(CountersSize),
1103          ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy,
1104                                                 EmitFunctionCallArgsArrayGV,
1105                                                 TwoZero32s),
1106          ConstantExpr::getInBoundsGetElementPtr(
1107              EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)}));
1108   }
1109 
1110   // If we didn't find anything to actually emit, bail on out.
1111   if (FileInfos.empty()) {
1112     Builder.CreateRetVoid();
1113     return WriteoutF;
1114   }
1115 
1116   // To simplify code, we cap the number of file infos we write out to fit
1117   // easily in a 32-bit signed integer. This gives consistent behavior between
1118   // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
1119   // operations on 32-bit systems. It also seems unreasonable to try to handle
1120   // more than 2 billion files.
1121   if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
1122     FileInfos.resize(INT_MAX);
1123 
1124   // Create a global for the entire data structure so we can walk it more
1125   // easily.
1126   auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
1127   auto *FileInfoArrayGV = new GlobalVariable(
1128       *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
1129       ConstantArray::get(FileInfoArrayTy, FileInfos),
1130       "__llvm_internal_gcov_emit_file_info");
1131   FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1132 
1133   // Create the CFG for walking this data structure.
1134   auto *FileLoopHeader =
1135       BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
1136   auto *CounterLoopHeader =
1137       BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
1138   auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
1139   auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
1140 
1141   // We always have at least one file, so just branch to the header.
1142   Builder.CreateBr(FileLoopHeader);
1143 
1144   // The index into the files structure is our loop induction variable.
1145   Builder.SetInsertPoint(FileLoopHeader);
1146   PHINode *IV =
1147       Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1148   IV->addIncoming(Builder.getInt32(0), BB);
1149   auto *FileInfoPtr = Builder.CreateInBoundsGEP(
1150       FileInfoArrayTy, FileInfoArrayGV, {Builder.getInt32(0), IV});
1151   auto *StartFileCallArgsPtr =
1152       Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 0);
1153   auto *StartFileCall = Builder.CreateCall(
1154       StartFile,
1155       {Builder.CreateLoad(StartFileCallArgsTy->getElementType(0),
1156                           Builder.CreateStructGEP(StartFileCallArgsTy,
1157                                                   StartFileCallArgsPtr, 0)),
1158        Builder.CreateLoad(StartFileCallArgsTy->getElementType(1),
1159                           Builder.CreateStructGEP(StartFileCallArgsTy,
1160                                                   StartFileCallArgsPtr, 1)),
1161        Builder.CreateLoad(StartFileCallArgsTy->getElementType(2),
1162                           Builder.CreateStructGEP(StartFileCallArgsTy,
1163                                                   StartFileCallArgsPtr, 2))});
1164   if (auto AK = TLI->getExtAttrForI32Param(false))
1165     StartFileCall->addParamAttr(2, AK);
1166   auto *NumCounters =
1167       Builder.CreateLoad(FileInfoTy->getElementType(1),
1168                          Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 1));
1169   auto *EmitFunctionCallArgsArray =
1170       Builder.CreateLoad(FileInfoTy->getElementType(2),
1171                          Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 2));
1172   auto *EmitArcsCallArgsArray =
1173       Builder.CreateLoad(FileInfoTy->getElementType(3),
1174                          Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 3));
1175   auto *EnterCounterLoopCond =
1176       Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
1177   Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
1178 
1179   Builder.SetInsertPoint(CounterLoopHeader);
1180   auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1181   JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
1182   auto *EmitFunctionCallArgsPtr = Builder.CreateInBoundsGEP(
1183       EmitFunctionCallArgsTy, EmitFunctionCallArgsArray, JV);
1184   auto *EmitFunctionCall = Builder.CreateCall(
1185       EmitFunction,
1186       {Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(0),
1187                           Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1188                                                   EmitFunctionCallArgsPtr, 0)),
1189        Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(1),
1190                           Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1191                                                   EmitFunctionCallArgsPtr, 1)),
1192        Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(2),
1193                           Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1194                                                   EmitFunctionCallArgsPtr,
1195                                                   2))});
1196   if (auto AK = TLI->getExtAttrForI32Param(false)) {
1197     EmitFunctionCall->addParamAttr(0, AK);
1198     EmitFunctionCall->addParamAttr(1, AK);
1199     EmitFunctionCall->addParamAttr(2, AK);
1200   }
1201   auto *EmitArcsCallArgsPtr =
1202       Builder.CreateInBoundsGEP(EmitArcsCallArgsTy, EmitArcsCallArgsArray, JV);
1203   auto *EmitArcsCall = Builder.CreateCall(
1204       EmitArcs,
1205       {Builder.CreateLoad(
1206            EmitArcsCallArgsTy->getElementType(0),
1207            Builder.CreateStructGEP(EmitArcsCallArgsTy, EmitArcsCallArgsPtr, 0)),
1208        Builder.CreateLoad(EmitArcsCallArgsTy->getElementType(1),
1209                           Builder.CreateStructGEP(EmitArcsCallArgsTy,
1210                                                   EmitArcsCallArgsPtr, 1))});
1211   if (auto AK = TLI->getExtAttrForI32Param(false))
1212     EmitArcsCall->addParamAttr(0, AK);
1213   auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1214   auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1215   Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1216   JV->addIncoming(NextJV, CounterLoopHeader);
1217 
1218   Builder.SetInsertPoint(FileLoopLatch);
1219   Builder.CreateCall(SummaryInfo, {});
1220   Builder.CreateCall(EndFile, {});
1221   auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1222   auto *FileLoopCond =
1223       Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1224   Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1225   IV->addIncoming(NextIV, FileLoopLatch);
1226 
1227   Builder.SetInsertPoint(ExitBB);
1228   Builder.CreateRetVoid();
1229 
1230   return WriteoutF;
1231 }
1232 
1233 Function *GCOVProfiler::insertReset(
1234     ArrayRef<std::pair<GlobalVariable *, MDNode *>> CountersBySP) {
1235   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1236   Function *ResetF = M->getFunction("__llvm_gcov_reset");
1237   if (!ResetF)
1238     ResetF = Function::Create(FTy, GlobalValue::InternalLinkage,
1239                               "__llvm_gcov_reset", M);
1240   ResetF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1241   ResetF->addFnAttr(Attribute::NoInline);
1242   if (Options.NoRedZone)
1243     ResetF->addFnAttr(Attribute::NoRedZone);
1244 
1245   BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", ResetF);
1246   IRBuilder<> Builder(Entry);
1247 
1248   // Zero out the counters.
1249   for (const auto &I : CountersBySP) {
1250     GlobalVariable *GV = I.first;
1251     Constant *Null = Constant::getNullValue(GV->getValueType());
1252     Builder.CreateStore(Null, GV);
1253   }
1254 
1255   Type *RetTy = ResetF->getReturnType();
1256   if (RetTy->isVoidTy())
1257     Builder.CreateRetVoid();
1258   else if (RetTy->isIntegerTy())
1259     // Used if __llvm_gcov_reset was implicitly declared.
1260     Builder.CreateRet(ConstantInt::get(RetTy, 0));
1261   else
1262     report_fatal_error("invalid return type for __llvm_gcov_reset");
1263 
1264   return ResetF;
1265 }
1266