1 //===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
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
7 //===----------------------------------------------------------------------===//
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"
14 //===----------------------------------------------------------------------===//
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"
50 #define DEBUG_TYPE "insert-gcov-profiling"
52 static cl::opt<std::string>
53 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
55 static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
56 cl::init(false), cl::Hidden);
58 GCOVOptions GCOVOptions::getDefault() {
60 Options.EmitNotes = true;
61 Options.EmitData = true;
62 Options.UseCfgChecksum = false;
63 Options.NoRedZone = false;
64 Options.FunctionNamesInData = true;
65 Options.ExitBlockBeforeBody = DefaultExitBlockBeforeBody;
67 if (DefaultGCOVVersion.size() != 4) {
68 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
71 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
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';
91 runOnModule(Module &M,
92 std::function<const TargetLibraryInfo &(Function &F)> GetTLI);
95 // Create the .gcno files for the Module based on DebugInfo.
96 void emitProfileNotes();
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();
102 bool isFunctionInstrumented(const Function &F);
103 std::vector<Regex> createRegexesFromString(StringRef RegexesStr);
104 static bool doesFilenameMatchARegex(StringRef Filename,
105 std::vector<Regex> &Regexes);
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();
114 // Add the function to write out all our counters to the global destructor
117 insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
118 Function *insertReset(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
119 Function *insertFlush(Function *ResetF);
121 void AddFlushBeforeForkAndExec();
123 enum class GCovFileType { GCNO, GCDA };
124 std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
128 // Reversed, NUL-terminated copy of Options.Version.
129 char ReversedVersion[5];
130 // Checksum, produced by hash of EdgeDestinations
131 SmallVector<uint32_t, 4> FileChecksums;
134 std::function<const TargetLibraryInfo &(Function &F)> GetTLI;
135 LLVMContext *Ctx = nullptr;
136 SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
137 std::vector<Regex> FilterRe;
138 std::vector<Regex> ExcludeRe;
139 StringMap<bool> InstrumentedFiles;
142 class GCOVProfilerLegacyPass : public ModulePass {
145 GCOVProfilerLegacyPass()
146 : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
147 GCOVProfilerLegacyPass(const GCOVOptions &Opts)
148 : ModulePass(ID), Profiler(Opts) {
149 initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
151 StringRef getPassName() const override { return "GCOV Profiler"; }
153 bool runOnModule(Module &M) override {
154 return Profiler.runOnModule(M, [this](Function &F) -> TargetLibraryInfo & {
155 return getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
159 void getAnalysisUsage(AnalysisUsage &AU) const override {
160 AU.addRequired<TargetLibraryInfoWrapperPass>();
164 GCOVProfiler Profiler;
168 char GCOVProfilerLegacyPass::ID = 0;
169 INITIALIZE_PASS_BEGIN(
170 GCOVProfilerLegacyPass, "insert-gcov-profiling",
171 "Insert instrumentation for GCOV profiling", false, false)
172 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
174 GCOVProfilerLegacyPass, "insert-gcov-profiling",
175 "Insert instrumentation for GCOV profiling", false, false)
177 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
178 return new GCOVProfilerLegacyPass(Options);
181 static StringRef getFunctionName(const DISubprogram *SP) {
182 if (!SP->getLinkageName().empty())
183 return SP->getLinkageName();
184 return SP->getName();
187 /// Extract a filename for a DISubprogram.
189 /// Prefer relative paths in the coverage notes. Clang also may split
190 /// up absolute paths into a directory and filename component. When
191 /// the relative path doesn't exist, reconstruct the absolute path.
192 static SmallString<128> getFilename(const DISubprogram *SP) {
193 SmallString<128> Path;
194 StringRef RelPath = SP->getFilename();
195 if (sys::fs::exists(RelPath))
198 sys::path::append(Path, SP->getDirectory(), SP->getFilename());
205 static const char *const LinesTag;
206 static const char *const FunctionTag;
207 static const char *const BlockTag;
208 static const char *const EdgeTag;
210 GCOVRecord() = default;
212 void writeBytes(const char *Bytes, int Size) {
213 os->write(Bytes, Size);
216 void write(uint32_t i) {
217 writeBytes(reinterpret_cast<char*>(&i), 4);
220 // Returns the length measured in 4-byte blocks that will be used to
221 // represent this string in a GCOV file
222 static unsigned lengthOfGCOVString(StringRef s) {
223 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
224 // padding out to the next 4-byte word. The length is measured in 4-byte
225 // words including padding, not bytes of actual string.
226 return (s.size() / 4) + 1;
229 void writeGCOVString(StringRef s) {
230 uint32_t Len = lengthOfGCOVString(s);
232 writeBytes(s.data(), s.size());
234 // Write 1 to 4 bytes of NUL padding.
235 assert((unsigned)(4 - (s.size() % 4)) > 0);
236 assert((unsigned)(4 - (s.size() % 4)) <= 4);
237 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
242 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
243 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
244 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
245 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
250 // Constructed only by requesting it from a GCOVBlock, this object stores a
251 // list of line numbers and a single filename, representing lines that belong
253 class GCOVLines : public GCOVRecord {
255 void addLine(uint32_t Line) {
256 assert(Line != 0 && "Line zero is not a valid real line number.");
257 Lines.push_back(Line);
260 uint32_t length() const {
261 // Here 2 = 1 for string length + 1 for '0' id#.
262 return lengthOfGCOVString(Filename) + 2 + Lines.size();
267 writeGCOVString(Filename);
268 for (int i = 0, e = Lines.size(); i != e; ++i)
272 GCOVLines(StringRef F, raw_ostream *os)
278 std::string Filename;
279 SmallVector<uint32_t, 32> Lines;
283 // Represent a basic block in GCOV. Each block has a unique number in the
284 // function, number of lines belonging to each block, and a set of edges to
286 class GCOVBlock : public GCOVRecord {
288 GCOVLines &getFile(StringRef Filename) {
289 return LinesByFile.try_emplace(Filename, Filename, os).first->second;
292 void addEdge(GCOVBlock &Successor) {
293 OutEdges.push_back(&Successor);
298 SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
299 for (auto &I : LinesByFile) {
300 Len += I.second.length();
301 SortedLinesByFile.push_back(&I);
304 writeBytes(LinesTag, 4);
308 llvm::sort(SortedLinesByFile, [](StringMapEntry<GCOVLines> *LHS,
309 StringMapEntry<GCOVLines> *RHS) {
310 return LHS->getKey() < RHS->getKey();
312 for (auto &I : SortedLinesByFile)
313 I->getValue().writeOut();
318 GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
319 // Only allow copy before edges and lines have been added. After that,
320 // there are inter-block pointers (eg: edges) that won't take kindly to
321 // blocks being copied or moved around.
322 assert(LinesByFile.empty());
323 assert(OutEdges.empty());
327 friend class GCOVFunction;
329 GCOVBlock(uint32_t Number, raw_ostream *os)
335 StringMap<GCOVLines> LinesByFile;
336 SmallVector<GCOVBlock *, 4> OutEdges;
339 // A function has a unique identifier, a checksum (we leave as zero) and a
340 // set of blocks and a map of edges between blocks. This is the only GCOV
341 // object users can construct, the blocks and lines will be rooted here.
342 class GCOVFunction : public GCOVRecord {
344 GCOVFunction(const DISubprogram *SP, Function *F, raw_ostream *os,
345 uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
346 : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
350 LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
353 for (auto &BB : *F) {
354 // Skip index 1 if it's assigned to the ReturnBlock.
355 if (i == 1 && ExitBlockBeforeBody)
357 Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
359 if (!ExitBlockBeforeBody)
360 ReturnBlock.Number = i;
362 std::string FunctionNameAndLine;
363 raw_string_ostream FNLOS(FunctionNameAndLine);
364 FNLOS << getFunctionName(SP) << SP->getLine();
366 FuncChecksum = hash_value(FunctionNameAndLine);
369 GCOVBlock &getBlock(BasicBlock *BB) {
370 return Blocks.find(BB)->second;
373 GCOVBlock &getReturnBlock() {
377 std::string getEdgeDestinations() {
378 std::string EdgeDestinations;
379 raw_string_ostream EDOS(EdgeDestinations);
380 Function *F = Blocks.begin()->first->getParent();
381 for (BasicBlock &I : *F) {
382 GCOVBlock &Block = getBlock(&I);
383 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
384 EDOS << Block.OutEdges[i]->Number;
386 return EdgeDestinations;
389 uint32_t getFuncChecksum() const {
393 void setCfgChecksum(uint32_t Checksum) {
394 CfgChecksum = Checksum;
398 writeBytes(FunctionTag, 4);
399 SmallString<128> Filename = getFilename(SP);
400 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
401 1 + lengthOfGCOVString(Filename) + 1;
409 writeGCOVString(getFunctionName(SP));
410 writeGCOVString(Filename);
411 write(SP->getLine());
413 // Emit count of blocks.
414 writeBytes(BlockTag, 4);
415 write(Blocks.size() + 1);
416 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
417 write(0); // No flags on our blocks.
419 LLVM_DEBUG(dbgs() << Blocks.size() << " blocks.\n");
421 // Emit edges between blocks.
422 if (Blocks.empty()) return;
423 Function *F = Blocks.begin()->first->getParent();
424 for (BasicBlock &I : *F) {
425 GCOVBlock &Block = getBlock(&I);
426 if (Block.OutEdges.empty()) continue;
428 writeBytes(EdgeTag, 4);
429 write(Block.OutEdges.size() * 2 + 1);
431 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
432 LLVM_DEBUG(dbgs() << Block.Number << " -> "
433 << Block.OutEdges[i]->Number << "\n");
434 write(Block.OutEdges[i]->Number);
435 write(0); // no flags
439 // Emit lines for each block.
440 for (BasicBlock &I : *F)
441 getBlock(&I).writeOut();
445 const DISubprogram *SP;
447 uint32_t FuncChecksum;
449 uint32_t CfgChecksum;
450 DenseMap<BasicBlock *, GCOVBlock> Blocks;
451 GCOVBlock ReturnBlock;
455 // RegexesStr is a string containing differents regex separated by a semi-colon.
456 // For example "foo\..*$;bar\..*$".
457 std::vector<Regex> GCOVProfiler::createRegexesFromString(StringRef RegexesStr) {
458 std::vector<Regex> Regexes;
459 while (!RegexesStr.empty()) {
460 std::pair<StringRef, StringRef> HeadTail = RegexesStr.split(';');
461 if (!HeadTail.first.empty()) {
462 Regex Re(HeadTail.first);
464 if (!Re.isValid(Err)) {
465 Ctx->emitError(Twine("Regex ") + HeadTail.first +
466 " is not valid: " + Err);
468 Regexes.emplace_back(std::move(Re));
470 RegexesStr = HeadTail.second;
475 bool GCOVProfiler::doesFilenameMatchARegex(StringRef Filename,
476 std::vector<Regex> &Regexes) {
477 for (Regex &Re : Regexes) {
478 if (Re.match(Filename)) {
485 bool GCOVProfiler::isFunctionInstrumented(const Function &F) {
486 if (FilterRe.empty() && ExcludeRe.empty()) {
489 SmallString<128> Filename = getFilename(F.getSubprogram());
490 auto It = InstrumentedFiles.find(Filename);
491 if (It != InstrumentedFiles.end()) {
495 SmallString<256> RealPath;
496 StringRef RealFilename;
499 // /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/*.h so for
500 // such a case we must get the real_path.
501 if (sys::fs::real_path(Filename, RealPath)) {
502 // real_path can fail with path like "foo.c".
503 RealFilename = Filename;
505 RealFilename = RealPath;
508 bool ShouldInstrument;
509 if (FilterRe.empty()) {
510 ShouldInstrument = !doesFilenameMatchARegex(RealFilename, ExcludeRe);
511 } else if (ExcludeRe.empty()) {
512 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe);
514 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe) &&
515 !doesFilenameMatchARegex(RealFilename, ExcludeRe);
517 InstrumentedFiles[Filename] = ShouldInstrument;
518 return ShouldInstrument;
521 std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
522 GCovFileType OutputType) {
523 bool Notes = OutputType == GCovFileType::GCNO;
525 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
526 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
527 MDNode *N = GCov->getOperand(i);
528 bool ThreeElement = N->getNumOperands() == 3;
529 if (!ThreeElement && N->getNumOperands() != 2)
531 if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
535 // These nodes have no mangling to apply, it's stored mangled in the
537 MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
538 MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
539 if (!NotesFile || !DataFile)
541 return Notes ? NotesFile->getString() : DataFile->getString();
544 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
548 SmallString<128> Filename = GCovFile->getString();
549 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
550 return Filename.str();
554 SmallString<128> Filename = CU->getFilename();
555 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
556 StringRef FName = sys::path::filename(Filename);
557 SmallString<128> CurPath;
558 if (sys::fs::current_path(CurPath)) return FName;
559 sys::path::append(CurPath, FName);
560 return CurPath.str();
563 bool GCOVProfiler::runOnModule(
564 Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
566 this->GetTLI = std::move(GetTLI);
567 Ctx = &M.getContext();
569 AddFlushBeforeForkAndExec();
571 FilterRe = createRegexesFromString(Options.Filter);
572 ExcludeRe = createRegexesFromString(Options.Exclude);
574 if (Options.EmitNotes) emitProfileNotes();
575 if (Options.EmitData) return emitProfileArcs();
579 PreservedAnalyses GCOVProfilerPass::run(Module &M,
580 ModuleAnalysisManager &AM) {
582 GCOVProfiler Profiler(GCOVOpts);
583 FunctionAnalysisManager &FAM =
584 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
586 if (!Profiler.runOnModule(M, [&](Function &F) -> TargetLibraryInfo & {
587 return FAM.getResult<TargetLibraryAnalysis>(F);
589 return PreservedAnalyses::all();
591 return PreservedAnalyses::none();
594 static bool functionHasLines(Function &F) {
595 // Check whether this function actually has any source lines. Not only
596 // do these waste space, they also can crash gcov.
599 // Debug intrinsic locations correspond to the location of the
600 // declaration, not necessarily any statements or expressions.
601 if (isa<DbgInfoIntrinsic>(&I)) continue;
603 const DebugLoc &Loc = I.getDebugLoc();
607 // Artificial lines such as calls to the global constructors.
608 if (Loc.getLine() == 0) continue;
616 static bool isUsingScopeBasedEH(Function &F) {
617 if (!F.hasPersonalityFn()) return false;
619 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
620 return isScopedEHPersonality(Personality);
623 static bool shouldKeepInEntry(BasicBlock::iterator It) {
624 if (isa<AllocaInst>(*It)) return true;
625 if (isa<DbgInfoIntrinsic>(*It)) return true;
626 if (auto *II = dyn_cast<IntrinsicInst>(It)) {
627 if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
633 void GCOVProfiler::AddFlushBeforeForkAndExec() {
634 SmallVector<CallInst *, 2> Forks;
635 SmallVector<CallInst *, 2> Execs;
636 for (auto &F : M->functions()) {
637 auto *TLI = &GetTLI(F);
638 for (auto &I : instructions(F)) {
639 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
640 if (Function *Callee = CI->getCalledFunction()) {
642 if (TLI->getLibFunc(*Callee, LF)) {
643 if (LF == LibFunc_fork) {
647 } else if (LF == LibFunc_execl || LF == LibFunc_execle ||
648 LF == LibFunc_execlp || LF == LibFunc_execv ||
649 LF == LibFunc_execvp || LF == LibFunc_execve ||
650 LF == LibFunc_execvpe || LF == LibFunc_execvP) {
659 for (auto F : Forks) {
660 IRBuilder<> Builder(F);
661 BasicBlock *Parent = F->getParent();
662 auto NextInst = ++F->getIterator();
664 // We've a fork so just reset the counters in the child process
665 FunctionType *FTy = FunctionType::get(Builder.getInt32Ty(), {}, false);
666 FunctionCallee GCOVFork = M->getOrInsertFunction("__gcov_fork", FTy);
667 F->setCalledFunction(GCOVFork);
669 // We split just after the fork to have a counter for the lines after
670 // Anyway there's a bug:
671 // void foo() { fork(); }
672 // void bar() { foo(); blah(); }
673 // then "blah();" will be called 2 times but showed as 1
674 // because "blah()" belongs to the same block as "foo();"
675 Parent->splitBasicBlock(NextInst);
677 // back() is a br instruction with a debug location
678 // equals to the one from NextAfterFork
679 // So to avoid to have two debug locs on two blocks just change it
680 DebugLoc Loc = F->getDebugLoc();
681 Parent->back().setDebugLoc(Loc);
684 for (auto E : Execs) {
685 IRBuilder<> Builder(E);
686 BasicBlock *Parent = E->getParent();
687 auto NextInst = ++E->getIterator();
689 // Since the process is replaced by a new one we need to write out gcdas
690 // No need to reset the counters since they'll be lost after the exec**
691 FunctionType *FTy = FunctionType::get(Builder.getVoidTy(), {}, false);
692 FunctionCallee WriteoutF =
693 M->getOrInsertFunction("llvm_writeout_files", FTy);
694 Builder.CreateCall(WriteoutF);
696 DebugLoc Loc = E->getDebugLoc();
697 Builder.SetInsertPoint(&*NextInst);
698 // If the exec** fails we must reset the counters since they've been
700 FunctionCallee ResetF = M->getOrInsertFunction("llvm_reset_counters", FTy);
701 Builder.CreateCall(ResetF)->setDebugLoc(Loc);
702 Parent->splitBasicBlock(NextInst);
703 Parent->back().setDebugLoc(Loc);
707 void GCOVProfiler::emitProfileNotes() {
708 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
709 if (!CU_Nodes) return;
711 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
712 // Each compile unit gets its own .gcno file. This means that whether we run
713 // this pass over the original .o's as they're produced, or run it after
714 // LTO, we'll generate the same .gcno files.
716 auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
718 // Skip module skeleton (and module) CUs.
723 raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC,
726 Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
731 std::string EdgeDestinations;
733 unsigned FunctionIdent = 0;
734 for (auto &F : M->functions()) {
735 DISubprogram *SP = F.getSubprogram();
737 if (!functionHasLines(F) || !isFunctionInstrumented(F))
739 // TODO: Functions using scope-based EH are currently not supported.
740 if (isUsingScopeBasedEH(F)) continue;
742 // gcov expects every function to start with an entry block that has a
743 // single successor, so split the entry block to make sure of that.
744 BasicBlock &EntryBlock = F.getEntryBlock();
745 BasicBlock::iterator It = EntryBlock.begin();
746 while (shouldKeepInEntry(It))
748 EntryBlock.splitBasicBlock(It);
750 Funcs.push_back(std::make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
751 Options.UseCfgChecksum,
752 Options.ExitBlockBeforeBody));
753 GCOVFunction &Func = *Funcs.back();
755 // Add the function line number to the lines of the entry block
756 // to have a counter for the function definition.
757 uint32_t Line = SP->getLine();
758 auto Filename = getFilename(SP);
760 // Artificial functions such as global initializers
761 if (!SP->isArtificial())
762 Func.getBlock(&EntryBlock).getFile(Filename).addLine(Line);
765 GCOVBlock &Block = Func.getBlock(&BB);
766 Instruction *TI = BB.getTerminator();
767 if (int successors = TI->getNumSuccessors()) {
768 for (int i = 0; i != successors; ++i) {
769 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
771 } else if (isa<ReturnInst>(TI)) {
772 Block.addEdge(Func.getReturnBlock());
776 // Debug intrinsic locations correspond to the location of the
777 // declaration, not necessarily any statements or expressions.
778 if (isa<DbgInfoIntrinsic>(&I)) continue;
780 const DebugLoc &Loc = I.getDebugLoc();
784 // Artificial lines such as calls to the global constructors.
785 if (Loc.getLine() == 0 || Loc.isImplicitCode())
788 if (Line == Loc.getLine()) continue;
789 Line = Loc.getLine();
790 if (SP != getDISubprogram(Loc.getScope()))
793 GCOVLines &Lines = Block.getFile(Filename);
794 Lines.addLine(Loc.getLine());
798 EdgeDestinations += Func.getEdgeDestinations();
801 FileChecksums.push_back(hash_value(EdgeDestinations));
802 out.write("oncg", 4);
803 out.write(ReversedVersion, 4);
804 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
806 for (auto &Func : Funcs) {
807 Func->setCfgChecksum(FileChecksums.back());
811 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
816 bool GCOVProfiler::emitProfileArcs() {
817 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
818 if (!CU_Nodes) return false;
821 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
822 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
823 for (auto &F : M->functions()) {
824 DISubprogram *SP = F.getSubprogram();
826 if (!functionHasLines(F) || !isFunctionInstrumented(F))
828 // TODO: Functions using scope-based EH are currently not supported.
829 if (isUsingScopeBasedEH(F)) continue;
830 if (!Result) Result = true;
832 DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter;
835 Instruction *TI = BB.getTerminator();
836 if (isa<ReturnInst>(TI)) {
837 EdgeToCounter[{&BB, nullptr}] = Edges++;
839 for (BasicBlock *Succ : successors(TI)) {
840 EdgeToCounter[{&BB, Succ}] = Edges++;
845 ArrayType *CounterTy =
846 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
847 GlobalVariable *Counters =
848 new GlobalVariable(*M, CounterTy, false,
849 GlobalValue::InternalLinkage,
850 Constant::getNullValue(CounterTy),
852 CountersBySP.push_back(std::make_pair(Counters, SP));
854 // If a BB has several predecessors, use a PHINode to select
855 // the correct counter.
857 const unsigned EdgeCount =
858 std::distance(pred_begin(&BB), pred_end(&BB));
860 // The phi node must be at the begin of the BB.
861 IRBuilder<> BuilderForPhi(&*BB.begin());
862 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
863 PHINode *Phi = BuilderForPhi.CreatePHI(Int64PtrTy, EdgeCount);
864 for (BasicBlock *Pred : predecessors(&BB)) {
865 auto It = EdgeToCounter.find({Pred, &BB});
866 assert(It != EdgeToCounter.end());
867 const unsigned Edge = It->second;
868 Value *EdgeCounter = BuilderForPhi.CreateConstInBoundsGEP2_64(
869 Counters->getValueType(), Counters, 0, Edge);
870 Phi->addIncoming(EdgeCounter, Pred);
873 // Skip phis, landingpads.
874 IRBuilder<> Builder(&*BB.getFirstInsertionPt());
875 Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Phi);
876 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
877 Builder.CreateStore(Count, Phi);
879 Instruction *TI = BB.getTerminator();
880 if (isa<ReturnInst>(TI)) {
881 auto It = EdgeToCounter.find({&BB, nullptr});
882 assert(It != EdgeToCounter.end());
883 const unsigned Edge = It->second;
884 Value *Counter = Builder.CreateConstInBoundsGEP2_64(
885 Counters->getValueType(), Counters, 0, Edge);
886 Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Counter);
887 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
888 Builder.CreateStore(Count, Counter);
894 Function *WriteoutF = insertCounterWriteout(CountersBySP);
895 Function *ResetF = insertReset(CountersBySP);
896 Function *FlushF = insertFlush(ResetF);
898 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
899 // be executed at exit and the "__llvm_gcov_flush" function to be executed
900 // when "__gcov_flush" is called.
901 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
902 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
903 "__llvm_gcov_init", M);
904 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
905 F->setLinkage(GlobalValue::InternalLinkage);
906 F->addFnAttr(Attribute::NoInline);
907 if (Options.NoRedZone)
908 F->addFnAttr(Attribute::NoRedZone);
910 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
911 IRBuilder<> Builder(BB);
913 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
914 Type *Params[] = {PointerType::get(FTy, 0), PointerType::get(FTy, 0),
915 PointerType::get(FTy, 0)};
916 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
918 // Initialize the environment and register the local writeout, flush and
920 FunctionCallee GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
921 Builder.CreateCall(GCOVInit, {WriteoutF, FlushF, ResetF});
922 Builder.CreateRetVoid();
924 appendToGlobalCtors(*M, F, 0);
930 FunctionCallee GCOVProfiler::getStartFileFunc(const TargetLibraryInfo *TLI) {
932 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
933 Type::getInt8PtrTy(*Ctx), // const char version[4]
934 Type::getInt32Ty(*Ctx), // uint32_t checksum
936 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
938 if (auto AK = TLI->getExtAttrForI32Param(false))
939 AL = AL.addParamAttribute(*Ctx, 2, AK);
940 FunctionCallee Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy, AL);
944 FunctionCallee GCOVProfiler::getEmitFunctionFunc(const TargetLibraryInfo *TLI) {
946 Type::getInt32Ty(*Ctx), // uint32_t ident
947 Type::getInt8PtrTy(*Ctx), // const char *function_name
948 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
949 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
950 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
952 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
954 if (auto AK = TLI->getExtAttrForI32Param(false)) {
955 AL = AL.addParamAttribute(*Ctx, 0, AK);
956 AL = AL.addParamAttribute(*Ctx, 2, AK);
957 AL = AL.addParamAttribute(*Ctx, 3, AK);
958 AL = AL.addParamAttribute(*Ctx, 4, AK);
960 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
963 FunctionCallee GCOVProfiler::getEmitArcsFunc(const TargetLibraryInfo *TLI) {
965 Type::getInt32Ty(*Ctx), // uint32_t num_counters
966 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
968 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
970 if (auto AK = TLI->getExtAttrForI32Param(false))
971 AL = AL.addParamAttribute(*Ctx, 0, AK);
972 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy, AL);
975 FunctionCallee GCOVProfiler::getSummaryInfoFunc() {
976 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
977 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
980 FunctionCallee GCOVProfiler::getEndFileFunc() {
981 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
982 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
985 Function *GCOVProfiler::insertCounterWriteout(
986 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
987 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
988 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
990 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
991 "__llvm_gcov_writeout", M);
992 WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
993 WriteoutF->addFnAttr(Attribute::NoInline);
994 if (Options.NoRedZone)
995 WriteoutF->addFnAttr(Attribute::NoRedZone);
997 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
998 IRBuilder<> Builder(BB);
1000 auto *TLI = &GetTLI(*WriteoutF);
1002 FunctionCallee StartFile = getStartFileFunc(TLI);
1003 FunctionCallee EmitFunction = getEmitFunctionFunc(TLI);
1004 FunctionCallee EmitArcs = getEmitArcsFunc(TLI);
1005 FunctionCallee SummaryInfo = getSummaryInfoFunc();
1006 FunctionCallee EndFile = getEndFileFunc();
1008 NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
1010 Builder.CreateRetVoid();
1014 // Collect the relevant data into a large constant data structure that we can
1015 // walk to write out everything.
1016 StructType *StartFileCallArgsTy = StructType::create(
1017 {Builder.getInt8PtrTy(), Builder.getInt8PtrTy(), Builder.getInt32Ty()});
1018 StructType *EmitFunctionCallArgsTy = StructType::create(
1019 {Builder.getInt32Ty(), Builder.getInt8PtrTy(), Builder.getInt32Ty(),
1020 Builder.getInt8Ty(), Builder.getInt32Ty()});
1021 StructType *EmitArcsCallArgsTy = StructType::create(
1022 {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
1023 StructType *FileInfoTy =
1024 StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
1025 EmitFunctionCallArgsTy->getPointerTo(),
1026 EmitArcsCallArgsTy->getPointerTo()});
1028 Constant *Zero32 = Builder.getInt32(0);
1029 // Build an explicit array of two zeros for use in ConstantExpr GEP building.
1030 Constant *TwoZero32s[] = {Zero32, Zero32};
1032 SmallVector<Constant *, 8> FileInfos;
1033 for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
1034 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
1036 // Skip module skeleton (and module) CUs.
1040 std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
1041 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
1042 auto *StartFileCallArgs = ConstantStruct::get(
1043 StartFileCallArgsTy, {Builder.CreateGlobalStringPtr(FilenameGcda),
1044 Builder.CreateGlobalStringPtr(ReversedVersion),
1045 Builder.getInt32(CfgChecksum)});
1047 SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
1048 SmallVector<Constant *, 8> EmitArcsCallArgsArray;
1049 for (int j : llvm::seq<int>(0, CountersBySP.size())) {
1050 auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
1051 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
1052 EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
1053 EmitFunctionCallArgsTy,
1054 {Builder.getInt32(j),
1055 Options.FunctionNamesInData
1056 ? Builder.CreateGlobalStringPtr(getFunctionName(SP))
1057 : Constant::getNullValue(Builder.getInt8PtrTy()),
1058 Builder.getInt32(FuncChecksum),
1059 Builder.getInt8(Options.UseCfgChecksum),
1060 Builder.getInt32(CfgChecksum)}));
1062 GlobalVariable *GV = CountersBySP[j].first;
1063 unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
1064 EmitArcsCallArgsArray.push_back(ConstantStruct::get(
1066 {Builder.getInt32(Arcs), ConstantExpr::getInBoundsGetElementPtr(
1067 GV->getValueType(), GV, TwoZero32s)}));
1069 // Create global arrays for the two emit calls.
1070 int CountersSize = CountersBySP.size();
1071 assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
1072 "Mismatched array size!");
1073 assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
1074 "Mismatched array size!");
1075 auto *EmitFunctionCallArgsArrayTy =
1076 ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
1077 auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
1078 *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
1079 GlobalValue::InternalLinkage,
1080 ConstantArray::get(EmitFunctionCallArgsArrayTy,
1081 EmitFunctionCallArgsArray),
1082 Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
1083 auto *EmitArcsCallArgsArrayTy =
1084 ArrayType::get(EmitArcsCallArgsTy, CountersSize);
1085 EmitFunctionCallArgsArrayGV->setUnnamedAddr(
1086 GlobalValue::UnnamedAddr::Global);
1087 auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
1088 *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
1089 GlobalValue::InternalLinkage,
1090 ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
1091 Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
1092 EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1094 FileInfos.push_back(ConstantStruct::get(
1096 {StartFileCallArgs, Builder.getInt32(CountersSize),
1097 ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy,
1098 EmitFunctionCallArgsArrayGV,
1100 ConstantExpr::getInBoundsGetElementPtr(
1101 EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)}));
1104 // If we didn't find anything to actually emit, bail on out.
1105 if (FileInfos.empty()) {
1106 Builder.CreateRetVoid();
1110 // To simplify code, we cap the number of file infos we write out to fit
1111 // easily in a 32-bit signed integer. This gives consistent behavior between
1112 // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
1113 // operations on 32-bit systems. It also seems unreasonable to try to handle
1114 // more than 2 billion files.
1115 if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
1116 FileInfos.resize(INT_MAX);
1118 // Create a global for the entire data structure so we can walk it more
1120 auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
1121 auto *FileInfoArrayGV = new GlobalVariable(
1122 *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
1123 ConstantArray::get(FileInfoArrayTy, FileInfos),
1124 "__llvm_internal_gcov_emit_file_info");
1125 FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1127 // Create the CFG for walking this data structure.
1128 auto *FileLoopHeader =
1129 BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
1130 auto *CounterLoopHeader =
1131 BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
1132 auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
1133 auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
1135 // We always have at least one file, so just branch to the header.
1136 Builder.CreateBr(FileLoopHeader);
1138 // The index into the files structure is our loop induction variable.
1139 Builder.SetInsertPoint(FileLoopHeader);
1141 Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1142 IV->addIncoming(Builder.getInt32(0), BB);
1143 auto *FileInfoPtr = Builder.CreateInBoundsGEP(
1144 FileInfoArrayTy, FileInfoArrayGV, {Builder.getInt32(0), IV});
1145 auto *StartFileCallArgsPtr =
1146 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 0);
1147 auto *StartFileCall = Builder.CreateCall(
1149 {Builder.CreateLoad(StartFileCallArgsTy->getElementType(0),
1150 Builder.CreateStructGEP(StartFileCallArgsTy,
1151 StartFileCallArgsPtr, 0)),
1152 Builder.CreateLoad(StartFileCallArgsTy->getElementType(1),
1153 Builder.CreateStructGEP(StartFileCallArgsTy,
1154 StartFileCallArgsPtr, 1)),
1155 Builder.CreateLoad(StartFileCallArgsTy->getElementType(2),
1156 Builder.CreateStructGEP(StartFileCallArgsTy,
1157 StartFileCallArgsPtr, 2))});
1158 if (auto AK = TLI->getExtAttrForI32Param(false))
1159 StartFileCall->addParamAttr(2, AK);
1161 Builder.CreateLoad(FileInfoTy->getElementType(1),
1162 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 1));
1163 auto *EmitFunctionCallArgsArray =
1164 Builder.CreateLoad(FileInfoTy->getElementType(2),
1165 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 2));
1166 auto *EmitArcsCallArgsArray =
1167 Builder.CreateLoad(FileInfoTy->getElementType(3),
1168 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 3));
1169 auto *EnterCounterLoopCond =
1170 Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
1171 Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
1173 Builder.SetInsertPoint(CounterLoopHeader);
1174 auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1175 JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
1176 auto *EmitFunctionCallArgsPtr = Builder.CreateInBoundsGEP(
1177 EmitFunctionCallArgsTy, EmitFunctionCallArgsArray, JV);
1178 auto *EmitFunctionCall = Builder.CreateCall(
1180 {Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(0),
1181 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1182 EmitFunctionCallArgsPtr, 0)),
1183 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(1),
1184 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1185 EmitFunctionCallArgsPtr, 1)),
1186 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(2),
1187 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1188 EmitFunctionCallArgsPtr, 2)),
1189 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(3),
1190 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1191 EmitFunctionCallArgsPtr, 3)),
1192 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(4),
1193 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1194 EmitFunctionCallArgsPtr,
1196 if (auto AK = TLI->getExtAttrForI32Param(false)) {
1197 EmitFunctionCall->addParamAttr(0, AK);
1198 EmitFunctionCall->addParamAttr(2, AK);
1199 EmitFunctionCall->addParamAttr(3, AK);
1200 EmitFunctionCall->addParamAttr(4, AK);
1202 auto *EmitArcsCallArgsPtr =
1203 Builder.CreateInBoundsGEP(EmitArcsCallArgsTy, EmitArcsCallArgsArray, JV);
1204 auto *EmitArcsCall = Builder.CreateCall(
1206 {Builder.CreateLoad(
1207 EmitArcsCallArgsTy->getElementType(0),
1208 Builder.CreateStructGEP(EmitArcsCallArgsTy, EmitArcsCallArgsPtr, 0)),
1209 Builder.CreateLoad(EmitArcsCallArgsTy->getElementType(1),
1210 Builder.CreateStructGEP(EmitArcsCallArgsTy,
1211 EmitArcsCallArgsPtr, 1))});
1212 if (auto AK = TLI->getExtAttrForI32Param(false))
1213 EmitArcsCall->addParamAttr(0, AK);
1214 auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1215 auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1216 Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1217 JV->addIncoming(NextJV, CounterLoopHeader);
1219 Builder.SetInsertPoint(FileLoopLatch);
1220 Builder.CreateCall(SummaryInfo, {});
1221 Builder.CreateCall(EndFile, {});
1222 auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1223 auto *FileLoopCond =
1224 Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1225 Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1226 IV->addIncoming(NextIV, FileLoopLatch);
1228 Builder.SetInsertPoint(ExitBB);
1229 Builder.CreateRetVoid();
1234 Function *GCOVProfiler::insertReset(
1235 ArrayRef<std::pair<GlobalVariable *, MDNode *>> CountersBySP) {
1236 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1237 Function *ResetF = M->getFunction("__llvm_gcov_reset");
1239 ResetF = Function::Create(FTy, GlobalValue::InternalLinkage,
1240 "__llvm_gcov_reset", M);
1242 ResetF->setLinkage(GlobalValue::InternalLinkage);
1243 ResetF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1244 ResetF->addFnAttr(Attribute::NoInline);
1245 if (Options.NoRedZone)
1246 ResetF->addFnAttr(Attribute::NoRedZone);
1248 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", ResetF);
1249 IRBuilder<> Builder(Entry);
1251 // Zero out the counters.
1252 for (const auto &I : CountersBySP) {
1253 GlobalVariable *GV = I.first;
1254 Constant *Null = Constant::getNullValue(GV->getValueType());
1255 Builder.CreateStore(Null, GV);
1258 Type *RetTy = ResetF->getReturnType();
1259 if (RetTy->isVoidTy())
1260 Builder.CreateRetVoid();
1261 else if (RetTy->isIntegerTy())
1262 // Used if __llvm_gcov_reset was implicitly declared.
1263 Builder.CreateRet(ConstantInt::get(RetTy, 0));
1265 report_fatal_error("invalid return type for __llvm_gcov_reset");
1270 Function *GCOVProfiler::insertFlush(Function *ResetF) {
1271 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1272 Function *FlushF = M->getFunction("__llvm_gcov_flush");
1274 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
1275 "__llvm_gcov_flush", M);
1277 FlushF->setLinkage(GlobalValue::InternalLinkage);
1278 FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1279 FlushF->addFnAttr(Attribute::NoInline);
1280 if (Options.NoRedZone)
1281 FlushF->addFnAttr(Attribute::NoRedZone);
1283 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
1285 // Write out the current counters.
1286 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1287 assert(WriteoutF && "Need to create the writeout function first!");
1289 IRBuilder<> Builder(Entry);
1290 Builder.CreateCall(WriteoutF, {});
1291 Builder.CreateCall(ResetF, {});
1293 Type *RetTy = FlushF->getReturnType();
1294 if (RetTy->isVoidTy())
1295 Builder.CreateRetVoid();
1296 else if (RetTy->isIntegerTy())
1297 // Used if __llvm_gcov_flush was implicitly declared.
1298 Builder.CreateRet(ConstantInt::get(RetTy, 0));
1300 report_fatal_error("invalid return type for __llvm_gcov_flush");