1 //===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass implements GCOV-style profiling. When this pass is run it emits
11 // "gcno" files next to the existing source, and instruments the code that runs
12 // to records the edges between blocks that run and emit a complementary "gcda"
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "insert-gcov-profiling"
19 #include "llvm/Transforms/Instrumentation.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/Hashing.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/UniqueVector.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DebugLoc.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InstIterator.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Utils/ModuleUtils.h"
46 static cl::opt<std::string>
47 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
50 GCOVOptions GCOVOptions::getDefault() {
52 Options.EmitNotes = true;
53 Options.EmitData = true;
54 Options.UseCfgChecksum = false;
55 Options.NoRedZone = false;
56 Options.FunctionNamesInData = true;
58 if (DefaultGCOVVersion.size() != 4) {
59 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
62 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
69 class GCOVProfiler : public ModulePass {
72 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
75 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
76 assert((Options.EmitNotes || Options.EmitData) &&
77 "GCOVProfiler asked to do nothing?");
81 DeleteContainerPointers(Funcs);
83 const char *getPassName() const override {
84 return "GCOV Profiler";
89 ReversedVersion[0] = Options.Version[3];
90 ReversedVersion[1] = Options.Version[2];
91 ReversedVersion[2] = Options.Version[1];
92 ReversedVersion[3] = Options.Version[0];
93 ReversedVersion[4] = '\0';
94 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
96 bool runOnModule(Module &M) override;
98 // Create the .gcno files for the Module based on DebugInfo.
99 void emitProfileNotes();
101 // Modify the program to track transitions along edges and call into the
102 // profiling runtime to emit .gcda files when run.
103 bool emitProfileArcs();
105 // Get pointers to the functions in the runtime library.
106 Constant *getStartFileFunc();
107 Constant *getIncrementIndirectCounterFunc();
108 Constant *getEmitFunctionFunc();
109 Constant *getEmitArcsFunc();
110 Constant *getSummaryInfoFunc();
111 Constant *getDeleteWriteoutFunctionListFunc();
112 Constant *getDeleteFlushFunctionListFunc();
113 Constant *getEndFileFunc();
115 // Create or retrieve an i32 state value that is used to represent the
116 // pred block number for certain non-trivial edges.
117 GlobalVariable *getEdgeStateValue();
119 // Produce a table of pointers to counters, by predecessor and successor
121 GlobalVariable *buildEdgeLookupTable(Function *F,
122 GlobalVariable *Counter,
123 const UniqueVector<BasicBlock *>&Preds,
124 const UniqueVector<BasicBlock*>&Succs);
126 // Add the function to write out all our counters to the global destructor
128 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
130 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
131 void insertIndirectCounterIncrement();
133 std::string mangleName(DICompileUnit CU, const char *NewStem);
137 // Reversed, NUL-terminated copy of Options.Version.
138 char ReversedVersion[5];
139 // Checksum, produced by hash of EdgeDestinations
140 SmallVector<uint32_t, 4> FileChecksums;
144 SmallVector<GCOVFunction *, 16> Funcs;
148 char GCOVProfiler::ID = 0;
149 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
150 "Insert instrumentation for GCOV profiling", false, false)
152 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
153 return new GCOVProfiler(Options);
156 static StringRef getFunctionName(DISubprogram SP) {
157 if (!SP.getLinkageName().empty())
158 return SP.getLinkageName();
165 static const char *const LinesTag;
166 static const char *const FunctionTag;
167 static const char *const BlockTag;
168 static const char *const EdgeTag;
172 void writeBytes(const char *Bytes, int Size) {
173 os->write(Bytes, Size);
176 void write(uint32_t i) {
177 writeBytes(reinterpret_cast<char*>(&i), 4);
180 // Returns the length measured in 4-byte blocks that will be used to
181 // represent this string in a GCOV file
182 static unsigned lengthOfGCOVString(StringRef s) {
183 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
184 // padding out to the next 4-byte word. The length is measured in 4-byte
185 // words including padding, not bytes of actual string.
186 return (s.size() / 4) + 1;
189 void writeGCOVString(StringRef s) {
190 uint32_t Len = lengthOfGCOVString(s);
192 writeBytes(s.data(), s.size());
194 // Write 1 to 4 bytes of NUL padding.
195 assert((unsigned)(4 - (s.size() % 4)) > 0);
196 assert((unsigned)(4 - (s.size() % 4)) <= 4);
197 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
202 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
203 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
204 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
205 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
210 // Constructed only by requesting it from a GCOVBlock, this object stores a
211 // list of line numbers and a single filename, representing lines that belong
213 class GCOVLines : public GCOVRecord {
215 void addLine(uint32_t Line) {
216 Lines.push_back(Line);
219 uint32_t length() const {
220 // Here 2 = 1 for string length + 1 for '0' id#.
221 return lengthOfGCOVString(Filename) + 2 + Lines.size();
226 writeGCOVString(Filename);
227 for (int i = 0, e = Lines.size(); i != e; ++i)
231 GCOVLines(StringRef F, raw_ostream *os)
238 SmallVector<uint32_t, 32> Lines;
242 // Represent a basic block in GCOV. Each block has a unique number in the
243 // function, number of lines belonging to each block, and a set of edges to
245 class GCOVBlock : public GCOVRecord {
247 GCOVLines &getFile(StringRef Filename) {
248 GCOVLines *&Lines = LinesByFile[Filename];
250 Lines = new GCOVLines(Filename, os);
255 void addEdge(GCOVBlock &Successor) {
256 OutEdges.push_back(&Successor);
261 SmallVector<StringMapEntry<GCOVLines *> *, 32> SortedLinesByFile;
262 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
263 E = LinesByFile.end(); I != E; ++I) {
264 Len += I->second->length();
265 SortedLinesByFile.push_back(&*I);
268 writeBytes(LinesTag, 4);
272 std::sort(SortedLinesByFile.begin(), SortedLinesByFile.end(),
273 [](StringMapEntry<GCOVLines *> *LHS,
274 StringMapEntry<GCOVLines *> *RHS) {
275 return LHS->getKey() < RHS->getKey();
277 for (SmallVectorImpl<StringMapEntry<GCOVLines *> *>::iterator
278 I = SortedLinesByFile.begin(), E = SortedLinesByFile.end();
280 (*I)->getValue()->writeOut();
286 DeleteContainerSeconds(LinesByFile);
290 friend class GCOVFunction;
292 GCOVBlock(uint32_t Number, raw_ostream *os)
298 StringMap<GCOVLines *> LinesByFile;
299 SmallVector<GCOVBlock *, 4> OutEdges;
302 // A function has a unique identifier, a checksum (we leave as zero) and a
303 // set of blocks and a map of edges between blocks. This is the only GCOV
304 // object users can construct, the blocks and lines will be rooted here.
305 class GCOVFunction : public GCOVRecord {
307 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
308 bool UseCfgChecksum) :
309 SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0) {
312 Function *F = SP.getFunction();
313 DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
315 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
316 Blocks[BB] = new GCOVBlock(i++, os);
318 ReturnBlock = new GCOVBlock(i++, os);
320 std::string FunctionNameAndLine;
321 raw_string_ostream FNLOS(FunctionNameAndLine);
322 FNLOS << getFunctionName(SP) << SP.getLineNumber();
324 FuncChecksum = hash_value(FunctionNameAndLine);
328 DeleteContainerSeconds(Blocks);
332 GCOVBlock &getBlock(BasicBlock *BB) {
336 GCOVBlock &getReturnBlock() {
340 std::string getEdgeDestinations() {
341 std::string EdgeDestinations;
342 raw_string_ostream EDOS(EdgeDestinations);
343 Function *F = Blocks.begin()->first->getParent();
344 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
345 GCOVBlock &Block = *Blocks[I];
346 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
347 EDOS << Block.OutEdges[i]->Number;
349 return EdgeDestinations;
352 uint32_t getFuncChecksum() {
356 void setCfgChecksum(uint32_t Checksum) {
357 CfgChecksum = Checksum;
361 writeBytes(FunctionTag, 4);
362 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
363 1 + lengthOfGCOVString(SP.getFilename()) + 1;
371 writeGCOVString(getFunctionName(SP));
372 writeGCOVString(SP.getFilename());
373 write(SP.getLineNumber());
375 // Emit count of blocks.
376 writeBytes(BlockTag, 4);
377 write(Blocks.size() + 1);
378 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
379 write(0); // No flags on our blocks.
381 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
383 // Emit edges between blocks.
384 if (Blocks.empty()) return;
385 Function *F = Blocks.begin()->first->getParent();
386 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
387 GCOVBlock &Block = *Blocks[I];
388 if (Block.OutEdges.empty()) continue;
390 writeBytes(EdgeTag, 4);
391 write(Block.OutEdges.size() * 2 + 1);
393 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
394 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
396 write(Block.OutEdges[i]->Number);
397 write(0); // no flags
401 // Emit lines for each block.
402 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
403 Blocks[I]->writeOut();
410 uint32_t FuncChecksum;
412 uint32_t CfgChecksum;
413 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
414 GCOVBlock *ReturnBlock;
418 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
419 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
420 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
421 MDNode *N = GCov->getOperand(i);
422 if (N->getNumOperands() != 2) continue;
423 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
424 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
425 if (!GCovFile || !CompileUnit) continue;
426 if (CompileUnit == CU) {
427 SmallString<128> Filename = GCovFile->getString();
428 sys::path::replace_extension(Filename, NewStem);
429 return Filename.str();
434 SmallString<128> Filename = CU.getFilename();
435 sys::path::replace_extension(Filename, NewStem);
436 StringRef FName = sys::path::filename(Filename);
437 SmallString<128> CurPath;
438 if (sys::fs::current_path(CurPath)) return FName;
439 sys::path::append(CurPath, FName.str());
440 return CurPath.str();
443 bool GCOVProfiler::runOnModule(Module &M) {
445 Ctx = &M.getContext();
447 if (Options.EmitNotes) emitProfileNotes();
448 if (Options.EmitData) return emitProfileArcs();
452 static bool functionHasLines(Function *F) {
453 // Check whether this function actually has any source lines. Not only
454 // do these waste space, they also can crash gcov.
455 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
456 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
458 const DebugLoc &Loc = I->getDebugLoc();
459 if (Loc.isUnknown()) continue;
460 if (Loc.getLine() != 0)
467 void GCOVProfiler::emitProfileNotes() {
468 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
469 if (!CU_Nodes) return;
471 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
472 // Each compile unit gets its own .gcno file. This means that whether we run
473 // this pass over the original .o's as they're produced, or run it after
474 // LTO, we'll generate the same .gcno files.
476 DICompileUnit CU(CU_Nodes->getOperand(i));
477 std::string ErrorInfo;
478 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
480 std::string EdgeDestinations;
482 DIArray SPs = CU.getSubprograms();
483 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
484 DISubprogram SP(SPs.getElement(i));
485 assert((!SP || SP.isSubprogram()) &&
486 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
490 Function *F = SP.getFunction();
492 if (!functionHasLines(F)) continue;
494 // gcov expects every function to start with an entry block that has a
495 // single successor, so split the entry block to make sure of that.
496 BasicBlock &EntryBlock = F->getEntryBlock();
497 BasicBlock::iterator It = EntryBlock.begin();
498 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
500 EntryBlock.splitBasicBlock(It);
503 new GCOVFunction(SP, &out, i, Options.UseCfgChecksum);
504 Funcs.push_back(Func);
506 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
507 GCOVBlock &Block = Func->getBlock(BB);
508 TerminatorInst *TI = BB->getTerminator();
509 if (int successors = TI->getNumSuccessors()) {
510 for (int i = 0; i != successors; ++i) {
511 Block.addEdge(Func->getBlock(TI->getSuccessor(i)));
513 } else if (isa<ReturnInst>(TI)) {
514 Block.addEdge(Func->getReturnBlock());
518 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
520 const DebugLoc &Loc = I->getDebugLoc();
521 if (Loc.isUnknown()) continue;
522 if (Line == Loc.getLine()) continue;
523 Line = Loc.getLine();
524 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
526 GCOVLines &Lines = Block.getFile(SP.getFilename());
527 Lines.addLine(Loc.getLine());
530 EdgeDestinations += Func->getEdgeDestinations();
533 FileChecksums.push_back(hash_value(EdgeDestinations));
534 out.write("oncg", 4);
535 out.write(ReversedVersion, 4);
536 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
538 for (SmallVectorImpl<GCOVFunction *>::iterator I = Funcs.begin(),
539 E = Funcs.end(); I != E; ++I) {
540 GCOVFunction *Func = *I;
541 Func->setCfgChecksum(FileChecksums.back());
545 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
550 bool GCOVProfiler::emitProfileArcs() {
551 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
552 if (!CU_Nodes) return false;
555 bool InsertIndCounterIncrCode = false;
556 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
557 DICompileUnit CU(CU_Nodes->getOperand(i));
558 DIArray SPs = CU.getSubprograms();
559 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
560 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
561 DISubprogram SP(SPs.getElement(i));
562 assert((!SP || SP.isSubprogram()) &&
563 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
566 Function *F = SP.getFunction();
568 if (!functionHasLines(F)) continue;
569 if (!Result) Result = true;
571 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
572 TerminatorInst *TI = BB->getTerminator();
573 if (isa<ReturnInst>(TI))
576 Edges += TI->getNumSuccessors();
579 ArrayType *CounterTy =
580 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
581 GlobalVariable *Counters =
582 new GlobalVariable(*M, CounterTy, false,
583 GlobalValue::InternalLinkage,
584 Constant::getNullValue(CounterTy),
586 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
588 UniqueVector<BasicBlock *> ComplexEdgePreds;
589 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
592 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
593 TerminatorInst *TI = BB->getTerminator();
594 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
596 if (Successors == 1) {
597 IRBuilder<> Builder(BB->getFirstInsertionPt());
598 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
600 Value *Count = Builder.CreateLoad(Counter);
601 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
602 Builder.CreateStore(Count, Counter);
603 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
604 IRBuilder<> Builder(BI);
605 Value *Sel = Builder.CreateSelect(BI->getCondition(),
606 Builder.getInt64(Edge),
607 Builder.getInt64(Edge + 1));
608 SmallVector<Value *, 2> Idx;
609 Idx.push_back(Builder.getInt64(0));
611 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
612 Value *Count = Builder.CreateLoad(Counter);
613 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
614 Builder.CreateStore(Count, Counter);
616 ComplexEdgePreds.insert(BB);
617 for (int i = 0; i != Successors; ++i)
618 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
625 if (!ComplexEdgePreds.empty()) {
626 GlobalVariable *EdgeTable =
627 buildEdgeLookupTable(F, Counters,
628 ComplexEdgePreds, ComplexEdgeSuccs);
629 GlobalVariable *EdgeState = getEdgeStateValue();
631 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
632 IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
633 Builder.CreateStore(Builder.getInt32(i), EdgeState);
636 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
637 // Call runtime to perform increment.
638 IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
639 Value *CounterPtrArray =
640 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
641 i * ComplexEdgePreds.size());
643 // Build code to increment the counter.
644 InsertIndCounterIncrCode = true;
645 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
646 EdgeState, CounterPtrArray);
651 Function *WriteoutF = insertCounterWriteout(CountersBySP);
652 Function *FlushF = insertFlush(CountersBySP);
654 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
655 // be executed at exit and the "__llvm_gcov_flush" function to be executed
656 // when "__gcov_flush" is called.
657 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
658 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
659 "__llvm_gcov_init", M);
660 F->setUnnamedAddr(true);
661 F->setLinkage(GlobalValue::InternalLinkage);
662 F->addFnAttr(Attribute::NoInline);
663 if (Options.NoRedZone)
664 F->addFnAttr(Attribute::NoRedZone);
666 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
667 IRBuilder<> Builder(BB);
669 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
671 PointerType::get(FTy, 0),
672 PointerType::get(FTy, 0)
674 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
676 // Initialize the environment and register the local writeout and flush
678 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
679 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
680 Builder.CreateRetVoid();
682 appendToGlobalCtors(*M, F, 0);
685 if (InsertIndCounterIncrCode)
686 insertIndirectCounterIncrement();
691 // All edges with successors that aren't branches are "complex", because it
692 // requires complex logic to pick which counter to update.
693 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
695 GlobalVariable *Counters,
696 const UniqueVector<BasicBlock *> &Preds,
697 const UniqueVector<BasicBlock *> &Succs) {
698 // TODO: support invoke, threads. We rely on the fact that nothing can modify
699 // the whole-Module pred edge# between the time we set it and the time we next
700 // read it. Threads and invoke make this untrue.
702 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
703 size_t TableSize = Succs.size() * Preds.size();
704 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
705 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
707 std::unique_ptr<Constant * []> EdgeTable(new Constant *[TableSize]);
708 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
709 for (size_t i = 0; i != TableSize; ++i)
710 EdgeTable[i] = NullValue;
713 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
714 TerminatorInst *TI = BB->getTerminator();
715 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
716 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
717 for (int i = 0; i != Successors; ++i) {
718 BasicBlock *Succ = TI->getSuccessor(i);
719 IRBuilder<> Builder(Succ);
720 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
722 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
723 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
729 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
730 GlobalVariable *EdgeTableGV =
732 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
733 ConstantArray::get(EdgeTableTy, V),
734 "__llvm_gcda_edge_table");
735 EdgeTableGV->setUnnamedAddr(true);
739 Constant *GCOVProfiler::getStartFileFunc() {
741 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
742 Type::getInt8PtrTy(*Ctx), // const char version[4]
743 Type::getInt32Ty(*Ctx), // uint32_t checksum
745 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
746 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
749 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
750 Type *Int32Ty = Type::getInt32Ty(*Ctx);
751 Type *Int64Ty = Type::getInt64Ty(*Ctx);
753 Int32Ty->getPointerTo(), // uint32_t *predecessor
754 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
756 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
757 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
760 Constant *GCOVProfiler::getEmitFunctionFunc() {
762 Type::getInt32Ty(*Ctx), // uint32_t ident
763 Type::getInt8PtrTy(*Ctx), // const char *function_name
764 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
765 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
766 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
768 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
769 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
772 Constant *GCOVProfiler::getEmitArcsFunc() {
774 Type::getInt32Ty(*Ctx), // uint32_t num_counters
775 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
777 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
778 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
781 Constant *GCOVProfiler::getSummaryInfoFunc() {
782 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
783 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
786 Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
787 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
788 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
791 Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
792 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
793 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
796 Constant *GCOVProfiler::getEndFileFunc() {
797 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
798 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
801 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
802 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
804 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
805 GlobalValue::InternalLinkage,
806 ConstantInt::get(Type::getInt32Ty(*Ctx),
808 "__llvm_gcov_global_state_pred");
809 GV->setUnnamedAddr(true);
814 Function *GCOVProfiler::insertCounterWriteout(
815 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
816 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
817 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
819 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
820 "__llvm_gcov_writeout", M);
821 WriteoutF->setUnnamedAddr(true);
822 WriteoutF->addFnAttr(Attribute::NoInline);
823 if (Options.NoRedZone)
824 WriteoutF->addFnAttr(Attribute::NoRedZone);
826 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
827 IRBuilder<> Builder(BB);
829 Constant *StartFile = getStartFileFunc();
830 Constant *EmitFunction = getEmitFunctionFunc();
831 Constant *EmitArcs = getEmitArcsFunc();
832 Constant *SummaryInfo = getSummaryInfoFunc();
833 Constant *EndFile = getEndFileFunc();
835 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
837 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
838 DICompileUnit CU(CU_Nodes->getOperand(i));
839 std::string FilenameGcda = mangleName(CU, "gcda");
840 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
841 Builder.CreateCall3(StartFile,
842 Builder.CreateGlobalStringPtr(FilenameGcda),
843 Builder.CreateGlobalStringPtr(ReversedVersion),
844 Builder.getInt32(CfgChecksum));
845 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
846 DISubprogram SP(CountersBySP[j].second);
847 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
849 EmitFunction, Builder.getInt32(j),
850 Options.FunctionNamesInData ?
851 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
852 Constant::getNullValue(Builder.getInt8PtrTy()),
853 Builder.getInt32(FuncChecksum),
854 Builder.getInt8(Options.UseCfgChecksum),
855 Builder.getInt32(CfgChecksum));
857 GlobalVariable *GV = CountersBySP[j].first;
859 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
860 Builder.CreateCall2(EmitArcs,
861 Builder.getInt32(Arcs),
862 Builder.CreateConstGEP2_64(GV, 0, 0));
864 Builder.CreateCall(SummaryInfo);
865 Builder.CreateCall(EndFile);
869 Builder.CreateRetVoid();
873 void GCOVProfiler::insertIndirectCounterIncrement() {
875 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
876 Fn->setUnnamedAddr(true);
877 Fn->setLinkage(GlobalValue::InternalLinkage);
878 Fn->addFnAttr(Attribute::NoInline);
879 if (Options.NoRedZone)
880 Fn->addFnAttr(Attribute::NoRedZone);
882 // Create basic blocks for function.
883 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
884 IRBuilder<> Builder(BB);
886 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
887 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
888 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
890 // uint32_t pred = *predecessor;
891 // if (pred == 0xffffffff) return;
892 Argument *Arg = Fn->arg_begin();
893 Arg->setName("predecessor");
894 Value *Pred = Builder.CreateLoad(Arg, "pred");
895 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
896 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
898 Builder.SetInsertPoint(PredNotNegOne);
900 // uint64_t *counter = counters[pred];
901 // if (!counter) return;
902 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
903 Arg = std::next(Fn->arg_begin());
904 Arg->setName("counters");
905 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
906 Value *Counter = Builder.CreateLoad(GEP, "counter");
907 Cond = Builder.CreateICmpEQ(Counter,
908 Constant::getNullValue(
909 Builder.getInt64Ty()->getPointerTo()));
910 Builder.CreateCondBr(Cond, Exit, CounterEnd);
913 Builder.SetInsertPoint(CounterEnd);
914 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
915 Builder.getInt64(1));
916 Builder.CreateStore(Add, Counter);
917 Builder.CreateBr(Exit);
919 // Fill in the exit block.
920 Builder.SetInsertPoint(Exit);
921 Builder.CreateRetVoid();
924 Function *GCOVProfiler::
925 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
926 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
927 Function *FlushF = M->getFunction("__llvm_gcov_flush");
929 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
930 "__llvm_gcov_flush", M);
932 FlushF->setLinkage(GlobalValue::InternalLinkage);
933 FlushF->setUnnamedAddr(true);
934 FlushF->addFnAttr(Attribute::NoInline);
935 if (Options.NoRedZone)
936 FlushF->addFnAttr(Attribute::NoRedZone);
938 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
940 // Write out the current counters.
941 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
942 assert(WriteoutF && "Need to create the writeout function first!");
944 IRBuilder<> Builder(Entry);
945 Builder.CreateCall(WriteoutF);
947 // Zero out the counters.
948 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
949 I = CountersBySP.begin(), E = CountersBySP.end();
951 GlobalVariable *GV = I->first;
952 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
953 Builder.CreateStore(Null, GV);
956 Type *RetTy = FlushF->getReturnType();
957 if (RetTy == Type::getVoidTy(*Ctx))
958 Builder.CreateRetVoid();
959 else if (RetTy->isIntegerTy())
960 // Used if __llvm_gcov_flush was implicitly declared.
961 Builder.CreateRet(ConstantInt::get(RetTy, 0));
963 report_fatal_error("invalid return type for __llvm_gcov_flush");