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/DebugInfo.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/DebugLoc.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/InstIterator.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Transforms/Utils/ModuleUtils.h"
45 static cl::opt<std::string>
46 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
49 GCOVOptions GCOVOptions::getDefault() {
51 Options.EmitNotes = true;
52 Options.EmitData = true;
53 Options.UseCfgChecksum = false;
54 Options.NoRedZone = false;
55 Options.FunctionNamesInData = true;
57 if (DefaultGCOVVersion.size() != 4) {
58 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
61 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
68 class GCOVProfiler : public ModulePass {
71 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
74 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
75 assert((Options.EmitNotes || Options.EmitData) &&
76 "GCOVProfiler asked to do nothing?");
80 DeleteContainerPointers(Funcs);
82 virtual const char *getPassName() const {
83 return "GCOV Profiler";
88 ReversedVersion[0] = Options.Version[3];
89 ReversedVersion[1] = Options.Version[2];
90 ReversedVersion[2] = Options.Version[1];
91 ReversedVersion[3] = Options.Version[0];
92 ReversedVersion[4] = '\0';
93 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
95 bool runOnModule(Module &M);
97 // Create the .gcno files for the Module based on DebugInfo.
98 void emitProfileNotes();
100 // Modify the program to track transitions along edges and call into the
101 // profiling runtime to emit .gcda files when run.
102 bool emitProfileArcs();
104 // Get pointers to the functions in the runtime library.
105 Constant *getStartFileFunc();
106 Constant *getIncrementIndirectCounterFunc();
107 Constant *getEmitFunctionFunc();
108 Constant *getEmitArcsFunc();
109 Constant *getSummaryInfoFunc();
110 Constant *getDeleteWriteoutFunctionListFunc();
111 Constant *getDeleteFlushFunctionListFunc();
112 Constant *getEndFileFunc();
114 // Create or retrieve an i32 state value that is used to represent the
115 // pred block number for certain non-trivial edges.
116 GlobalVariable *getEdgeStateValue();
118 // Produce a table of pointers to counters, by predecessor and successor
120 GlobalVariable *buildEdgeLookupTable(Function *F,
121 GlobalVariable *Counter,
122 const UniqueVector<BasicBlock *>&Preds,
123 const UniqueVector<BasicBlock*>&Succs);
125 // Add the function to write out all our counters to the global destructor
127 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
129 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
130 void insertIndirectCounterIncrement();
132 std::string mangleName(DICompileUnit CU, const char *NewStem);
136 // Reversed, NUL-terminated copy of Options.Version.
137 char ReversedVersion[5];
138 // Checksum, produced by hash of EdgeDestinations
139 uint32_t FileChecksum;
143 SmallVector<GCOVFunction *, 16> Funcs;
147 char GCOVProfiler::ID = 0;
148 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
149 "Insert instrumentation for GCOV profiling", false, false)
151 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
152 return new GCOVProfiler(Options);
155 static StringRef getFunctionName(DISubprogram SP) {
156 if (!SP.getLinkageName().empty())
157 return SP.getLinkageName();
164 static const char *const LinesTag;
165 static const char *const FunctionTag;
166 static const char *const BlockTag;
167 static const char *const EdgeTag;
171 void writeBytes(const char *Bytes, int Size) {
172 os->write(Bytes, Size);
175 void write(uint32_t i) {
176 writeBytes(reinterpret_cast<char*>(&i), 4);
179 // Returns the length measured in 4-byte blocks that will be used to
180 // represent this string in a GCOV file
181 static unsigned lengthOfGCOVString(StringRef s) {
182 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
183 // padding out to the next 4-byte word. The length is measured in 4-byte
184 // words including padding, not bytes of actual string.
185 return (s.size() / 4) + 1;
188 void writeGCOVString(StringRef s) {
189 uint32_t Len = lengthOfGCOVString(s);
191 writeBytes(s.data(), s.size());
193 // Write 1 to 4 bytes of NUL padding.
194 assert((unsigned)(4 - (s.size() % 4)) > 0);
195 assert((unsigned)(4 - (s.size() % 4)) <= 4);
196 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
201 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
202 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
203 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
204 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
209 // Constructed only by requesting it from a GCOVBlock, this object stores a
210 // list of line numbers and a single filename, representing lines that belong
212 class GCOVLines : public GCOVRecord {
214 void addLine(uint32_t Line) {
215 Lines.push_back(Line);
218 uint32_t length() const {
219 // Here 2 = 1 for string length + 1 for '0' id#.
220 return lengthOfGCOVString(Filename) + 2 + Lines.size();
225 writeGCOVString(Filename);
226 for (int i = 0, e = Lines.size(); i != e; ++i)
230 GCOVLines(StringRef F, raw_ostream *os)
237 SmallVector<uint32_t, 32> Lines;
241 // Sorting function for deterministic behaviour in GCOVBlock::writeOut.
242 struct StringKeySort {
243 bool operator()(StringMapEntry<GCOVLines *> *LHS,
244 StringMapEntry<GCOVLines *> *RHS) const {
245 return LHS->getKey() < RHS->getKey();
249 // Represent a basic block in GCOV. Each block has a unique number in the
250 // function, number of lines belonging to each block, and a set of edges to
252 class GCOVBlock : public GCOVRecord {
254 GCOVLines &getFile(StringRef Filename) {
255 GCOVLines *&Lines = LinesByFile[Filename];
257 Lines = new GCOVLines(Filename, os);
262 void addEdge(GCOVBlock &Successor) {
263 OutEdges.push_back(&Successor);
268 SmallVector<StringMapEntry<GCOVLines *> *, 32> SortedLinesByFile;
269 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
270 E = LinesByFile.end(); I != E; ++I) {
271 Len += I->second->length();
272 SortedLinesByFile.push_back(&*I);
275 writeBytes(LinesTag, 4);
279 StringKeySort Sorter;
280 std::sort(SortedLinesByFile.begin(), SortedLinesByFile.end(), Sorter);
281 for (SmallVectorImpl<StringMapEntry<GCOVLines *> *>::iterator
282 I = SortedLinesByFile.begin(), E = SortedLinesByFile.end();
284 (*I)->getValue()->writeOut();
290 DeleteContainerSeconds(LinesByFile);
294 friend class GCOVFunction;
296 GCOVBlock(uint32_t Number, raw_ostream *os)
302 StringMap<GCOVLines *> LinesByFile;
303 SmallVector<GCOVBlock *, 4> OutEdges;
306 // A function has a unique identifier, a checksum (we leave as zero) and a
307 // set of blocks and a map of edges between blocks. This is the only GCOV
308 // object users can construct, the blocks and lines will be rooted here.
309 class GCOVFunction : public GCOVRecord {
311 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
312 bool UseCfgChecksum) :
313 SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0) {
316 Function *F = SP.getFunction();
317 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
319 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
320 Blocks[BB] = new GCOVBlock(i++, os);
322 ReturnBlock = new GCOVBlock(i++, os);
326 DeleteContainerSeconds(Blocks);
330 GCOVBlock &getBlock(BasicBlock *BB) {
334 GCOVBlock &getReturnBlock() {
338 std::string getEdgeDestinations() {
339 std::string EdgeDestinations;
340 raw_string_ostream EDOS(EdgeDestinations);
341 Function *F = Blocks.begin()->first->getParent();
342 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
343 GCOVBlock &Block = *Blocks[I];
344 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
345 EDOS << Block.OutEdges[i]->Number;
347 return EdgeDestinations;
350 void setCfgChecksum(uint32_t Checksum) {
351 CfgChecksum = Checksum;
355 writeBytes(FunctionTag, 4);
356 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
357 1 + lengthOfGCOVString(SP.getFilename()) + 1;
362 write(0); // lineno checksum
365 writeGCOVString(getFunctionName(SP));
366 writeGCOVString(SP.getFilename());
367 write(SP.getLineNumber());
369 // Emit count of blocks.
370 writeBytes(BlockTag, 4);
371 write(Blocks.size() + 1);
372 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
373 write(0); // No flags on our blocks.
375 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
377 // Emit edges between blocks.
378 if (Blocks.empty()) return;
379 Function *F = Blocks.begin()->first->getParent();
380 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
381 GCOVBlock &Block = *Blocks[I];
382 if (Block.OutEdges.empty()) continue;
384 writeBytes(EdgeTag, 4);
385 write(Block.OutEdges.size() * 2 + 1);
387 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
388 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
390 write(Block.OutEdges[i]->Number);
391 write(0); // no flags
395 // Emit lines for each block.
396 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
397 Blocks[I]->writeOut();
405 uint32_t CfgChecksum;
406 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
407 GCOVBlock *ReturnBlock;
411 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
412 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
413 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
414 MDNode *N = GCov->getOperand(i);
415 if (N->getNumOperands() != 2) continue;
416 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
417 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
418 if (!GCovFile || !CompileUnit) continue;
419 if (CompileUnit == CU) {
420 SmallString<128> Filename = GCovFile->getString();
421 sys::path::replace_extension(Filename, NewStem);
422 return Filename.str();
427 SmallString<128> Filename = CU.getFilename();
428 sys::path::replace_extension(Filename, NewStem);
429 StringRef FName = sys::path::filename(Filename);
430 SmallString<128> CurPath;
431 if (sys::fs::current_path(CurPath)) return FName;
432 sys::path::append(CurPath, FName.str());
433 return CurPath.str();
436 bool GCOVProfiler::runOnModule(Module &M) {
438 Ctx = &M.getContext();
440 if (Options.EmitNotes) emitProfileNotes();
441 if (Options.EmitData) return emitProfileArcs();
445 void GCOVProfiler::emitProfileNotes() {
446 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
447 if (!CU_Nodes) return;
449 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
450 // Each compile unit gets its own .gcno file. This means that whether we run
451 // this pass over the original .o's as they're produced, or run it after
452 // LTO, we'll generate the same .gcno files.
454 DICompileUnit CU(CU_Nodes->getOperand(i));
455 std::string ErrorInfo;
456 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
458 std::string EdgeDestinations;
460 DIArray SPs = CU.getSubprograms();
461 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
462 DISubprogram SP(SPs.getElement(i));
463 assert((!SP || SP.isSubprogram()) &&
464 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
468 Function *F = SP.getFunction();
471 new GCOVFunction(SP, &out, i, Options.UseCfgChecksum);
472 Funcs.push_back(Func);
474 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
475 GCOVBlock &Block = Func->getBlock(BB);
476 TerminatorInst *TI = BB->getTerminator();
477 if (int successors = TI->getNumSuccessors()) {
478 for (int i = 0; i != successors; ++i) {
479 Block.addEdge(Func->getBlock(TI->getSuccessor(i)));
481 } else if (isa<ReturnInst>(TI)) {
482 Block.addEdge(Func->getReturnBlock());
486 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
488 const DebugLoc &Loc = I->getDebugLoc();
489 if (Loc.isUnknown()) continue;
490 if (Line == Loc.getLine()) continue;
491 Line = Loc.getLine();
492 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
494 GCOVLines &Lines = Block.getFile(SP.getFilename());
495 Lines.addLine(Loc.getLine());
498 EdgeDestinations += Func->getEdgeDestinations();
501 FileChecksum = hash_value(EdgeDestinations);
502 out.write("oncg", 4);
503 out.write(ReversedVersion, 4);
504 out.write(reinterpret_cast<char*>(&FileChecksum), 4);
506 for (SmallVectorImpl<GCOVFunction *>::iterator I = Funcs.begin(),
507 E = Funcs.end(); I != E; ++I)
510 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
515 bool GCOVProfiler::emitProfileArcs() {
516 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
517 if (!CU_Nodes) return false;
520 bool InsertIndCounterIncrCode = false;
521 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
522 DICompileUnit CU(CU_Nodes->getOperand(i));
523 DIArray SPs = CU.getSubprograms();
524 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
525 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
526 DISubprogram SP(SPs.getElement(i));
527 assert((!SP || SP.isSubprogram()) &&
528 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
531 Function *F = SP.getFunction();
533 if (!Result) Result = true;
535 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
536 TerminatorInst *TI = BB->getTerminator();
537 if (isa<ReturnInst>(TI))
540 Edges += TI->getNumSuccessors();
543 ArrayType *CounterTy =
544 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
545 GlobalVariable *Counters =
546 new GlobalVariable(*M, CounterTy, false,
547 GlobalValue::InternalLinkage,
548 Constant::getNullValue(CounterTy),
550 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
552 UniqueVector<BasicBlock *> ComplexEdgePreds;
553 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
556 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
557 TerminatorInst *TI = BB->getTerminator();
558 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
560 if (Successors == 1) {
561 IRBuilder<> Builder(BB->getFirstInsertionPt());
562 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
564 Value *Count = Builder.CreateLoad(Counter);
565 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
566 Builder.CreateStore(Count, Counter);
567 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
568 IRBuilder<> Builder(BI);
569 Value *Sel = Builder.CreateSelect(BI->getCondition(),
570 Builder.getInt64(Edge),
571 Builder.getInt64(Edge + 1));
572 SmallVector<Value *, 2> Idx;
573 Idx.push_back(Builder.getInt64(0));
575 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
576 Value *Count = Builder.CreateLoad(Counter);
577 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
578 Builder.CreateStore(Count, Counter);
580 ComplexEdgePreds.insert(BB);
581 for (int i = 0; i != Successors; ++i)
582 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
589 if (!ComplexEdgePreds.empty()) {
590 GlobalVariable *EdgeTable =
591 buildEdgeLookupTable(F, Counters,
592 ComplexEdgePreds, ComplexEdgeSuccs);
593 GlobalVariable *EdgeState = getEdgeStateValue();
595 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
596 IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
597 Builder.CreateStore(Builder.getInt32(i), EdgeState);
600 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
601 // Call runtime to perform increment.
602 IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
603 Value *CounterPtrArray =
604 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
605 i * ComplexEdgePreds.size());
607 // Build code to increment the counter.
608 InsertIndCounterIncrCode = true;
609 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
610 EdgeState, CounterPtrArray);
615 Function *WriteoutF = insertCounterWriteout(CountersBySP);
616 Function *FlushF = insertFlush(CountersBySP);
618 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
619 // be executed at exit and the "__llvm_gcov_flush" function to be executed
620 // when "__gcov_flush" is called.
621 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
622 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
623 "__llvm_gcov_init", M);
624 F->setUnnamedAddr(true);
625 F->setLinkage(GlobalValue::InternalLinkage);
626 F->addFnAttr(Attribute::NoInline);
627 if (Options.NoRedZone)
628 F->addFnAttr(Attribute::NoRedZone);
630 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
631 IRBuilder<> Builder(BB);
633 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
635 PointerType::get(FTy, 0),
636 PointerType::get(FTy, 0)
638 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
640 // Initialize the environment and register the local writeout and flush
642 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
643 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
644 Builder.CreateRetVoid();
646 appendToGlobalCtors(*M, F, 0);
649 if (InsertIndCounterIncrCode)
650 insertIndirectCounterIncrement();
655 // All edges with successors that aren't branches are "complex", because it
656 // requires complex logic to pick which counter to update.
657 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
659 GlobalVariable *Counters,
660 const UniqueVector<BasicBlock *> &Preds,
661 const UniqueVector<BasicBlock *> &Succs) {
662 // TODO: support invoke, threads. We rely on the fact that nothing can modify
663 // the whole-Module pred edge# between the time we set it and the time we next
664 // read it. Threads and invoke make this untrue.
666 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
667 size_t TableSize = Succs.size() * Preds.size();
668 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
669 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
671 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
672 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
673 for (size_t i = 0; i != TableSize; ++i)
674 EdgeTable[i] = NullValue;
677 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
678 TerminatorInst *TI = BB->getTerminator();
679 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
680 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
681 for (int i = 0; i != Successors; ++i) {
682 BasicBlock *Succ = TI->getSuccessor(i);
683 IRBuilder<> Builder(Succ);
684 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
686 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
687 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
693 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
694 GlobalVariable *EdgeTableGV =
696 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
697 ConstantArray::get(EdgeTableTy, V),
698 "__llvm_gcda_edge_table");
699 EdgeTableGV->setUnnamedAddr(true);
703 Constant *GCOVProfiler::getStartFileFunc() {
705 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
706 Type::getInt8PtrTy(*Ctx), // const char version[4]
707 Type::getInt32Ty(*Ctx), // uint32_t checksum
709 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
710 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
713 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
714 Type *Int32Ty = Type::getInt32Ty(*Ctx);
715 Type *Int64Ty = Type::getInt64Ty(*Ctx);
717 Int32Ty->getPointerTo(), // uint32_t *predecessor
718 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
720 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
721 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
724 Constant *GCOVProfiler::getEmitFunctionFunc() {
726 Type::getInt32Ty(*Ctx), // uint32_t ident
727 Type::getInt8PtrTy(*Ctx), // const char *function_name
728 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
729 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
731 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
732 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
735 Constant *GCOVProfiler::getEmitArcsFunc() {
737 Type::getInt32Ty(*Ctx), // uint32_t num_counters
738 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
740 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
741 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
744 Constant *GCOVProfiler::getSummaryInfoFunc() {
745 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
746 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
749 Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
750 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
751 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
754 Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
755 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
756 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
759 Constant *GCOVProfiler::getEndFileFunc() {
760 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
761 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
764 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
765 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
767 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
768 GlobalValue::InternalLinkage,
769 ConstantInt::get(Type::getInt32Ty(*Ctx),
771 "__llvm_gcov_global_state_pred");
772 GV->setUnnamedAddr(true);
777 Function *GCOVProfiler::insertCounterWriteout(
778 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
779 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
780 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
782 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
783 "__llvm_gcov_writeout", M);
784 WriteoutF->setUnnamedAddr(true);
785 WriteoutF->addFnAttr(Attribute::NoInline);
786 if (Options.NoRedZone)
787 WriteoutF->addFnAttr(Attribute::NoRedZone);
789 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
790 IRBuilder<> Builder(BB);
792 Constant *StartFile = getStartFileFunc();
793 Constant *EmitFunction = getEmitFunctionFunc();
794 Constant *EmitArcs = getEmitArcsFunc();
795 Constant *SummaryInfo = getSummaryInfoFunc();
796 Constant *EndFile = getEndFileFunc();
798 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
800 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
801 DICompileUnit CU(CU_Nodes->getOperand(i));
802 std::string FilenameGcda = mangleName(CU, "gcda");
803 Builder.CreateCall3(StartFile,
804 Builder.CreateGlobalStringPtr(FilenameGcda),
805 Builder.CreateGlobalStringPtr(ReversedVersion),
806 Builder.getInt32(FileChecksum));
807 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
808 DISubprogram SP(CountersBySP[j].second);
810 EmitFunction, Builder.getInt32(j),
811 Options.FunctionNamesInData ?
812 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
813 Constant::getNullValue(Builder.getInt8PtrTy()),
814 Builder.getInt8(Options.UseCfgChecksum),
815 Builder.getInt32(FileChecksum));
817 GlobalVariable *GV = CountersBySP[j].first;
819 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
820 Builder.CreateCall2(EmitArcs,
821 Builder.getInt32(Arcs),
822 Builder.CreateConstGEP2_64(GV, 0, 0));
824 Builder.CreateCall(SummaryInfo);
825 Builder.CreateCall(EndFile);
829 Builder.CreateRetVoid();
833 void GCOVProfiler::insertIndirectCounterIncrement() {
835 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
836 Fn->setUnnamedAddr(true);
837 Fn->setLinkage(GlobalValue::InternalLinkage);
838 Fn->addFnAttr(Attribute::NoInline);
839 if (Options.NoRedZone)
840 Fn->addFnAttr(Attribute::NoRedZone);
842 // Create basic blocks for function.
843 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
844 IRBuilder<> Builder(BB);
846 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
847 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
848 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
850 // uint32_t pred = *predecessor;
851 // if (pred == 0xffffffff) return;
852 Argument *Arg = Fn->arg_begin();
853 Arg->setName("predecessor");
854 Value *Pred = Builder.CreateLoad(Arg, "pred");
855 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
856 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
858 Builder.SetInsertPoint(PredNotNegOne);
860 // uint64_t *counter = counters[pred];
861 // if (!counter) return;
862 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
863 Arg = llvm::next(Fn->arg_begin());
864 Arg->setName("counters");
865 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
866 Value *Counter = Builder.CreateLoad(GEP, "counter");
867 Cond = Builder.CreateICmpEQ(Counter,
868 Constant::getNullValue(
869 Builder.getInt64Ty()->getPointerTo()));
870 Builder.CreateCondBr(Cond, Exit, CounterEnd);
873 Builder.SetInsertPoint(CounterEnd);
874 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
875 Builder.getInt64(1));
876 Builder.CreateStore(Add, Counter);
877 Builder.CreateBr(Exit);
879 // Fill in the exit block.
880 Builder.SetInsertPoint(Exit);
881 Builder.CreateRetVoid();
884 Function *GCOVProfiler::
885 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
886 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
887 Function *FlushF = M->getFunction("__llvm_gcov_flush");
889 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
890 "__llvm_gcov_flush", M);
892 FlushF->setLinkage(GlobalValue::InternalLinkage);
893 FlushF->setUnnamedAddr(true);
894 FlushF->addFnAttr(Attribute::NoInline);
895 if (Options.NoRedZone)
896 FlushF->addFnAttr(Attribute::NoRedZone);
898 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
900 // Write out the current counters.
901 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
902 assert(WriteoutF && "Need to create the writeout function first!");
904 IRBuilder<> Builder(Entry);
905 Builder.CreateCall(WriteoutF);
907 // Zero out the counters.
908 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
909 I = CountersBySP.begin(), E = CountersBySP.end();
911 GlobalVariable *GV = I->first;
912 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
913 Builder.CreateStore(Null, GV);
916 Type *RetTy = FlushF->getReturnType();
917 if (RetTy == Type::getVoidTy(*Ctx))
918 Builder.CreateRetVoid();
919 else if (RetTy->isIntegerTy())
920 // Used if __llvm_gcov_flush was implicitly declared.
921 Builder.CreateRet(ConstantInt::get(RetTy, 0));
923 report_fatal_error("invalid return type for __llvm_gcov_flush");