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