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/Pass.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Regex.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Instrumentation.h"
41 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
42 #include "llvm/Transforms/Utils/ModuleUtils.h"
49 #define DEBUG_TYPE "insert-gcov-profiling"
51 static cl::opt
<std::string
>
52 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden
,
54 static cl::opt
<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
55 cl::init(false), cl::Hidden
);
57 GCOVOptions
GCOVOptions::getDefault() {
59 Options
.EmitNotes
= true;
60 Options
.EmitData
= true;
61 Options
.UseCfgChecksum
= false;
62 Options
.NoRedZone
= false;
63 Options
.FunctionNamesInData
= true;
64 Options
.ExitBlockBeforeBody
= DefaultExitBlockBeforeBody
;
66 if (DefaultGCOVVersion
.size() != 4) {
67 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
70 memcpy(Options
.Version
, DefaultGCOVVersion
.c_str(), 4);
79 GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
80 GCOVProfiler(const GCOVOptions
&Opts
) : Options(Opts
) {
81 assert((Options
.EmitNotes
|| Options
.EmitData
) &&
82 "GCOVProfiler asked to do nothing?");
83 ReversedVersion
[0] = Options
.Version
[3];
84 ReversedVersion
[1] = Options
.Version
[2];
85 ReversedVersion
[2] = Options
.Version
[1];
86 ReversedVersion
[3] = Options
.Version
[0];
87 ReversedVersion
[4] = '\0';
89 bool runOnModule(Module
&M
, const TargetLibraryInfo
&TLI
);
92 // Create the .gcno files for the Module based on DebugInfo.
93 void emitProfileNotes();
95 // Modify the program to track transitions along edges and call into the
96 // profiling runtime to emit .gcda files when run.
97 bool emitProfileArcs();
99 bool isFunctionInstrumented(const Function
&F
);
100 std::vector
<Regex
> createRegexesFromString(StringRef RegexesStr
);
101 static bool doesFilenameMatchARegex(StringRef Filename
,
102 std::vector
<Regex
> &Regexes
);
104 // Get pointers to the functions in the runtime library.
105 FunctionCallee
getStartFileFunc();
106 FunctionCallee
getEmitFunctionFunc();
107 FunctionCallee
getEmitArcsFunc();
108 FunctionCallee
getSummaryInfoFunc();
109 FunctionCallee
getEndFileFunc();
111 // Add the function to write out all our counters to the global destructor
114 insertCounterWriteout(ArrayRef
<std::pair
<GlobalVariable
*, MDNode
*>>);
115 Function
*insertFlush(ArrayRef
<std::pair
<GlobalVariable
*, MDNode
*>>);
117 void AddFlushBeforeForkAndExec();
119 enum class GCovFileType
{ GCNO
, GCDA
};
120 std::string
mangleName(const DICompileUnit
*CU
, GCovFileType FileType
);
124 // Reversed, NUL-terminated copy of Options.Version.
125 char ReversedVersion
[5];
126 // Checksum, produced by hash of EdgeDestinations
127 SmallVector
<uint32_t, 4> FileChecksums
;
130 const TargetLibraryInfo
*TLI
;
132 SmallVector
<std::unique_ptr
<GCOVFunction
>, 16> Funcs
;
133 std::vector
<Regex
> FilterRe
;
134 std::vector
<Regex
> ExcludeRe
;
135 StringMap
<bool> InstrumentedFiles
;
138 class GCOVProfilerLegacyPass
: public ModulePass
{
141 GCOVProfilerLegacyPass()
142 : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
143 GCOVProfilerLegacyPass(const GCOVOptions
&Opts
)
144 : ModulePass(ID
), Profiler(Opts
) {
145 initializeGCOVProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
147 StringRef
getPassName() const override
{ return "GCOV Profiler"; }
149 bool runOnModule(Module
&M
) override
{
150 auto &TLI
= getAnalysis
<TargetLibraryInfoWrapperPass
>().getTLI();
151 return Profiler
.runOnModule(M
, TLI
);
154 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
155 AU
.addRequired
<TargetLibraryInfoWrapperPass
>();
159 GCOVProfiler Profiler
;
163 char GCOVProfilerLegacyPass::ID
= 0;
164 INITIALIZE_PASS_BEGIN(
165 GCOVProfilerLegacyPass
, "insert-gcov-profiling",
166 "Insert instrumentation for GCOV profiling", false, false)
167 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass
)
169 GCOVProfilerLegacyPass
, "insert-gcov-profiling",
170 "Insert instrumentation for GCOV profiling", false, false)
172 ModulePass
*llvm::createGCOVProfilerPass(const GCOVOptions
&Options
) {
173 return new GCOVProfilerLegacyPass(Options
);
176 static StringRef
getFunctionName(const DISubprogram
*SP
) {
177 if (!SP
->getLinkageName().empty())
178 return SP
->getLinkageName();
179 return SP
->getName();
182 /// Extract a filename for a DISubprogram.
184 /// Prefer relative paths in the coverage notes. Clang also may split
185 /// up absolute paths into a directory and filename component. When
186 /// the relative path doesn't exist, reconstruct the absolute path.
187 static SmallString
<128> getFilename(const DISubprogram
*SP
) {
188 SmallString
<128> Path
;
189 StringRef RelPath
= SP
->getFilename();
190 if (sys::fs::exists(RelPath
))
193 sys::path::append(Path
, SP
->getDirectory(), SP
->getFilename());
200 static const char *const LinesTag
;
201 static const char *const FunctionTag
;
202 static const char *const BlockTag
;
203 static const char *const EdgeTag
;
205 GCOVRecord() = default;
207 void writeBytes(const char *Bytes
, int Size
) {
208 os
->write(Bytes
, Size
);
211 void write(uint32_t i
) {
212 writeBytes(reinterpret_cast<char*>(&i
), 4);
215 // Returns the length measured in 4-byte blocks that will be used to
216 // represent this string in a GCOV file
217 static unsigned lengthOfGCOVString(StringRef s
) {
218 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
219 // padding out to the next 4-byte word. The length is measured in 4-byte
220 // words including padding, not bytes of actual string.
221 return (s
.size() / 4) + 1;
224 void writeGCOVString(StringRef s
) {
225 uint32_t Len
= lengthOfGCOVString(s
);
227 writeBytes(s
.data(), s
.size());
229 // Write 1 to 4 bytes of NUL padding.
230 assert((unsigned)(4 - (s
.size() % 4)) > 0);
231 assert((unsigned)(4 - (s
.size() % 4)) <= 4);
232 writeBytes("\0\0\0\0", 4 - (s
.size() % 4));
237 const char *const GCOVRecord::LinesTag
= "\0\0\x45\x01";
238 const char *const GCOVRecord::FunctionTag
= "\0\0\0\1";
239 const char *const GCOVRecord::BlockTag
= "\0\0\x41\x01";
240 const char *const GCOVRecord::EdgeTag
= "\0\0\x43\x01";
245 // Constructed only by requesting it from a GCOVBlock, this object stores a
246 // list of line numbers and a single filename, representing lines that belong
248 class GCOVLines
: public GCOVRecord
{
250 void addLine(uint32_t Line
) {
251 assert(Line
!= 0 && "Line zero is not a valid real line number.");
252 Lines
.push_back(Line
);
255 uint32_t length() const {
256 // Here 2 = 1 for string length + 1 for '0' id#.
257 return lengthOfGCOVString(Filename
) + 2 + Lines
.size();
262 writeGCOVString(Filename
);
263 for (int i
= 0, e
= Lines
.size(); i
!= e
; ++i
)
267 GCOVLines(StringRef F
, raw_ostream
*os
)
273 std::string Filename
;
274 SmallVector
<uint32_t, 32> Lines
;
278 // Represent a basic block in GCOV. Each block has a unique number in the
279 // function, number of lines belonging to each block, and a set of edges to
281 class GCOVBlock
: public GCOVRecord
{
283 GCOVLines
&getFile(StringRef Filename
) {
284 return LinesByFile
.try_emplace(Filename
, Filename
, os
).first
->second
;
287 void addEdge(GCOVBlock
&Successor
) {
288 OutEdges
.push_back(&Successor
);
293 SmallVector
<StringMapEntry
<GCOVLines
> *, 32> SortedLinesByFile
;
294 for (auto &I
: LinesByFile
) {
295 Len
+= I
.second
.length();
296 SortedLinesByFile
.push_back(&I
);
299 writeBytes(LinesTag
, 4);
303 llvm::sort(SortedLinesByFile
, [](StringMapEntry
<GCOVLines
> *LHS
,
304 StringMapEntry
<GCOVLines
> *RHS
) {
305 return LHS
->getKey() < RHS
->getKey();
307 for (auto &I
: SortedLinesByFile
)
308 I
->getValue().writeOut();
313 GCOVBlock(const GCOVBlock
&RHS
) : GCOVRecord(RHS
), Number(RHS
.Number
) {
314 // Only allow copy before edges and lines have been added. After that,
315 // there are inter-block pointers (eg: edges) that won't take kindly to
316 // blocks being copied or moved around.
317 assert(LinesByFile
.empty());
318 assert(OutEdges
.empty());
322 friend class GCOVFunction
;
324 GCOVBlock(uint32_t Number
, raw_ostream
*os
)
330 StringMap
<GCOVLines
> LinesByFile
;
331 SmallVector
<GCOVBlock
*, 4> OutEdges
;
334 // A function has a unique identifier, a checksum (we leave as zero) and a
335 // set of blocks and a map of edges between blocks. This is the only GCOV
336 // object users can construct, the blocks and lines will be rooted here.
337 class GCOVFunction
: public GCOVRecord
{
339 GCOVFunction(const DISubprogram
*SP
, Function
*F
, raw_ostream
*os
,
340 uint32_t Ident
, bool UseCfgChecksum
, bool ExitBlockBeforeBody
)
341 : SP(SP
), Ident(Ident
), UseCfgChecksum(UseCfgChecksum
), CfgChecksum(0),
345 LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP
) << "\n");
348 for (auto &BB
: *F
) {
349 // Skip index 1 if it's assigned to the ReturnBlock.
350 if (i
== 1 && ExitBlockBeforeBody
)
352 Blocks
.insert(std::make_pair(&BB
, GCOVBlock(i
++, os
)));
354 if (!ExitBlockBeforeBody
)
355 ReturnBlock
.Number
= i
;
357 std::string FunctionNameAndLine
;
358 raw_string_ostream
FNLOS(FunctionNameAndLine
);
359 FNLOS
<< getFunctionName(SP
) << SP
->getLine();
361 FuncChecksum
= hash_value(FunctionNameAndLine
);
364 GCOVBlock
&getBlock(BasicBlock
*BB
) {
365 return Blocks
.find(BB
)->second
;
368 GCOVBlock
&getReturnBlock() {
372 std::string
getEdgeDestinations() {
373 std::string EdgeDestinations
;
374 raw_string_ostream
EDOS(EdgeDestinations
);
375 Function
*F
= Blocks
.begin()->first
->getParent();
376 for (BasicBlock
&I
: *F
) {
377 GCOVBlock
&Block
= getBlock(&I
);
378 for (int i
= 0, e
= Block
.OutEdges
.size(); i
!= e
; ++i
)
379 EDOS
<< Block
.OutEdges
[i
]->Number
;
381 return EdgeDestinations
;
384 uint32_t getFuncChecksum() {
388 void setCfgChecksum(uint32_t Checksum
) {
389 CfgChecksum
= Checksum
;
393 writeBytes(FunctionTag
, 4);
394 SmallString
<128> Filename
= getFilename(SP
);
395 uint32_t BlockLen
= 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP
)) +
396 1 + lengthOfGCOVString(Filename
) + 1;
404 writeGCOVString(getFunctionName(SP
));
405 writeGCOVString(Filename
);
406 write(SP
->getLine());
408 // Emit count of blocks.
409 writeBytes(BlockTag
, 4);
410 write(Blocks
.size() + 1);
411 for (int i
= 0, e
= Blocks
.size() + 1; i
!= e
; ++i
) {
412 write(0); // No flags on our blocks.
414 LLVM_DEBUG(dbgs() << Blocks
.size() << " blocks.\n");
416 // Emit edges between blocks.
417 if (Blocks
.empty()) return;
418 Function
*F
= Blocks
.begin()->first
->getParent();
419 for (BasicBlock
&I
: *F
) {
420 GCOVBlock
&Block
= getBlock(&I
);
421 if (Block
.OutEdges
.empty()) continue;
423 writeBytes(EdgeTag
, 4);
424 write(Block
.OutEdges
.size() * 2 + 1);
426 for (int i
= 0, e
= Block
.OutEdges
.size(); i
!= e
; ++i
) {
427 LLVM_DEBUG(dbgs() << Block
.Number
<< " -> "
428 << Block
.OutEdges
[i
]->Number
<< "\n");
429 write(Block
.OutEdges
[i
]->Number
);
430 write(0); // no flags
434 // Emit lines for each block.
435 for (BasicBlock
&I
: *F
)
436 getBlock(&I
).writeOut();
440 const DISubprogram
*SP
;
442 uint32_t FuncChecksum
;
444 uint32_t CfgChecksum
;
445 DenseMap
<BasicBlock
*, GCOVBlock
> Blocks
;
446 GCOVBlock ReturnBlock
;
450 // RegexesStr is a string containing differents regex separated by a semi-colon.
451 // For example "foo\..*$;bar\..*$".
452 std::vector
<Regex
> GCOVProfiler::createRegexesFromString(StringRef RegexesStr
) {
453 std::vector
<Regex
> Regexes
;
454 while (!RegexesStr
.empty()) {
455 std::pair
<StringRef
, StringRef
> HeadTail
= RegexesStr
.split(';');
456 if (!HeadTail
.first
.empty()) {
457 Regex
Re(HeadTail
.first
);
459 if (!Re
.isValid(Err
)) {
460 Ctx
->emitError(Twine("Regex ") + HeadTail
.first
+
461 " is not valid: " + Err
);
463 Regexes
.emplace_back(std::move(Re
));
465 RegexesStr
= HeadTail
.second
;
470 bool GCOVProfiler::doesFilenameMatchARegex(StringRef Filename
,
471 std::vector
<Regex
> &Regexes
) {
472 for (Regex
&Re
: Regexes
) {
473 if (Re
.match(Filename
)) {
480 bool GCOVProfiler::isFunctionInstrumented(const Function
&F
) {
481 if (FilterRe
.empty() && ExcludeRe
.empty()) {
484 SmallString
<128> Filename
= getFilename(F
.getSubprogram());
485 auto It
= InstrumentedFiles
.find(Filename
);
486 if (It
!= InstrumentedFiles
.end()) {
490 SmallString
<256> RealPath
;
491 StringRef RealFilename
;
494 // /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/*.h so for
495 // such a case we must get the real_path.
496 if (sys::fs::real_path(Filename
, RealPath
)) {
497 // real_path can fail with path like "foo.c".
498 RealFilename
= Filename
;
500 RealFilename
= RealPath
;
503 bool ShouldInstrument
;
504 if (FilterRe
.empty()) {
505 ShouldInstrument
= !doesFilenameMatchARegex(RealFilename
, ExcludeRe
);
506 } else if (ExcludeRe
.empty()) {
507 ShouldInstrument
= doesFilenameMatchARegex(RealFilename
, FilterRe
);
509 ShouldInstrument
= doesFilenameMatchARegex(RealFilename
, FilterRe
) &&
510 !doesFilenameMatchARegex(RealFilename
, ExcludeRe
);
512 InstrumentedFiles
[Filename
] = ShouldInstrument
;
513 return ShouldInstrument
;
516 std::string
GCOVProfiler::mangleName(const DICompileUnit
*CU
,
517 GCovFileType OutputType
) {
518 bool Notes
= OutputType
== GCovFileType::GCNO
;
520 if (NamedMDNode
*GCov
= M
->getNamedMetadata("llvm.gcov")) {
521 for (int i
= 0, e
= GCov
->getNumOperands(); i
!= e
; ++i
) {
522 MDNode
*N
= GCov
->getOperand(i
);
523 bool ThreeElement
= N
->getNumOperands() == 3;
524 if (!ThreeElement
&& N
->getNumOperands() != 2)
526 if (dyn_cast
<MDNode
>(N
->getOperand(ThreeElement
? 2 : 1)) != CU
)
530 // These nodes have no mangling to apply, it's stored mangled in the
532 MDString
*NotesFile
= dyn_cast
<MDString
>(N
->getOperand(0));
533 MDString
*DataFile
= dyn_cast
<MDString
>(N
->getOperand(1));
534 if (!NotesFile
|| !DataFile
)
536 return Notes
? NotesFile
->getString() : DataFile
->getString();
539 MDString
*GCovFile
= dyn_cast
<MDString
>(N
->getOperand(0));
543 SmallString
<128> Filename
= GCovFile
->getString();
544 sys::path::replace_extension(Filename
, Notes
? "gcno" : "gcda");
545 return Filename
.str();
549 SmallString
<128> Filename
= CU
->getFilename();
550 sys::path::replace_extension(Filename
, Notes
? "gcno" : "gcda");
551 StringRef FName
= sys::path::filename(Filename
);
552 SmallString
<128> CurPath
;
553 if (sys::fs::current_path(CurPath
)) return FName
;
554 sys::path::append(CurPath
, FName
);
555 return CurPath
.str();
558 bool GCOVProfiler::runOnModule(Module
&M
, const TargetLibraryInfo
&TLI
) {
561 Ctx
= &M
.getContext();
563 AddFlushBeforeForkAndExec();
565 FilterRe
= createRegexesFromString(Options
.Filter
);
566 ExcludeRe
= createRegexesFromString(Options
.Exclude
);
568 if (Options
.EmitNotes
) emitProfileNotes();
569 if (Options
.EmitData
) return emitProfileArcs();
573 PreservedAnalyses
GCOVProfilerPass::run(Module
&M
,
574 ModuleAnalysisManager
&AM
) {
576 GCOVProfiler
Profiler(GCOVOpts
);
578 auto &TLI
= AM
.getResult
<TargetLibraryAnalysis
>(M
);
579 if (!Profiler
.runOnModule(M
, TLI
))
580 return PreservedAnalyses::all();
582 return PreservedAnalyses::none();
585 static bool functionHasLines(Function
&F
) {
586 // Check whether this function actually has any source lines. Not only
587 // do these waste space, they also can crash gcov.
590 // Debug intrinsic locations correspond to the location of the
591 // declaration, not necessarily any statements or expressions.
592 if (isa
<DbgInfoIntrinsic
>(&I
)) continue;
594 const DebugLoc
&Loc
= I
.getDebugLoc();
598 // Artificial lines such as calls to the global constructors.
599 if (Loc
.getLine() == 0) continue;
607 static bool isUsingScopeBasedEH(Function
&F
) {
608 if (!F
.hasPersonalityFn()) return false;
610 EHPersonality Personality
= classifyEHPersonality(F
.getPersonalityFn());
611 return isScopedEHPersonality(Personality
);
614 static bool shouldKeepInEntry(BasicBlock::iterator It
) {
615 if (isa
<AllocaInst
>(*It
)) return true;
616 if (isa
<DbgInfoIntrinsic
>(*It
)) return true;
617 if (auto *II
= dyn_cast
<IntrinsicInst
>(It
)) {
618 if (II
->getIntrinsicID() == llvm::Intrinsic::localescape
) return true;
624 void GCOVProfiler::AddFlushBeforeForkAndExec() {
625 SmallVector
<Instruction
*, 2> ForkAndExecs
;
626 for (auto &F
: M
->functions()) {
627 for (auto &I
: instructions(F
)) {
628 if (CallInst
*CI
= dyn_cast
<CallInst
>(&I
)) {
629 if (Function
*Callee
= CI
->getCalledFunction()) {
631 if (TLI
->getLibFunc(*Callee
, LF
) &&
632 (LF
== LibFunc_fork
|| LF
== LibFunc_execl
||
633 LF
== LibFunc_execle
|| LF
== LibFunc_execlp
||
634 LF
== LibFunc_execv
|| LF
== LibFunc_execvp
||
635 LF
== LibFunc_execve
|| LF
== LibFunc_execvpe
||
636 LF
== LibFunc_execvP
)) {
637 ForkAndExecs
.push_back(&I
);
644 // We need to split the block after the fork/exec call
645 // because else the counters for the lines after will be
646 // the same as before the call.
647 for (auto I
: ForkAndExecs
) {
648 IRBuilder
<> Builder(I
);
649 FunctionType
*FTy
= FunctionType::get(Builder
.getVoidTy(), {}, false);
650 FunctionCallee GCOVFlush
= M
->getOrInsertFunction("__gcov_flush", FTy
);
651 Builder
.CreateCall(GCOVFlush
);
652 I
->getParent()->splitBasicBlock(I
);
656 void GCOVProfiler::emitProfileNotes() {
657 NamedMDNode
*CU_Nodes
= M
->getNamedMetadata("llvm.dbg.cu");
658 if (!CU_Nodes
) return;
660 for (unsigned i
= 0, e
= CU_Nodes
->getNumOperands(); i
!= e
; ++i
) {
661 // Each compile unit gets its own .gcno file. This means that whether we run
662 // this pass over the original .o's as they're produced, or run it after
663 // LTO, we'll generate the same .gcno files.
665 auto *CU
= cast
<DICompileUnit
>(CU_Nodes
->getOperand(i
));
667 // Skip module skeleton (and module) CUs.
672 raw_fd_ostream
out(mangleName(CU
, GCovFileType::GCNO
), EC
, sys::fs::F_None
);
674 Ctx
->emitError(Twine("failed to open coverage notes file for writing: ") +
679 std::string EdgeDestinations
;
681 unsigned FunctionIdent
= 0;
682 for (auto &F
: M
->functions()) {
683 DISubprogram
*SP
= F
.getSubprogram();
685 if (!functionHasLines(F
) || !isFunctionInstrumented(F
))
687 // TODO: Functions using scope-based EH are currently not supported.
688 if (isUsingScopeBasedEH(F
)) continue;
690 // gcov expects every function to start with an entry block that has a
691 // single successor, so split the entry block to make sure of that.
692 BasicBlock
&EntryBlock
= F
.getEntryBlock();
693 BasicBlock::iterator It
= EntryBlock
.begin();
694 while (shouldKeepInEntry(It
))
696 EntryBlock
.splitBasicBlock(It
);
698 Funcs
.push_back(make_unique
<GCOVFunction
>(SP
, &F
, &out
, FunctionIdent
++,
699 Options
.UseCfgChecksum
,
700 Options
.ExitBlockBeforeBody
));
701 GCOVFunction
&Func
= *Funcs
.back();
703 // Add the function line number to the lines of the entry block
704 // to have a counter for the function definition.
705 uint32_t Line
= SP
->getLine();
706 auto Filename
= getFilename(SP
);
707 Func
.getBlock(&EntryBlock
).getFile(Filename
).addLine(Line
);
710 GCOVBlock
&Block
= Func
.getBlock(&BB
);
711 Instruction
*TI
= BB
.getTerminator();
712 if (int successors
= TI
->getNumSuccessors()) {
713 for (int i
= 0; i
!= successors
; ++i
) {
714 Block
.addEdge(Func
.getBlock(TI
->getSuccessor(i
)));
716 } else if (isa
<ReturnInst
>(TI
)) {
717 Block
.addEdge(Func
.getReturnBlock());
721 // Debug intrinsic locations correspond to the location of the
722 // declaration, not necessarily any statements or expressions.
723 if (isa
<DbgInfoIntrinsic
>(&I
)) continue;
725 const DebugLoc
&Loc
= I
.getDebugLoc();
729 // Artificial lines such as calls to the global constructors.
730 if (Loc
.getLine() == 0 || Loc
.isImplicitCode())
733 if (Line
== Loc
.getLine()) continue;
734 Line
= Loc
.getLine();
735 if (SP
!= getDISubprogram(Loc
.getScope()))
738 GCOVLines
&Lines
= Block
.getFile(Filename
);
739 Lines
.addLine(Loc
.getLine());
743 EdgeDestinations
+= Func
.getEdgeDestinations();
746 FileChecksums
.push_back(hash_value(EdgeDestinations
));
747 out
.write("oncg", 4);
748 out
.write(ReversedVersion
, 4);
749 out
.write(reinterpret_cast<char*>(&FileChecksums
.back()), 4);
751 for (auto &Func
: Funcs
) {
752 Func
->setCfgChecksum(FileChecksums
.back());
756 out
.write("\0\0\0\0\0\0\0\0", 8); // EOF
761 bool GCOVProfiler::emitProfileArcs() {
762 NamedMDNode
*CU_Nodes
= M
->getNamedMetadata("llvm.dbg.cu");
763 if (!CU_Nodes
) return false;
766 for (unsigned i
= 0, e
= CU_Nodes
->getNumOperands(); i
!= e
; ++i
) {
767 SmallVector
<std::pair
<GlobalVariable
*, MDNode
*>, 8> CountersBySP
;
768 for (auto &F
: M
->functions()) {
769 DISubprogram
*SP
= F
.getSubprogram();
771 if (!functionHasLines(F
) || !isFunctionInstrumented(F
))
773 // TODO: Functions using scope-based EH are currently not supported.
774 if (isUsingScopeBasedEH(F
)) continue;
775 if (!Result
) Result
= true;
777 DenseMap
<std::pair
<BasicBlock
*, BasicBlock
*>, unsigned> EdgeToCounter
;
780 Instruction
*TI
= BB
.getTerminator();
781 if (isa
<ReturnInst
>(TI
)) {
782 EdgeToCounter
[{&BB
, nullptr}] = Edges
++;
784 for (BasicBlock
*Succ
: successors(TI
)) {
785 EdgeToCounter
[{&BB
, Succ
}] = Edges
++;
790 ArrayType
*CounterTy
=
791 ArrayType::get(Type::getInt64Ty(*Ctx
), Edges
);
792 GlobalVariable
*Counters
=
793 new GlobalVariable(*M
, CounterTy
, false,
794 GlobalValue::InternalLinkage
,
795 Constant::getNullValue(CounterTy
),
797 CountersBySP
.push_back(std::make_pair(Counters
, SP
));
799 // If a BB has several predecessors, use a PHINode to select
800 // the correct counter.
802 const unsigned EdgeCount
=
803 std::distance(pred_begin(&BB
), pred_end(&BB
));
805 // The phi node must be at the begin of the BB.
806 IRBuilder
<> BuilderForPhi(&*BB
.begin());
807 Type
*Int64PtrTy
= Type::getInt64PtrTy(*Ctx
);
808 PHINode
*Phi
= BuilderForPhi
.CreatePHI(Int64PtrTy
, EdgeCount
);
809 for (BasicBlock
*Pred
: predecessors(&BB
)) {
810 auto It
= EdgeToCounter
.find({Pred
, &BB
});
811 assert(It
!= EdgeToCounter
.end());
812 const unsigned Edge
= It
->second
;
813 Value
*EdgeCounter
= BuilderForPhi
.CreateConstInBoundsGEP2_64(
814 Counters
->getValueType(), Counters
, 0, Edge
);
815 Phi
->addIncoming(EdgeCounter
, Pred
);
818 // Skip phis, landingpads.
819 IRBuilder
<> Builder(&*BB
.getFirstInsertionPt());
820 Value
*Count
= Builder
.CreateLoad(Builder
.getInt64Ty(), Phi
);
821 Count
= Builder
.CreateAdd(Count
, Builder
.getInt64(1));
822 Builder
.CreateStore(Count
, Phi
);
824 Instruction
*TI
= BB
.getTerminator();
825 if (isa
<ReturnInst
>(TI
)) {
826 auto It
= EdgeToCounter
.find({&BB
, nullptr});
827 assert(It
!= EdgeToCounter
.end());
828 const unsigned Edge
= It
->second
;
829 Value
*Counter
= Builder
.CreateConstInBoundsGEP2_64(
830 Counters
->getValueType(), Counters
, 0, Edge
);
831 Value
*Count
= Builder
.CreateLoad(Builder
.getInt64Ty(), Counter
);
832 Count
= Builder
.CreateAdd(Count
, Builder
.getInt64(1));
833 Builder
.CreateStore(Count
, Counter
);
839 Function
*WriteoutF
= insertCounterWriteout(CountersBySP
);
840 Function
*FlushF
= insertFlush(CountersBySP
);
842 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
843 // be executed at exit and the "__llvm_gcov_flush" function to be executed
844 // when "__gcov_flush" is called.
845 FunctionType
*FTy
= FunctionType::get(Type::getVoidTy(*Ctx
), false);
846 Function
*F
= Function::Create(FTy
, GlobalValue::InternalLinkage
,
847 "__llvm_gcov_init", M
);
848 F
->setUnnamedAddr(GlobalValue::UnnamedAddr::Global
);
849 F
->setLinkage(GlobalValue::InternalLinkage
);
850 F
->addFnAttr(Attribute::NoInline
);
851 if (Options
.NoRedZone
)
852 F
->addFnAttr(Attribute::NoRedZone
);
854 BasicBlock
*BB
= BasicBlock::Create(*Ctx
, "entry", F
);
855 IRBuilder
<> Builder(BB
);
857 FTy
= FunctionType::get(Type::getVoidTy(*Ctx
), false);
859 PointerType::get(FTy
, 0),
860 PointerType::get(FTy
, 0)
862 FTy
= FunctionType::get(Builder
.getVoidTy(), Params
, false);
864 // Initialize the environment and register the local writeout and flush
866 FunctionCallee GCOVInit
= M
->getOrInsertFunction("llvm_gcov_init", FTy
);
867 Builder
.CreateCall(GCOVInit
, {WriteoutF
, FlushF
});
868 Builder
.CreateRetVoid();
870 appendToGlobalCtors(*M
, F
, 0);
876 FunctionCallee
GCOVProfiler::getStartFileFunc() {
878 Type::getInt8PtrTy(*Ctx
), // const char *orig_filename
879 Type::getInt8PtrTy(*Ctx
), // const char version[4]
880 Type::getInt32Ty(*Ctx
), // uint32_t checksum
882 FunctionType
*FTy
= FunctionType::get(Type::getVoidTy(*Ctx
), Args
, false);
884 if (auto AK
= TLI
->getExtAttrForI32Param(false))
885 AL
= AL
.addParamAttribute(*Ctx
, 2, AK
);
886 FunctionCallee Res
= M
->getOrInsertFunction("llvm_gcda_start_file", FTy
, AL
);
890 FunctionCallee
GCOVProfiler::getEmitFunctionFunc() {
892 Type::getInt32Ty(*Ctx
), // uint32_t ident
893 Type::getInt8PtrTy(*Ctx
), // const char *function_name
894 Type::getInt32Ty(*Ctx
), // uint32_t func_checksum
895 Type::getInt8Ty(*Ctx
), // uint8_t use_extra_checksum
896 Type::getInt32Ty(*Ctx
), // uint32_t cfg_checksum
898 FunctionType
*FTy
= FunctionType::get(Type::getVoidTy(*Ctx
), Args
, false);
900 if (auto AK
= TLI
->getExtAttrForI32Param(false)) {
901 AL
= AL
.addParamAttribute(*Ctx
, 0, AK
);
902 AL
= AL
.addParamAttribute(*Ctx
, 2, AK
);
903 AL
= AL
.addParamAttribute(*Ctx
, 3, AK
);
904 AL
= AL
.addParamAttribute(*Ctx
, 4, AK
);
906 return M
->getOrInsertFunction("llvm_gcda_emit_function", FTy
);
909 FunctionCallee
GCOVProfiler::getEmitArcsFunc() {
911 Type::getInt32Ty(*Ctx
), // uint32_t num_counters
912 Type::getInt64PtrTy(*Ctx
), // uint64_t *counters
914 FunctionType
*FTy
= FunctionType::get(Type::getVoidTy(*Ctx
), Args
, false);
916 if (auto AK
= TLI
->getExtAttrForI32Param(false))
917 AL
= AL
.addParamAttribute(*Ctx
, 0, AK
);
918 return M
->getOrInsertFunction("llvm_gcda_emit_arcs", FTy
, AL
);
921 FunctionCallee
GCOVProfiler::getSummaryInfoFunc() {
922 FunctionType
*FTy
= FunctionType::get(Type::getVoidTy(*Ctx
), false);
923 return M
->getOrInsertFunction("llvm_gcda_summary_info", FTy
);
926 FunctionCallee
GCOVProfiler::getEndFileFunc() {
927 FunctionType
*FTy
= FunctionType::get(Type::getVoidTy(*Ctx
), false);
928 return M
->getOrInsertFunction("llvm_gcda_end_file", FTy
);
931 Function
*GCOVProfiler::insertCounterWriteout(
932 ArrayRef
<std::pair
<GlobalVariable
*, MDNode
*> > CountersBySP
) {
933 FunctionType
*WriteoutFTy
= FunctionType::get(Type::getVoidTy(*Ctx
), false);
934 Function
*WriteoutF
= M
->getFunction("__llvm_gcov_writeout");
936 WriteoutF
= Function::Create(WriteoutFTy
, GlobalValue::InternalLinkage
,
937 "__llvm_gcov_writeout", M
);
938 WriteoutF
->setUnnamedAddr(GlobalValue::UnnamedAddr::Global
);
939 WriteoutF
->addFnAttr(Attribute::NoInline
);
940 if (Options
.NoRedZone
)
941 WriteoutF
->addFnAttr(Attribute::NoRedZone
);
943 BasicBlock
*BB
= BasicBlock::Create(*Ctx
, "entry", WriteoutF
);
944 IRBuilder
<> Builder(BB
);
946 FunctionCallee StartFile
= getStartFileFunc();
947 FunctionCallee EmitFunction
= getEmitFunctionFunc();
948 FunctionCallee EmitArcs
= getEmitArcsFunc();
949 FunctionCallee SummaryInfo
= getSummaryInfoFunc();
950 FunctionCallee EndFile
= getEndFileFunc();
952 NamedMDNode
*CUNodes
= M
->getNamedMetadata("llvm.dbg.cu");
954 Builder
.CreateRetVoid();
958 // Collect the relevant data into a large constant data structure that we can
959 // walk to write out everything.
960 StructType
*StartFileCallArgsTy
= StructType::create(
961 {Builder
.getInt8PtrTy(), Builder
.getInt8PtrTy(), Builder
.getInt32Ty()});
962 StructType
*EmitFunctionCallArgsTy
= StructType::create(
963 {Builder
.getInt32Ty(), Builder
.getInt8PtrTy(), Builder
.getInt32Ty(),
964 Builder
.getInt8Ty(), Builder
.getInt32Ty()});
965 StructType
*EmitArcsCallArgsTy
= StructType::create(
966 {Builder
.getInt32Ty(), Builder
.getInt64Ty()->getPointerTo()});
967 StructType
*FileInfoTy
=
968 StructType::create({StartFileCallArgsTy
, Builder
.getInt32Ty(),
969 EmitFunctionCallArgsTy
->getPointerTo(),
970 EmitArcsCallArgsTy
->getPointerTo()});
972 Constant
*Zero32
= Builder
.getInt32(0);
973 // Build an explicit array of two zeros for use in ConstantExpr GEP building.
974 Constant
*TwoZero32s
[] = {Zero32
, Zero32
};
976 SmallVector
<Constant
*, 8> FileInfos
;
977 for (int i
: llvm::seq
<int>(0, CUNodes
->getNumOperands())) {
978 auto *CU
= cast
<DICompileUnit
>(CUNodes
->getOperand(i
));
980 // Skip module skeleton (and module) CUs.
984 std::string FilenameGcda
= mangleName(CU
, GCovFileType::GCDA
);
985 uint32_t CfgChecksum
= FileChecksums
.empty() ? 0 : FileChecksums
[i
];
986 auto *StartFileCallArgs
= ConstantStruct::get(
987 StartFileCallArgsTy
, {Builder
.CreateGlobalStringPtr(FilenameGcda
),
988 Builder
.CreateGlobalStringPtr(ReversedVersion
),
989 Builder
.getInt32(CfgChecksum
)});
991 SmallVector
<Constant
*, 8> EmitFunctionCallArgsArray
;
992 SmallVector
<Constant
*, 8> EmitArcsCallArgsArray
;
993 for (int j
: llvm::seq
<int>(0, CountersBySP
.size())) {
994 auto *SP
= cast_or_null
<DISubprogram
>(CountersBySP
[j
].second
);
995 uint32_t FuncChecksum
= Funcs
.empty() ? 0 : Funcs
[j
]->getFuncChecksum();
996 EmitFunctionCallArgsArray
.push_back(ConstantStruct::get(
997 EmitFunctionCallArgsTy
,
998 {Builder
.getInt32(j
),
999 Options
.FunctionNamesInData
1000 ? Builder
.CreateGlobalStringPtr(getFunctionName(SP
))
1001 : Constant::getNullValue(Builder
.getInt8PtrTy()),
1002 Builder
.getInt32(FuncChecksum
),
1003 Builder
.getInt8(Options
.UseCfgChecksum
),
1004 Builder
.getInt32(CfgChecksum
)}));
1006 GlobalVariable
*GV
= CountersBySP
[j
].first
;
1007 unsigned Arcs
= cast
<ArrayType
>(GV
->getValueType())->getNumElements();
1008 EmitArcsCallArgsArray
.push_back(ConstantStruct::get(
1010 {Builder
.getInt32(Arcs
), ConstantExpr::getInBoundsGetElementPtr(
1011 GV
->getValueType(), GV
, TwoZero32s
)}));
1013 // Create global arrays for the two emit calls.
1014 int CountersSize
= CountersBySP
.size();
1015 assert(CountersSize
== (int)EmitFunctionCallArgsArray
.size() &&
1016 "Mismatched array size!");
1017 assert(CountersSize
== (int)EmitArcsCallArgsArray
.size() &&
1018 "Mismatched array size!");
1019 auto *EmitFunctionCallArgsArrayTy
=
1020 ArrayType::get(EmitFunctionCallArgsTy
, CountersSize
);
1021 auto *EmitFunctionCallArgsArrayGV
= new GlobalVariable(
1022 *M
, EmitFunctionCallArgsArrayTy
, /*isConstant*/ true,
1023 GlobalValue::InternalLinkage
,
1024 ConstantArray::get(EmitFunctionCallArgsArrayTy
,
1025 EmitFunctionCallArgsArray
),
1026 Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i
));
1027 auto *EmitArcsCallArgsArrayTy
=
1028 ArrayType::get(EmitArcsCallArgsTy
, CountersSize
);
1029 EmitFunctionCallArgsArrayGV
->setUnnamedAddr(
1030 GlobalValue::UnnamedAddr::Global
);
1031 auto *EmitArcsCallArgsArrayGV
= new GlobalVariable(
1032 *M
, EmitArcsCallArgsArrayTy
, /*isConstant*/ true,
1033 GlobalValue::InternalLinkage
,
1034 ConstantArray::get(EmitArcsCallArgsArrayTy
, EmitArcsCallArgsArray
),
1035 Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i
));
1036 EmitArcsCallArgsArrayGV
->setUnnamedAddr(GlobalValue::UnnamedAddr::Global
);
1038 FileInfos
.push_back(ConstantStruct::get(
1040 {StartFileCallArgs
, Builder
.getInt32(CountersSize
),
1041 ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy
,
1042 EmitFunctionCallArgsArrayGV
,
1044 ConstantExpr::getInBoundsGetElementPtr(
1045 EmitArcsCallArgsArrayTy
, EmitArcsCallArgsArrayGV
, TwoZero32s
)}));
1048 // If we didn't find anything to actually emit, bail on out.
1049 if (FileInfos
.empty()) {
1050 Builder
.CreateRetVoid();
1054 // To simplify code, we cap the number of file infos we write out to fit
1055 // easily in a 32-bit signed integer. This gives consistent behavior between
1056 // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
1057 // operations on 32-bit systems. It also seems unreasonable to try to handle
1058 // more than 2 billion files.
1059 if ((int64_t)FileInfos
.size() > (int64_t)INT_MAX
)
1060 FileInfos
.resize(INT_MAX
);
1062 // Create a global for the entire data structure so we can walk it more
1064 auto *FileInfoArrayTy
= ArrayType::get(FileInfoTy
, FileInfos
.size());
1065 auto *FileInfoArrayGV
= new GlobalVariable(
1066 *M
, FileInfoArrayTy
, /*isConstant*/ true, GlobalValue::InternalLinkage
,
1067 ConstantArray::get(FileInfoArrayTy
, FileInfos
),
1068 "__llvm_internal_gcov_emit_file_info");
1069 FileInfoArrayGV
->setUnnamedAddr(GlobalValue::UnnamedAddr::Global
);
1071 // Create the CFG for walking this data structure.
1072 auto *FileLoopHeader
=
1073 BasicBlock::Create(*Ctx
, "file.loop.header", WriteoutF
);
1074 auto *CounterLoopHeader
=
1075 BasicBlock::Create(*Ctx
, "counter.loop.header", WriteoutF
);
1076 auto *FileLoopLatch
= BasicBlock::Create(*Ctx
, "file.loop.latch", WriteoutF
);
1077 auto *ExitBB
= BasicBlock::Create(*Ctx
, "exit", WriteoutF
);
1079 // We always have at least one file, so just branch to the header.
1080 Builder
.CreateBr(FileLoopHeader
);
1082 // The index into the files structure is our loop induction variable.
1083 Builder
.SetInsertPoint(FileLoopHeader
);
1085 Builder
.CreatePHI(Builder
.getInt32Ty(), /*NumReservedValues*/ 2);
1086 IV
->addIncoming(Builder
.getInt32(0), BB
);
1087 auto *FileInfoPtr
= Builder
.CreateInBoundsGEP(
1088 FileInfoArrayTy
, FileInfoArrayGV
, {Builder
.getInt32(0), IV
});
1089 auto *StartFileCallArgsPtr
=
1090 Builder
.CreateStructGEP(FileInfoTy
, FileInfoPtr
, 0);
1091 auto *StartFileCall
= Builder
.CreateCall(
1093 {Builder
.CreateLoad(StartFileCallArgsTy
->getElementType(0),
1094 Builder
.CreateStructGEP(StartFileCallArgsTy
,
1095 StartFileCallArgsPtr
, 0)),
1096 Builder
.CreateLoad(StartFileCallArgsTy
->getElementType(1),
1097 Builder
.CreateStructGEP(StartFileCallArgsTy
,
1098 StartFileCallArgsPtr
, 1)),
1099 Builder
.CreateLoad(StartFileCallArgsTy
->getElementType(2),
1100 Builder
.CreateStructGEP(StartFileCallArgsTy
,
1101 StartFileCallArgsPtr
, 2))});
1102 if (auto AK
= TLI
->getExtAttrForI32Param(false))
1103 StartFileCall
->addParamAttr(2, AK
);
1105 Builder
.CreateLoad(FileInfoTy
->getElementType(1),
1106 Builder
.CreateStructGEP(FileInfoTy
, FileInfoPtr
, 1));
1107 auto *EmitFunctionCallArgsArray
=
1108 Builder
.CreateLoad(FileInfoTy
->getElementType(2),
1109 Builder
.CreateStructGEP(FileInfoTy
, FileInfoPtr
, 2));
1110 auto *EmitArcsCallArgsArray
=
1111 Builder
.CreateLoad(FileInfoTy
->getElementType(3),
1112 Builder
.CreateStructGEP(FileInfoTy
, FileInfoPtr
, 3));
1113 auto *EnterCounterLoopCond
=
1114 Builder
.CreateICmpSLT(Builder
.getInt32(0), NumCounters
);
1115 Builder
.CreateCondBr(EnterCounterLoopCond
, CounterLoopHeader
, FileLoopLatch
);
1117 Builder
.SetInsertPoint(CounterLoopHeader
);
1118 auto *JV
= Builder
.CreatePHI(Builder
.getInt32Ty(), /*NumReservedValues*/ 2);
1119 JV
->addIncoming(Builder
.getInt32(0), FileLoopHeader
);
1120 auto *EmitFunctionCallArgsPtr
= Builder
.CreateInBoundsGEP(
1121 EmitFunctionCallArgsTy
, EmitFunctionCallArgsArray
, JV
);
1122 auto *EmitFunctionCall
= Builder
.CreateCall(
1124 {Builder
.CreateLoad(EmitFunctionCallArgsTy
->getElementType(0),
1125 Builder
.CreateStructGEP(EmitFunctionCallArgsTy
,
1126 EmitFunctionCallArgsPtr
, 0)),
1127 Builder
.CreateLoad(EmitFunctionCallArgsTy
->getElementType(1),
1128 Builder
.CreateStructGEP(EmitFunctionCallArgsTy
,
1129 EmitFunctionCallArgsPtr
, 1)),
1130 Builder
.CreateLoad(EmitFunctionCallArgsTy
->getElementType(2),
1131 Builder
.CreateStructGEP(EmitFunctionCallArgsTy
,
1132 EmitFunctionCallArgsPtr
, 2)),
1133 Builder
.CreateLoad(EmitFunctionCallArgsTy
->getElementType(3),
1134 Builder
.CreateStructGEP(EmitFunctionCallArgsTy
,
1135 EmitFunctionCallArgsPtr
, 3)),
1136 Builder
.CreateLoad(EmitFunctionCallArgsTy
->getElementType(4),
1137 Builder
.CreateStructGEP(EmitFunctionCallArgsTy
,
1138 EmitFunctionCallArgsPtr
,
1140 if (auto AK
= TLI
->getExtAttrForI32Param(false)) {
1141 EmitFunctionCall
->addParamAttr(0, AK
);
1142 EmitFunctionCall
->addParamAttr(2, AK
);
1143 EmitFunctionCall
->addParamAttr(3, AK
);
1144 EmitFunctionCall
->addParamAttr(4, AK
);
1146 auto *EmitArcsCallArgsPtr
=
1147 Builder
.CreateInBoundsGEP(EmitArcsCallArgsTy
, EmitArcsCallArgsArray
, JV
);
1148 auto *EmitArcsCall
= Builder
.CreateCall(
1150 {Builder
.CreateLoad(
1151 EmitArcsCallArgsTy
->getElementType(0),
1152 Builder
.CreateStructGEP(EmitArcsCallArgsTy
, EmitArcsCallArgsPtr
, 0)),
1153 Builder
.CreateLoad(EmitArcsCallArgsTy
->getElementType(1),
1154 Builder
.CreateStructGEP(EmitArcsCallArgsTy
,
1155 EmitArcsCallArgsPtr
, 1))});
1156 if (auto AK
= TLI
->getExtAttrForI32Param(false))
1157 EmitArcsCall
->addParamAttr(0, AK
);
1158 auto *NextJV
= Builder
.CreateAdd(JV
, Builder
.getInt32(1));
1159 auto *CounterLoopCond
= Builder
.CreateICmpSLT(NextJV
, NumCounters
);
1160 Builder
.CreateCondBr(CounterLoopCond
, CounterLoopHeader
, FileLoopLatch
);
1161 JV
->addIncoming(NextJV
, CounterLoopHeader
);
1163 Builder
.SetInsertPoint(FileLoopLatch
);
1164 Builder
.CreateCall(SummaryInfo
, {});
1165 Builder
.CreateCall(EndFile
, {});
1166 auto *NextIV
= Builder
.CreateAdd(IV
, Builder
.getInt32(1));
1167 auto *FileLoopCond
=
1168 Builder
.CreateICmpSLT(NextIV
, Builder
.getInt32(FileInfos
.size()));
1169 Builder
.CreateCondBr(FileLoopCond
, FileLoopHeader
, ExitBB
);
1170 IV
->addIncoming(NextIV
, FileLoopLatch
);
1172 Builder
.SetInsertPoint(ExitBB
);
1173 Builder
.CreateRetVoid();
1178 Function
*GCOVProfiler::
1179 insertFlush(ArrayRef
<std::pair
<GlobalVariable
*, MDNode
*> > CountersBySP
) {
1180 FunctionType
*FTy
= FunctionType::get(Type::getVoidTy(*Ctx
), false);
1181 Function
*FlushF
= M
->getFunction("__llvm_gcov_flush");
1183 FlushF
= Function::Create(FTy
, GlobalValue::InternalLinkage
,
1184 "__llvm_gcov_flush", M
);
1186 FlushF
->setLinkage(GlobalValue::InternalLinkage
);
1187 FlushF
->setUnnamedAddr(GlobalValue::UnnamedAddr::Global
);
1188 FlushF
->addFnAttr(Attribute::NoInline
);
1189 if (Options
.NoRedZone
)
1190 FlushF
->addFnAttr(Attribute::NoRedZone
);
1192 BasicBlock
*Entry
= BasicBlock::Create(*Ctx
, "entry", FlushF
);
1194 // Write out the current counters.
1195 Function
*WriteoutF
= M
->getFunction("__llvm_gcov_writeout");
1196 assert(WriteoutF
&& "Need to create the writeout function first!");
1198 IRBuilder
<> Builder(Entry
);
1199 Builder
.CreateCall(WriteoutF
, {});
1201 // Zero out the counters.
1202 for (const auto &I
: CountersBySP
) {
1203 GlobalVariable
*GV
= I
.first
;
1204 Constant
*Null
= Constant::getNullValue(GV
->getValueType());
1205 Builder
.CreateStore(Null
, GV
);
1208 Type
*RetTy
= FlushF
->getReturnType();
1209 if (RetTy
== Type::getVoidTy(*Ctx
))
1210 Builder
.CreateRetVoid();
1211 else if (RetTy
->isIntegerTy())
1212 // Used if __llvm_gcov_flush was implicitly declared.
1213 Builder
.CreateRet(ConstantInt::get(RetTy
, 0));
1215 report_fatal_error("invalid return type for __llvm_gcov_flush");