LLVM 24.0.0git
GCOVProfiling.cpp
Go to the documentation of this file.
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
17#include "llvm/ADT/Hashing.h"
18#include "llvm/ADT/MapVector.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/Sequence.h"
21#include "llvm/ADT/StringMap.h"
25#include "llvm/IR/DebugInfo.h"
26#include "llvm/IR/DebugLoc.h"
28#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/Module.h"
33#include "llvm/Support/CRC.h"
34#include "llvm/Support/Debug.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/Regex.h"
44#include <algorithm>
45#include <memory>
46#include <string>
47#include <utility>
48
49using namespace llvm;
51
52#define DEBUG_TYPE "insert-gcov-profiling"
53
54enum : uint32_t {
56
57 GCOV_TAG_FUNCTION = 0x01000000,
58 GCOV_TAG_BLOCKS = 0x01410000,
59 GCOV_TAG_ARCS = 0x01430000,
60 GCOV_TAG_LINES = 0x01450000,
61};
62
63// Returns the number of words which will be used to represent this string.
64static unsigned wordsOfString(StringRef s) {
65 // Length + NUL-terminated string + 0~3 padding NULs.
66 return (s.size() / 4) + 2;
67}
68
71 Options.EmitNotes = true;
72 Options.EmitData = true;
73 Options.NoRedZone = false;
74 const InstrumentationOptions &Opts = InstrumentationOptions::Global;
75 Options.Atomic = Opts.gcov_atomic_counter;
76
77 if (Opts.default_gcov_version.size() != 4) {
78 reportFatalUsageError(Twine("Invalid -default-gcov-version: ") +
79 Opts.default_gcov_version);
80 }
81 memcpy(Options.Version, Opts.default_gcov_version.data(), 4);
82 return Options;
83}
84
85namespace {
86class GCOVFunction;
87
88class GCOVProfiler {
89public:
90 GCOVProfiler()
91 : GCOVProfiler(GCOVOptions::getDefault(), *vfs::getRealFileSystem()) {}
92 GCOVProfiler(const GCOVOptions &Opts, vfs::FileSystem &VFS)
93 : Options(Opts), VFS(VFS) {}
94 bool
95 runOnModule(Module &M, function_ref<BlockFrequencyInfo *(Function &F)> GetBFI,
96 function_ref<BranchProbabilityInfo *(Function &F)> GetBPI,
97 std::function<const TargetLibraryInfo &(Function &F)> GetTLI);
98
99 void write(uint32_t i) {
100 char Bytes[4];
101 endian::write32(Bytes, i, Endian);
102 os->write(Bytes, 4);
103 }
104 void writeString(StringRef s) {
105 write(wordsOfString(s) - 1);
106 os->write(s.data(), s.size());
107 os->write_zeros(4 - s.size() % 4);
108 }
109 void writeBytes(const char *Bytes, int Size) { os->write(Bytes, Size); }
110 vfs::FileSystem &getVirtualFileSystem() const { return VFS; }
111
112private:
113 // Create the .gcno files for the Module based on DebugInfo.
114 bool
115 emitProfileNotes(NamedMDNode *CUNode, bool HasExecOrFork,
116 function_ref<BlockFrequencyInfo *(Function &F)> GetBFI,
117 function_ref<BranchProbabilityInfo *(Function &F)> GetBPI,
118 function_ref<const TargetLibraryInfo &(Function &F)> GetTLI);
119
120 Function *createInternalFunction(FunctionType *FTy, StringRef Name,
121 StringRef MangledType = "");
122
123 void emitGlobalConstructor(
124 SmallVectorImpl<std::pair<GlobalVariable *, MDNode *>> &CountersBySP);
125 void emitModuleInitFunctionPtrs(
126 SmallVectorImpl<std::pair<GlobalVariable *, MDNode *>> &CountersBySP);
127
128 bool isFunctionInstrumented(const Function &F);
129 std::vector<Regex> createRegexesFromString(StringRef RegexesStr);
130 static bool doesFilenameMatchARegex(StringRef Filename,
131 std::vector<Regex> &Regexes);
132
133 // Get pointers to the functions in the runtime library.
134 FunctionCallee getStartFileFunc(const TargetLibraryInfo *TLI);
135 FunctionCallee getEmitFunctionFunc(const TargetLibraryInfo *TLI);
136 FunctionCallee getEmitArcsFunc(const TargetLibraryInfo *TLI);
137 FunctionCallee getSummaryInfoFunc();
138 FunctionCallee getEndFileFunc();
139
140 // Add the function to write out all our counters to the global destructor
141 // list.
142 Function *
143 insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
144 Function *insertReset(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
145
146 bool AddFlushBeforeForkAndExec();
147
148 enum class GCovFileType { GCNO, GCDA };
149 std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
150
151 GCOVOptions Options;
152 llvm::endianness Endian;
153 raw_ostream *os;
154 int Version = 0;
155
156 // Checksum, produced by hash of EdgeDestinations
157 SmallVector<uint32_t, 4> FileChecksums;
158
159 Module *M = nullptr;
160 std::function<const TargetLibraryInfo &(Function &F)> GetTLI;
161 LLVMContext *Ctx = nullptr;
163 std::vector<Regex> FilterRe;
164 std::vector<Regex> ExcludeRe;
165 DenseSet<const BasicBlock *> ExecBlocks;
166 StringMap<bool> InstrumentedFiles;
167 vfs::FileSystem &VFS;
168};
169
170struct BBInfo {
171 BBInfo *Group;
172 uint32_t Index;
173 uint32_t Rank = 0;
174
175 BBInfo(unsigned Index) : Group(this), Index(Index) {}
176 std::string infoString() const {
177 return (Twine("Index=") + Twine(Index)).str();
178 }
179};
180
181struct Edge {
182 // This class implements the CFG edges. Note the CFG can be a multi-graph.
183 // So there might be multiple edges with same SrcBB and DestBB.
184 const BasicBlock *SrcBB;
185 const BasicBlock *DestBB;
186 uint64_t Weight;
187 BasicBlock *Place = nullptr;
188 uint32_t SrcNumber, DstNumber;
189 bool InMST = false;
190 bool Removed = false;
191 bool IsCritical = false;
192
193 Edge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
194 : SrcBB(Src), DestBB(Dest), Weight(W) {}
195
196 // Return the information string of an edge.
197 std::string infoString() const {
198 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
199 (IsCritical ? "c" : " ") + " W=" + Twine(Weight))
200 .str();
201 }
202};
203}
204
206 if (!SP->getLinkageName().empty())
207 return SP->getLinkageName();
208 return SP->getName();
209}
210
211/// Extract a filename for a DIScope.
212///
213/// Prefer relative paths in the coverage notes. Clang also may split
214/// up absolute paths into a directory and filename component. When
215/// the relative path doesn't exist, reconstruct the absolute path.
217 SmallString<128> Path;
218 StringRef RelPath = SP->getFilename();
219 if (VFS.exists(RelPath))
220 Path = RelPath;
221 else
222 sys::path::append(Path, SP->getDirectory(), SP->getFilename());
223 return Path;
224}
225
226namespace {
227 class GCOVRecord {
228 protected:
229 GCOVProfiler *P;
230
231 GCOVRecord(GCOVProfiler *P) : P(P) {}
232
233 void write(uint32_t i) { P->write(i); }
234 void writeString(StringRef s) { P->writeString(s); }
235 void writeBytes(const char *Bytes, int Size) { P->writeBytes(Bytes, Size); }
236 };
237
238 class GCOVFunction;
239 class GCOVBlock;
240
241 // Constructed only by requesting it from a GCOVBlock, this object stores a
242 // list of line numbers and a single filename, representing lines that belong
243 // to the block.
244 class GCOVLines : public GCOVRecord {
245 public:
246 StringRef getFilename() { return Filename; }
247
248 void addLine(uint32_t Line) {
249 assert(Line != 0 && "Line zero is not a valid real line number.");
250 Lines.push_back(Line);
251 }
252
253 uint32_t length() const {
254 return 1 + wordsOfString(Filename) + Lines.size();
255 }
256
257 void writeOut() {
258 write(0);
260 for (uint32_t L : Lines)
261 write(L);
262 }
263
264 GCOVLines(GCOVProfiler *P, StringRef F)
265 : GCOVRecord(P), Filename(std::string(F)) {}
266
267 private:
268 std::string Filename;
269 SmallVector<uint32_t, 32> Lines;
270 };
271
272
273 // Represent a basic block in GCOV. Each block has a unique number in the
274 // function, number of lines belonging to each block, and a set of edges to
275 // other blocks.
276 class GCOVBlock : public GCOVRecord {
277 public:
278 GCOVLines &getFile(StringRef Filename) {
279 if (Lines.empty() || Lines.back().getFilename() != Filename)
280 Lines.emplace_back(P, Filename);
281 return Lines.back();
282 }
283
284 void addEdge(GCOVBlock &Successor, uint32_t Flags) {
285 OutEdges.emplace_back(&Successor, Flags);
286 }
287
288 void writeOut() {
289 uint32_t Len = 3;
290
291 for (auto &L : Lines)
292 Len += L.length();
293
295 write(Len);
296 write(Number);
297
298 for (auto &L : Lines)
299 L.writeOut();
300 write(0);
301 write(0);
302 }
303
304 GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
305 // Only allow copy before edges and lines have been added. After that,
306 // there are inter-block pointers (eg: edges) that won't take kindly to
307 // blocks being copied or moved around.
308 assert(Lines.empty());
309 assert(OutEdges.empty());
310 }
311
312 uint32_t Number;
314
315 private:
316 friend class GCOVFunction;
317
318 GCOVBlock(GCOVProfiler *P, uint32_t Number)
319 : GCOVRecord(P), Number(Number) {}
320
322 };
323
324 // A function has a unique identifier, a checksum (we leave as zero) and a
325 // set of blocks and a map of edges between blocks. This is the only GCOV
326 // object users can construct, the blocks and lines will be rooted here.
327 class GCOVFunction : public GCOVRecord {
328 public:
329 GCOVFunction(GCOVProfiler *P, Function *F, const DISubprogram *SP,
330 unsigned EndLine, uint32_t Ident, int Version)
331 : GCOVRecord(P), SP(SP), EndLine(EndLine), Ident(Ident),
332 Version(Version), EntryBlock(P, 0), ReturnBlock(P, 1) {
333 LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
334 uint32_t i = 2;
335 for (BasicBlock &BB : *F)
336 Blocks.insert(std::make_pair(&BB, GCOVBlock(P, i++)));
337
338 std::string FunctionNameAndLine;
339 raw_string_ostream FNLOS(FunctionNameAndLine);
340 FNLOS << getFunctionName(SP) << SP->getLine();
341 FuncChecksum = hash_value(FunctionNameAndLine);
342 }
343
344 GCOVBlock &getBlock(const BasicBlock *BB) {
345 return Blocks.find(const_cast<BasicBlock *>(BB))->second;
346 }
347
348 GCOVBlock &getEntryBlock() { return EntryBlock; }
349 GCOVBlock &getReturnBlock() {
350 return ReturnBlock;
351 }
352
353 uint32_t getFuncChecksum() const {
354 return FuncChecksum;
355 }
356
357 void writeOut(uint32_t CfgChecksum) {
359 SmallString<128> Filename = getFilename(SP, P->getVirtualFileSystem());
360 uint32_t BlockLen = 3 + wordsOfString(getFunctionName(SP));
361 BlockLen += 1 + wordsOfString(Filename) + 4;
362
363 write(BlockLen);
364 write(Ident);
365 write(FuncChecksum);
366 write(CfgChecksum);
368
369 write(SP->isArtificial()); // artificial
371 write(SP->getLine()); // start_line
372 write(0); // start_column
373 // EndLine is the last line with !dbg. It is not the } line as in GCC,
374 // but good enough.
375 write(EndLine);
376 write(0); // end_column
377
378 // Emit count of blocks.
380 write(1);
381 write(Blocks.size() + 2);
382 LLVM_DEBUG(dbgs() << (Blocks.size() + 1) << " blocks\n");
383
384 // Emit edges between blocks.
385 const uint32_t Outgoing = EntryBlock.OutEdges.size();
386 if (Outgoing) {
388 write(Outgoing * 2 + 1);
389 write(EntryBlock.Number);
390 for (const auto &E : EntryBlock.OutEdges) {
391 write(E.first->Number);
392 write(E.second);
393 }
394 }
395 for (auto &It : Blocks) {
396 const GCOVBlock &Block = It.second;
397 if (Block.OutEdges.empty()) continue;
398
400 write(Block.OutEdges.size() * 2 + 1);
401 write(Block.Number);
402 for (const auto &E : Block.OutEdges) {
403 write(E.first->Number);
404 write(E.second);
405 }
406 }
407
408 // Emit lines for each block.
409 for (auto &It : Blocks)
410 It.second.writeOut();
411 }
412
413 public:
414 const DISubprogram *SP;
415 unsigned EndLine;
416 uint32_t Ident;
417 uint32_t FuncChecksum;
418 int Version;
419 MapVector<BasicBlock *, GCOVBlock> Blocks;
420 GCOVBlock EntryBlock;
421 GCOVBlock ReturnBlock;
422 };
423}
424
425// RegexesStr is a string containing differents regex separated by a semi-colon.
426// For example "foo\..*$;bar\..*$".
427std::vector<Regex> GCOVProfiler::createRegexesFromString(StringRef RegexesStr) {
428 std::vector<Regex> Regexes;
429 while (!RegexesStr.empty()) {
430 std::pair<StringRef, StringRef> HeadTail = RegexesStr.split(';');
431 if (!HeadTail.first.empty()) {
432 Regex Re(HeadTail.first);
433 std::string Err;
434 if (!Re.isValid(Err)) {
435 Ctx->emitError(Twine("Regex ") + HeadTail.first +
436 " is not valid: " + Err);
437 }
438 Regexes.emplace_back(std::move(Re));
439 }
440 RegexesStr = HeadTail.second;
441 }
442 return Regexes;
443}
444
445bool GCOVProfiler::doesFilenameMatchARegex(StringRef Filename,
446 std::vector<Regex> &Regexes) {
447 for (Regex &Re : Regexes)
448 if (Re.match(Filename))
449 return true;
450 return false;
451}
452
453bool GCOVProfiler::isFunctionInstrumented(const Function &F) {
454 if (FilterRe.empty() && ExcludeRe.empty()) {
455 return true;
456 }
457 SmallString<128> Filename = getFilename(F.getSubprogram(), VFS);
458 auto It = InstrumentedFiles.find(Filename);
459 if (It != InstrumentedFiles.end()) {
460 return It->second;
461 }
462
463 SmallString<256> RealPath;
464 StringRef RealFilename;
465
466 // Path can be
467 // /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/*.h so for
468 // such a case we must get the real_path.
469 if (VFS.getRealPath(Filename, RealPath)) {
470 // real_path can fail with path like "foo.c".
471 RealFilename = Filename;
472 } else {
473 RealFilename = RealPath;
474 }
475
476 bool ShouldInstrument;
477 if (FilterRe.empty()) {
478 ShouldInstrument = !doesFilenameMatchARegex(RealFilename, ExcludeRe);
479 } else if (ExcludeRe.empty()) {
480 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe);
481 } else {
482 ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe) &&
483 !doesFilenameMatchARegex(RealFilename, ExcludeRe);
484 }
485 InstrumentedFiles[Filename] = ShouldInstrument;
486 return ShouldInstrument;
487}
488
489std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
490 GCovFileType OutputType) {
491 bool Notes = OutputType == GCovFileType::GCNO;
492
493 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
494 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
495 MDNode *N = GCov->getOperand(i);
496 bool ThreeElement = N->getNumOperands() == 3;
497 if (!ThreeElement && N->getNumOperands() != 2)
498 continue;
499 if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
500 continue;
501
502 if (ThreeElement) {
503 // These nodes have no mangling to apply, it's stored mangled in the
504 // bitcode.
505 MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
506 MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
507 if (!NotesFile || !DataFile)
508 continue;
509 return std::string(Notes ? NotesFile->getString()
510 : DataFile->getString());
511 }
512
513 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
514 if (!GCovFile)
515 continue;
516
517 SmallString<128> Filename = GCovFile->getString();
518 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
519 return std::string(Filename);
520 }
521 }
522
524 sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
526 ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory();
527 if (!CWD)
528 return std::string(FName);
529 SmallString<128> CurPath{*CWD};
530 sys::path::append(CurPath, FName);
531 return std::string(CurPath);
532}
533
534bool GCOVProfiler::runOnModule(
537 std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
538 this->M = &M;
539 this->GetTLI = std::move(GetTLI);
540 Ctx = &M.getContext();
541
542 NamedMDNode *CUNode = M.getNamedMetadata("llvm.dbg.cu");
543 if (!CUNode || (!Options.EmitNotes && !Options.EmitData))
544 return false;
545
546 bool HasExecOrFork = AddFlushBeforeForkAndExec();
547
548 FilterRe = createRegexesFromString(Options.Filter);
549 ExcludeRe = createRegexesFromString(Options.Exclude);
550 emitProfileNotes(CUNode, HasExecOrFork, GetBFI, GetBPI, this->GetTLI);
551 return true;
552}
553
556
557 GCOVProfiler Profiler(GCOVOpts, *VFS);
560
561 auto GetBFI = [&FAM](Function &F) {
562 return &FAM.getResult<BlockFrequencyAnalysis>(F);
563 };
564 auto GetBPI = [&FAM](Function &F) {
565 return &FAM.getResult<BranchProbabilityAnalysis>(F);
566 };
567 auto GetTLI = [&FAM](Function &F) -> const TargetLibraryInfo & {
568 return FAM.getResult<TargetLibraryAnalysis>(F);
569 };
570
571 if (!Profiler.runOnModule(M, GetBFI, GetBPI, GetTLI))
572 return PreservedAnalyses::all();
573
575}
576
577static bool functionHasLines(const Function &F, unsigned &EndLine) {
578 // Check whether this function actually has any source lines. Not only
579 // do these waste space, they also can crash gcov.
580 EndLine = 0;
581 for (const auto &BB : F) {
582 for (const auto &I : BB) {
583 const DebugLoc &Loc = I.getDebugLoc();
584 if (!Loc)
585 continue;
586
587 // Artificial lines such as calls to the global constructors.
588 if (Loc.getLine() == 0) continue;
589 EndLine = std::max(EndLine, Loc.getLine());
590
591 return true;
592 }
593 }
594 return false;
595}
596
598 if (!F.hasPersonalityFn()) return false;
599
600 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
601 return isScopedEHPersonality(Personality);
602}
603
604bool GCOVProfiler::AddFlushBeforeForkAndExec() {
605 const TargetLibraryInfo *TLI = nullptr;
608 for (auto &F : M->functions()) {
609 TLI = TLI == nullptr ? &GetTLI(F) : TLI;
610 for (auto &I : instructions(F)) {
611 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
612 if (Function *Callee = CI->getCalledFunction()) {
613 LibFunc LF = TLI->getLibFunc(*Callee);
614 if (LF != NotLibFunc) {
615 if (LF == LibFunc_fork) {
616#if !defined(_WIN32)
617 Forks.push_back(CI);
618#endif
619 } else if (LF == LibFunc_execl || LF == LibFunc_execle ||
620 LF == LibFunc_execlp || LF == LibFunc_execv ||
621 LF == LibFunc_execvp || LF == LibFunc_execve ||
622 LF == LibFunc_execvpe || LF == LibFunc_execvP) {
623 Execs.push_back(CI);
624 }
625 }
626 }
627 }
628 }
629 }
630
631 for (auto *F : Forks) {
632 IRBuilder<> Builder(F);
633 BasicBlock *Parent = F->getParent();
634 auto NextInst = ++F->getIterator();
635
636 // We've a fork so just reset the counters in the child process
637 FunctionType *FTy = FunctionType::get(Builder.getInt32Ty(), {}, false);
638 FunctionCallee GCOVFork = M->getOrInsertFunction(
639 "__gcov_fork", FTy,
640 TLI->getAttrList(Ctx, {}, /*Signed=*/true, /*Ret=*/true));
641 F->setCalledFunction(GCOVFork);
642
643 // We split just after the fork to have a counter for the lines after
644 // Anyway there's a bug:
645 // void foo() { fork(); }
646 // void bar() { foo(); blah(); }
647 // then "blah();" will be called 2 times but showed as 1
648 // because "blah()" belongs to the same block as "foo();"
649 Parent->splitBasicBlock(NextInst);
650
651 // back() is a br instruction with a debug location
652 // equals to the one from NextAfterFork
653 // So to avoid to have two debug locs on two blocks just change it
654 DebugLoc Loc = F->getDebugLoc();
655 Parent->back().setDebugLoc(Loc);
656 }
657
658 for (auto *E : Execs) {
659 IRBuilder<> Builder(E);
660 BasicBlock *Parent = E->getParent();
661 auto NextInst = ++E->getIterator();
662
663 // Since the process is replaced by a new one we need to write out gcdas
664 // No need to reset the counters since they'll be lost after the exec**
665 FunctionType *FTy = FunctionType::get(Builder.getVoidTy(), {}, false);
666 FunctionCallee WriteoutF =
667 M->getOrInsertFunction("llvm_writeout_files", FTy);
668 Builder.CreateCall(WriteoutF);
669
670 DebugLoc Loc = E->getDebugLoc();
671 Builder.SetInsertPoint(&*NextInst);
672 // If the exec** fails we must reset the counters since they've been
673 // dumped
674 FunctionCallee ResetF = M->getOrInsertFunction("llvm_reset_counters", FTy);
675 Builder.CreateCall(ResetF)->setDebugLoc(Loc);
676 ExecBlocks.insert(Parent);
677 Parent->splitBasicBlock(NextInst);
678 Parent->back().setDebugLoc(Loc);
679 }
680
681 return !Forks.empty() || !Execs.empty();
682}
683
685 const DenseSet<const BasicBlock *> &ExecBlocks) {
686 if (E.InMST || E.Removed)
687 return nullptr;
688
689 BasicBlock *SrcBB = const_cast<BasicBlock *>(E.SrcBB);
690 BasicBlock *DestBB = const_cast<BasicBlock *>(E.DestBB);
691 // For a fake edge, instrument the real BB.
692 if (SrcBB == nullptr)
693 return DestBB;
694 if (DestBB == nullptr)
695 return SrcBB;
696
697 auto CanInstrument = [](BasicBlock *BB) -> BasicBlock * {
698 // There are basic blocks (such as catchswitch) cannot be instrumented.
699 // If the returned first insertion point is the end of BB, skip this BB.
700 if (BB->getFirstInsertionPt() == BB->end())
701 return nullptr;
702 return BB;
703 };
704
705 // Instrument the SrcBB if it has a single successor,
706 // otherwise, the DestBB if this is not a critical edge.
707 Instruction *TI = SrcBB->getTerminator();
708 if (TI->getNumSuccessors() <= 1 && !ExecBlocks.count(SrcBB))
709 return CanInstrument(SrcBB);
710 if (!E.IsCritical)
711 return CanInstrument(DestBB);
712
713 // Some IndirectBr critical edges cannot be split by the previous
714 // SplitIndirectBrCriticalEdges call. Bail out.
715 const unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
716 BasicBlock *InstrBB =
717 isa<IndirectBrInst>(TI) ? nullptr : SplitCriticalEdge(TI, SuccNum);
718 if (!InstrBB)
719 return nullptr;
720
721 MST.addEdge(SrcBB, InstrBB, 0);
722 MST.addEdge(InstrBB, DestBB, 0).InMST = true;
723 E.Removed = true;
724
725 return CanInstrument(InstrBB);
726}
727
728#ifndef NDEBUG
730 size_t ID = 0;
731 for (const auto &E : make_pointee_range(MST.allEdges())) {
732 GCOVBlock &Src = E.SrcBB ? GF.getBlock(E.SrcBB) : GF.getEntryBlock();
733 GCOVBlock &Dst = E.DestBB ? GF.getBlock(E.DestBB) : GF.getReturnBlock();
734 dbgs() << " Edge " << ID++ << ": " << Src.Number << "->" << Dst.Number
735 << E.infoString() << "\n";
736 }
737}
738#endif
739
740bool GCOVProfiler::emitProfileNotes(
741 NamedMDNode *CUNode, bool HasExecOrFork,
744 function_ref<const TargetLibraryInfo &(Function &F)> GetTLI) {
745 {
746 uint8_t c3 = Options.Version[0];
747 uint8_t c2 = Options.Version[1];
748 uint8_t c1 = Options.Version[2];
749 Version = c3 >= 'A' ? (c3 - 'A') * 100 + (c2 - '0') * 10 + c1 - '0'
750 : (c3 - '0') * 10 + c1 - '0';
751 }
752 // Emit .gcno files that are compatible with GCC 11.1.
753 if (Version < 111) {
754 Version = 111;
755 memcpy(Options.Version, "B11*", 4);
756 }
757
758 bool EmitGCDA = Options.EmitData;
759 for (unsigned i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
760 // Each compile unit gets its own .gcno file. This means that whether we run
761 // this pass over the original .o's as they're produced, or run it after
762 // LTO, we'll generate the same .gcno files.
763
764 auto *CU = cast<DICompileUnit>(CUNode->getOperand(i));
765
766 // Skip module skeleton (and module) CUs.
767 if (CU->getDWOId())
768 continue;
769
770 std::vector<uint8_t> EdgeDestinations;
772
773 Endian = M->getDataLayout().isLittleEndian() ? llvm::endianness::little
775 unsigned FunctionIdent = 0;
776 for (auto &F : M->functions()) {
777 DISubprogram *SP = F.getSubprogram();
778 unsigned EndLine;
779 if (!SP) continue;
780 if (!functionHasLines(F, EndLine) || !isFunctionInstrumented(F))
781 continue;
782 // TODO: Functions using scope-based EH are currently not supported.
783 if (isUsingScopeBasedEH(F)) continue;
784 if (F.hasFnAttribute(llvm::Attribute::NoProfile))
785 continue;
786 if (F.hasFnAttribute(llvm::Attribute::SkipProfile))
787 continue;
788
789 // Add the function line number to the lines of the entry block
790 // to have a counter for the function definition.
791 uint32_t Line = SP->getLine();
792 auto Filename = getFilename(SP, VFS);
793
794 BranchProbabilityInfo *BPI = GetBPI(F);
795 BlockFrequencyInfo *BFI = GetBFI(F);
796
797 // Split indirectbr critical edges here before computing the MST rather
798 // than later in getInstrBB() to avoid invalidating it.
799 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/false, BPI,
800 BFI);
801
802 CFGMST<Edge, BBInfo> MST(F, /*InstrumentFuncEntry=*/false,
803 /*InstrumentLoopEntries=*/false, BPI, BFI);
804
805 // getInstrBB can split basic blocks and push elements to AllEdges.
806 for (size_t I : llvm::seq<size_t>(0, MST.numEdges())) {
807 auto &E = *MST.allEdges()[I];
808 // For now, disable spanning tree optimization when fork or exec* is
809 // used.
810 if (HasExecOrFork)
811 E.InMST = false;
812 E.Place = getInstrBB(MST, E, ExecBlocks);
813 }
814 // Basic blocks in F are finalized at this point.
815 BasicBlock &EntryBlock = F.getEntryBlock();
816 Funcs.push_back(std::make_unique<GCOVFunction>(this, &F, SP, EndLine,
817 FunctionIdent++, Version));
818 GCOVFunction &Func = *Funcs.back();
819
820 // Some non-tree edges are IndirectBr which cannot be split. Ignore them
821 // as well.
822 llvm::erase_if(MST.allEdges(), [](std::unique_ptr<Edge> &E) {
823 return E->Removed || (!E->InMST && !E->Place);
824 });
825 const size_t Measured =
826 std::stable_partition(
827 MST.allEdges().begin(), MST.allEdges().end(),
828 [](std::unique_ptr<Edge> &E) { return E->Place; }) -
829 MST.allEdges().begin();
830 for (size_t I : llvm::seq<size_t>(0, Measured)) {
831 Edge &E = *MST.allEdges()[I];
832 GCOVBlock &Src =
833 E.SrcBB ? Func.getBlock(E.SrcBB) : Func.getEntryBlock();
834 GCOVBlock &Dst =
835 E.DestBB ? Func.getBlock(E.DestBB) : Func.getReturnBlock();
836 E.SrcNumber = Src.Number;
837 E.DstNumber = Dst.Number;
838 }
839 std::stable_sort(
840 MST.allEdges().begin(), MST.allEdges().begin() + Measured,
841 [](const std::unique_ptr<Edge> &L, const std::unique_ptr<Edge> &R) {
842 return L->SrcNumber != R->SrcNumber ? L->SrcNumber < R->SrcNumber
843 : L->DstNumber < R->DstNumber;
844 });
845
846 for (const Edge &E : make_pointee_range(MST.allEdges())) {
847 GCOVBlock &Src =
848 E.SrcBB ? Func.getBlock(E.SrcBB) : Func.getEntryBlock();
849 GCOVBlock &Dst =
850 E.DestBB ? Func.getBlock(E.DestBB) : Func.getReturnBlock();
851 Src.addEdge(Dst, E.Place ? 0 : uint32_t(GCOV_ARC_ON_TREE));
852 }
853
854 // Artificial functions such as global initializers
855 if (!SP->isArtificial())
856 Func.getBlock(&EntryBlock).getFile(Filename).addLine(Line);
857
858 LLVM_DEBUG(dumpEdges(MST, Func));
859
860 for (auto &GB : Func.Blocks) {
861 const BasicBlock &BB = *GB.first;
862 auto &Block = GB.second;
863 for (auto Succ : Block.OutEdges) {
864 uint32_t Idx = Succ.first->Number;
865 do EdgeDestinations.push_back(Idx & 255);
866 while ((Idx >>= 8) > 0);
867 }
868
869 for (const auto &I : BB) {
870 const DebugLoc &Loc = I.getDebugLoc();
871 if (!Loc)
872 continue;
873
874 // Artificial lines such as calls to the global constructors.
875 if (Loc.getLine() == 0 || Loc.isImplicitCode())
876 continue;
877
878 if (Line == Loc.getLine()) continue;
879 Line = Loc.getLine();
880 MDNode *Scope = Loc.getScope();
881 if (SP != getDISubprogram(Scope))
882 continue;
883
884 GCOVLines &Lines = Block.getFile(getFilename(Loc->getScope(), VFS));
885 Lines.addLine(Loc.getLine());
886 }
887 Line = 0;
888 }
889 if (EmitGCDA) {
890 DISubprogram *SP = F.getSubprogram();
891 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(*Ctx), Measured);
893 *M, CounterTy, false, GlobalValue::InternalLinkage,
894 Constant::getNullValue(CounterTy), "__llvm_gcov_ctr");
895 const llvm::Triple &Triple = M->getTargetTriple();
897 Counters->setSection("__llvm_gcov_ctr_section");
898 CountersBySP.emplace_back(Counters, SP);
899
900 for (size_t I : llvm::seq<size_t>(0, Measured)) {
901 const Edge &E = *MST.allEdges()[I];
902 IRBuilder<> Builder(E.Place->getFirstInsertionPt());
903 Value *V = Builder.CreateConstInBoundsGEP2_64(
904 Counters->getValueType(), Counters, 0, I);
905 // Disable sanitizers to decrease size bloat. We don't expect
906 // sanitizers to catch interesting issues.
907 Instruction *Inst;
908 if (Options.Atomic) {
909 Inst = Builder.CreateAtomicRMW(AtomicRMWInst::Add, V,
910 Builder.getInt64(1), MaybeAlign(),
912 } else {
913 LoadInst *OldCount =
914 Builder.CreateLoad(Builder.getInt64Ty(), V, "gcov_ctr");
915 OldCount->setNoSanitizeMetadata();
916 Value *NewCount = Builder.CreateAdd(OldCount, Builder.getInt64(1));
917 Inst = Builder.CreateStore(NewCount, V);
918 }
919 Inst->setNoSanitizeMetadata();
920 }
921 }
922 }
923
924 char Tmp[4];
925 JamCRC JC;
926 JC.update(EdgeDestinations);
927 uint32_t Stamp = JC.getCRC();
928 FileChecksums.push_back(Stamp);
929
930 if (Options.EmitNotes) {
931 std::error_code EC;
932 raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC,
934 if (EC) {
935 Ctx->emitError(
936 Twine("failed to open coverage notes file for writing: ") +
937 EC.message());
938 continue;
939 }
940 os = &out;
941 if (Endian == llvm::endianness::big) {
942 out.write("gcno", 4);
943 out.write(Options.Version, 4);
944 } else {
945 out.write("oncg", 4);
946 std::reverse_copy(Options.Version, Options.Version + 4, Tmp);
947 out.write(Tmp, 4);
948 }
949 write(Stamp);
950 writeString("."); // unuseful current_working_directory
951 write(0); // unuseful has_unexecuted_blocks
952
953 for (auto &Func : Funcs)
954 Func->writeOut(Stamp);
955
956 write(0);
957 write(0);
958 out.close();
959 }
960
961 if (EmitGCDA) {
962 const llvm::Triple &Triple = M->getTargetTriple();
964 emitModuleInitFunctionPtrs(CountersBySP);
965 else
966 emitGlobalConstructor(CountersBySP);
967 EmitGCDA = false;
968 }
969 }
970 return true;
971}
972
973Function *GCOVProfiler::createInternalFunction(FunctionType *FTy,
974 StringRef Name,
975 StringRef MangledType /*=""*/) {
977 FTy, GlobalValue::InternalLinkage, 0, Name, M);
978 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
979 F->addFnAttr(Attribute::NoUnwind);
980 if (Options.NoRedZone)
981 F->addFnAttr(Attribute::NoRedZone);
982 if (!MangledType.empty())
983 setKCFIType(*M, *F, MangledType);
984 return F;
985}
986
987void GCOVProfiler::emitGlobalConstructor(
988 SmallVectorImpl<std::pair<GlobalVariable *, MDNode *>> &CountersBySP) {
989 Function *WriteoutF = insertCounterWriteout(CountersBySP);
990 Function *ResetF = insertReset(CountersBySP);
991
992 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
993 // be executed at exit and the "__llvm_gcov_reset" function to be executed
994 // when "__gcov_flush" is called.
996 Function *F = createInternalFunction(FTy, "__llvm_gcov_init", "_ZTSFvvE");
997 F->addFnAttr(Attribute::NoInline);
998
999 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
1000 IRBuilder<> Builder(BB);
1001
1002 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1003 auto *PFTy = PointerType::get(*Ctx, 0);
1004 FTy = FunctionType::get(Builder.getVoidTy(), {PFTy, PFTy}, false);
1005
1006 // Initialize the environment and register the local writeout, flush and
1007 // reset functions.
1008 FunctionCallee GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
1009 Builder.CreateCall(GCOVInit, {WriteoutF, ResetF});
1010 Builder.CreateRetVoid();
1011
1012 appendToGlobalCtors(*M, F, 0);
1013}
1014
1015void GCOVProfiler::emitModuleInitFunctionPtrs(
1016 SmallVectorImpl<std::pair<GlobalVariable *, MDNode *>> &CountersBySP) {
1017 Function *WriteoutF = insertCounterWriteout(CountersBySP);
1018 Function *ResetF = insertReset(CountersBySP);
1019
1020 // Instead of creating a function call and add it to the constructors list,
1021 // create a global variable in the __llvm_covinit section so the functions
1022 // can be registered by a constructor in the runtime.
1023
1024 auto &Ctx = M->getContext();
1025
1026 Type *InitFuncDataTy[] = {
1027#define COVINIT_FUNC(Type, LLVMType, Name, Init) LLVMType,
1029 };
1030
1031 auto STy = StructType::get(Ctx, ArrayRef(InitFuncDataTy));
1032
1033 Constant *InitFuncPtrs[] = {
1034#define COVINIT_FUNC(Type, LLVMType, Name, Init) Init,
1036 };
1037
1038 auto *CovInitGV =
1039 new GlobalVariable(*M, STy, false, GlobalValue::PrivateLinkage, nullptr,
1040 "__llvm_covinit_functions");
1041 CovInitGV->setInitializer(ConstantStruct::get(STy, InitFuncPtrs));
1042 CovInitGV->setVisibility(GlobalValue::VisibilityTypes::DefaultVisibility);
1043 CovInitGV->setSection(getInstrProfSectionName(
1044 IPSK_covinit, M->getTargetTriple().getObjectFormat()));
1045 CovInitGV->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
1046 CovInitGV->setConstant(true);
1047}
1048
1049FunctionCallee GCOVProfiler::getStartFileFunc(const TargetLibraryInfo *TLI) {
1050 Type *Args[] = {
1051 PointerType::getUnqual(*Ctx), // const char *orig_filename
1052 Type::getInt32Ty(*Ctx), // uint32_t version
1053 Type::getInt32Ty(*Ctx), // uint32_t checksum
1054 };
1055 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
1056 return M->getOrInsertFunction("llvm_gcda_start_file", FTy,
1057 TLI->getAttrList(Ctx, {1, 2}, /*Signed=*/false));
1058}
1059
1060FunctionCallee GCOVProfiler::getEmitFunctionFunc(const TargetLibraryInfo *TLI) {
1061 Type *Args[] = {
1062 Type::getInt32Ty(*Ctx), // uint32_t ident
1063 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
1064 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
1065 };
1066 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
1067 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy,
1068 TLI->getAttrList(Ctx, {0, 1, 2}, /*Signed=*/false));
1069}
1070
1071FunctionCallee GCOVProfiler::getEmitArcsFunc(const TargetLibraryInfo *TLI) {
1072 Type *Args[] = {
1073 Type::getInt32Ty(*Ctx), // uint32_t num_counters
1074 PointerType::getUnqual(*Ctx), // uint64_t *counters
1075 };
1076 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
1077 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy,
1078 TLI->getAttrList(Ctx, {0}, /*Signed=*/false));
1079}
1080
1081FunctionCallee GCOVProfiler::getSummaryInfoFunc() {
1082 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1083 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
1084}
1085
1086FunctionCallee GCOVProfiler::getEndFileFunc() {
1087 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1088 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
1089}
1090
1091Function *GCOVProfiler::insertCounterWriteout(
1092 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
1093 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1094 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1095 if (!WriteoutF)
1096 WriteoutF =
1097 createInternalFunction(WriteoutFTy, "__llvm_gcov_writeout", "_ZTSFvvE");
1098 WriteoutF->addFnAttr(Attribute::NoInline);
1099
1100 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
1101 IRBuilder<> Builder(BB);
1102
1103 auto *TLI = &GetTLI(*WriteoutF);
1104
1105 FunctionCallee StartFile = getStartFileFunc(TLI);
1106 FunctionCallee EmitFunction = getEmitFunctionFunc(TLI);
1107 FunctionCallee EmitArcs = getEmitArcsFunc(TLI);
1108 FunctionCallee SummaryInfo = getSummaryInfoFunc();
1109 FunctionCallee EndFile = getEndFileFunc();
1110
1111 NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
1112 if (!CUNodes) {
1113 Builder.CreateRetVoid();
1114 return WriteoutF;
1115 }
1116
1117 // Collect the relevant data into a large constant data structure that we can
1118 // walk to write out everything.
1119 StructType *StartFileCallArgsTy = StructType::create(
1120 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getInt32Ty()},
1121 "start_file_args_ty");
1122 StructType *EmitFunctionCallArgsTy = StructType::create(
1123 {Builder.getInt32Ty(), Builder.getInt32Ty(), Builder.getInt32Ty()},
1124 "emit_function_args_ty");
1125 auto *PtrTy = Builder.getPtrTy();
1126 StructType *EmitArcsCallArgsTy =
1127 StructType::create({Builder.getInt32Ty(), PtrTy}, "emit_arcs_args_ty");
1128 StructType *FileInfoTy = StructType::create(
1129 {StartFileCallArgsTy, Builder.getInt32Ty(), PtrTy, PtrTy}, "file_info");
1130
1132 for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
1133 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
1134
1135 // Skip module skeleton (and module) CUs.
1136 if (CU->getDWOId())
1137 continue;
1138
1139 std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
1140 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
1141 auto *StartFileCallArgs = ConstantStruct::get(
1142 StartFileCallArgsTy,
1143 {Builder.CreateGlobalString(FilenameGcda),
1144 Builder.getInt32(endian::read32be(Options.Version)),
1145 Builder.getInt32(CfgChecksum)});
1146
1147 SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
1148 SmallVector<Constant *, 8> EmitArcsCallArgsArray;
1149 for (int j : llvm::seq<int>(0, CountersBySP.size())) {
1150 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
1151 EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
1152 EmitFunctionCallArgsTy,
1153 {Builder.getInt32(j),
1154 Builder.getInt32(FuncChecksum),
1155 Builder.getInt32(CfgChecksum)}));
1156
1157 GlobalVariable *GV = CountersBySP[j].first;
1158 unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
1159 EmitArcsCallArgsArray.push_back(ConstantStruct::get(
1160 EmitArcsCallArgsTy, {Builder.getInt32(Arcs), GV}));
1161 }
1162 // Create global arrays for the two emit calls.
1163 int CountersSize = CountersBySP.size();
1164 assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
1165 "Mismatched array size!");
1166 assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
1167 "Mismatched array size!");
1168 auto *EmitFunctionCallArgsArrayTy =
1169 ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
1170 auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
1171 *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
1173 ConstantArray::get(EmitFunctionCallArgsArrayTy,
1174 EmitFunctionCallArgsArray),
1175 Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
1176 auto *EmitArcsCallArgsArrayTy =
1177 ArrayType::get(EmitArcsCallArgsTy, CountersSize);
1178 EmitFunctionCallArgsArrayGV->setUnnamedAddr(
1180 auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
1181 *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
1183 ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
1184 Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
1185 EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1186
1187 FileInfos.push_back(ConstantStruct::get(
1188 FileInfoTy, {StartFileCallArgs, Builder.getInt32(CountersSize),
1189 EmitFunctionCallArgsArrayGV, EmitArcsCallArgsArrayGV}));
1190 }
1191
1192 // If we didn't find anything to actually emit, bail on out.
1193 if (FileInfos.empty()) {
1194 Builder.CreateRetVoid();
1195 return WriteoutF;
1196 }
1197
1198 // To simplify code, we cap the number of file infos we write out to fit
1199 // easily in a 32-bit signed integer. This gives consistent behavior between
1200 // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
1201 // operations on 32-bit systems. It also seems unreasonable to try to handle
1202 // more than 2 billion files.
1203 if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
1204 FileInfos.resize(INT_MAX);
1205
1206 // Create a global for the entire data structure so we can walk it more
1207 // easily.
1208 auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
1209 auto *FileInfoArrayGV = new GlobalVariable(
1210 *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
1211 ConstantArray::get(FileInfoArrayTy, FileInfos),
1212 "__llvm_internal_gcov_emit_file_info");
1213 FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1214
1215 // Create the CFG for walking this data structure.
1216 auto *FileLoopHeader =
1217 BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
1218 auto *CounterLoopHeader =
1219 BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
1220 auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
1221 auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
1222
1223 // We always have at least one file, so just branch to the header.
1224 Builder.CreateBr(FileLoopHeader);
1225
1226 // The index into the files structure is our loop induction variable.
1227 Builder.SetInsertPoint(FileLoopHeader);
1228 PHINode *IV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2,
1229 "file_idx");
1230 IV->addIncoming(Builder.getInt32(0), BB);
1231 auto *FileInfoPtr = Builder.CreateInBoundsGEP(
1232 FileInfoArrayTy, FileInfoArrayGV, {Builder.getInt32(0), IV});
1233 auto *StartFileCallArgsPtr =
1234 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 0, "start_file_args");
1235 auto *StartFileCall = Builder.CreateCall(
1236 StartFile,
1237 {Builder.CreateLoad(StartFileCallArgsTy->getElementType(0),
1238 Builder.CreateStructGEP(StartFileCallArgsTy,
1239 StartFileCallArgsPtr, 0),
1240 "filename"),
1241 Builder.CreateLoad(StartFileCallArgsTy->getElementType(1),
1242 Builder.CreateStructGEP(StartFileCallArgsTy,
1243 StartFileCallArgsPtr, 1),
1244 "version"),
1245 Builder.CreateLoad(StartFileCallArgsTy->getElementType(2),
1246 Builder.CreateStructGEP(StartFileCallArgsTy,
1247 StartFileCallArgsPtr, 2),
1248 "stamp")});
1249 if (auto AK = TLI->getExtAttrForI32Param(false))
1250 StartFileCall->addParamAttr(2, AK);
1251 auto *NumCounters = Builder.CreateLoad(
1252 FileInfoTy->getElementType(1),
1253 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 1), "num_ctrs");
1254 auto *EmitFunctionCallArgsArray =
1255 Builder.CreateLoad(FileInfoTy->getElementType(2),
1256 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 2),
1257 "emit_function_args");
1258 auto *EmitArcsCallArgsArray = Builder.CreateLoad(
1259 FileInfoTy->getElementType(3),
1260 Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 3), "emit_arcs_args");
1261 auto *EnterCounterLoopCond =
1262 Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
1263 Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
1264
1265 Builder.SetInsertPoint(CounterLoopHeader);
1266 auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2,
1267 "ctr_idx");
1268 JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
1269 auto *EmitFunctionCallArgsPtr = Builder.CreateInBoundsGEP(
1270 EmitFunctionCallArgsTy, EmitFunctionCallArgsArray, JV);
1271 auto *EmitFunctionCall = Builder.CreateCall(
1272 EmitFunction,
1273 {Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(0),
1274 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1275 EmitFunctionCallArgsPtr, 0),
1276 "ident"),
1277 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(1),
1278 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1279 EmitFunctionCallArgsPtr, 1),
1280 "func_checkssum"),
1281 Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(2),
1282 Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1283 EmitFunctionCallArgsPtr, 2),
1284 "cfg_checksum")});
1285 if (auto AK = TLI->getExtAttrForI32Param(false)) {
1286 EmitFunctionCall->addParamAttr(0, AK);
1287 EmitFunctionCall->addParamAttr(1, AK);
1288 EmitFunctionCall->addParamAttr(2, AK);
1289 }
1290 auto *EmitArcsCallArgsPtr =
1291 Builder.CreateInBoundsGEP(EmitArcsCallArgsTy, EmitArcsCallArgsArray, JV);
1292 auto *EmitArcsCall = Builder.CreateCall(
1293 EmitArcs,
1294 {Builder.CreateLoad(
1295 EmitArcsCallArgsTy->getElementType(0),
1296 Builder.CreateStructGEP(EmitArcsCallArgsTy, EmitArcsCallArgsPtr, 0),
1297 "num_counters"),
1298 Builder.CreateLoad(
1299 EmitArcsCallArgsTy->getElementType(1),
1300 Builder.CreateStructGEP(EmitArcsCallArgsTy, EmitArcsCallArgsPtr, 1),
1301 "counters")});
1302 if (auto AK = TLI->getExtAttrForI32Param(false))
1303 EmitArcsCall->addParamAttr(0, AK);
1304 auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1305 auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1306 Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1307 JV->addIncoming(NextJV, CounterLoopHeader);
1308
1309 Builder.SetInsertPoint(FileLoopLatch);
1310 Builder.CreateCall(SummaryInfo, {});
1311 Builder.CreateCall(EndFile, {});
1312 auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1), "next_file_idx");
1313 auto *FileLoopCond =
1314 Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1315 Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1316 IV->addIncoming(NextIV, FileLoopLatch);
1317
1318 Builder.SetInsertPoint(ExitBB);
1319 Builder.CreateRetVoid();
1320
1321 return WriteoutF;
1322}
1323
1324Function *GCOVProfiler::insertReset(
1325 ArrayRef<std::pair<GlobalVariable *, MDNode *>> CountersBySP) {
1326 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1327 Function *ResetF = M->getFunction("__llvm_gcov_reset");
1328 if (!ResetF)
1329 ResetF = createInternalFunction(FTy, "__llvm_gcov_reset", "_ZTSFvvE");
1330 ResetF->addFnAttr(Attribute::NoInline);
1331
1332 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", ResetF);
1333 IRBuilder<> Builder(Entry);
1334 LLVMContext &C = Entry->getContext();
1335
1336 // Zero out the counters.
1337 for (const auto &I : CountersBySP) {
1338 GlobalVariable *GV = I.first;
1339 auto *GVTy = cast<ArrayType>(GV->getValueType());
1340 Builder.CreateMemSet(GV, Constant::getNullValue(Type::getInt8Ty(C)),
1341 GVTy->getNumElements() *
1342 GVTy->getElementType()->getScalarSizeInBits() / 8,
1343 GV->getAlign());
1344 }
1345
1346 Type *RetTy = ResetF->getReturnType();
1347 if (RetTy->isVoidTy())
1348 Builder.CreateRetVoid();
1349 else if (RetTy->isIntegerTy())
1350 // Used if __llvm_gcov_reset was implicitly declared.
1351 Builder.CreateRet(ConstantInt::get(RetTy, 0));
1352 else
1353 report_fatal_error("invalid return type for __llvm_gcov_reset");
1354
1355 return ResetF;
1356}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
unsigned uint64_t
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static void writeString(raw_ostream &OS, StringRef S)
This file provides the interface for the GCOV style profiler pass.
static unsigned wordsOfString(StringRef s)
static bool functionHasLines(const Function &F, unsigned &EndLine)
static bool isUsingScopeBasedEH(Function &F)
static void dumpEdges(CFGMST< Edge, BBInfo > &MST, GCOVFunction &GF)
static BasicBlock * getInstrBB(CFGMST< Edge, BBInfo > &MST, Edge &E, const DenseSet< const BasicBlock * > &ExecBlocks)
static SmallString< 128 > getFilename(const DIScope *SP, vfs::FileSystem &VFS)
Extract a filename for a DIScope.
static StringRef getFunctionName(const DISubprogram *SP)
@ GCOV_TAG_LINES
Definition GCOV.cpp:38
@ GCOV_ARC_ON_TREE
Definition GCOV.cpp:32
@ GCOV_TAG_ARCS
Definition GCOV.cpp:37
@ GCOV_TAG_FUNCTION
Definition GCOV.cpp:35
@ GCOV_TAG_BLOCKS
Definition GCOV.cpp:36
Module.h This file contains the declarations for the Module class.
#define INSTR_PROF_DATA_ALIGNMENT
static LVOptions Options
Definition LVOptions.cpp:25
static void addEdge(SmallVectorImpl< LazyCallGraph::Edge > &Edges, DenseMap< LazyCallGraph::Node *, int > &EdgeIndexMap, LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
static constexpr StringLiteral Filename
#define P(N)
FunctionAnalysisManager FAM
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
Provides some synthesis utilities to produce sequences of values.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
@ Add
*p = old + v
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
const Instruction & back() const
Definition BasicBlock.h:471
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
An union-find based Minimum Spanning Tree for CFG.
Definition CFGMST.h:41
Edge & addEdge(BasicBlock *Src, BasicBlock *Dest, uint64_t W)
Definition CFGMST.h:330
const std::vector< std::unique_ptr< Edge > > & allEdges() const
Definition CFGMST.h:367
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
uint64_t getDWOId() const
Base class for scope-like contexts.
StringRef getFilename() const
Subprogram description. Uses SubclassData1.
A debug info location.
Definition DebugLoc.h:126
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Represents either an error or a value T.
Definition ErrorOr.h:56
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Class to represent function types.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:644
static Function * createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Creates a function with some attributes recorded in llvm.module.flags and the LLVMContext applied.
Definition Function.cpp:376
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
GCOVBlock - Collects block information.
Definition GCOV.h:283
GCOVBlock(uint32_t N)
Definition GCOV.h:290
GCOVFunction - Collects function information.
Definition GCOV.h:237
GCOVFunction(GCOVFile &file)
Definition GCOV.h:242
LLVM_ABI StringRef getFilename() const
Definition GCOV.cpp:353
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
Type * getValueType() const
MaybeAlign getAlign() const
Returns the alignment of the given variable.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2918
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI void setNoSanitizeMetadata()
Sets the nosanitize metadata on this instruction.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
uint32_t getCRC() const
Definition CRC.h:77
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Definition CRC.cpp:103
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
A single uniqued string.
Definition Metadata.h:733
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:615
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A tuple of MDNodes.
Definition Metadata.h:1797
LLVM_ABI MDNode * getOperand(unsigned i) const
LLVM_ABI unsigned getNumOperands() const
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:467
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:662
Type * getElementType(unsigned N) const
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
AttributeList getAttrList(LLVMContext *C, ArrayRef< unsigned > ArgNos, bool Signed, bool Ret=false, AttributeList AL=AttributeList()) const
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
ObjectFormatType getObjectFormat() const
Get the object format for this triple.
Definition Triple.h:539
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
LLVM Value Representation.
Definition Value.h:75
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to a file descriptor.
The virtual file system interface.
virtual bool exists(const Twine &Path)
Check whether Path exists.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
void write32(void *P, uint32_t V, endianness E)
Definition Endian.h:435
uint32_t read32be(const void *P)
Definition Endian.h:421
LLVM_ABI void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition Path.cpp:491
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
This is an optimization pass for GlobalISel generic memory operations.
hash_code hash_value(const FixedPointSemantics &Val)
LLVM_ABI unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Definition CFG.cpp:90
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr, DomTreeUpdater *DTU=nullptr)
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
iterator_range< pointee_iterator< WrappedIteratorT > > make_pointee_range(RangeT &&Range)
Definition iterator.h:341
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
LLVM_ABI void setKCFIType(Module &M, Function &F, StringRef MangledType)
Sets the KCFI type for the function.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
endianness
Definition bit.h:71
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:746
LLVM_ABI DISubprogram * getDISubprogram(const MDNode *Scope)
Find subprogram that is enclosing this scope.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static LLVM_ABI GCOVOptions getDefault()
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111