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/IntrinsicInst.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/DebugLoc.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/InstIterator.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 virtual const char *getPassName() const {
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);
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 // Sorting function for deterministic behaviour in GCOVBlock::writeOut.
243 struct StringKeySort {
244 bool operator()(StringMapEntry<GCOVLines *> *LHS,
245 StringMapEntry<GCOVLines *> *RHS) const {
246 return LHS->getKey() < RHS->getKey();
250 // Represent a basic block in GCOV. Each block has a unique number in the
251 // function, number of lines belonging to each block, and a set of edges to
253 class GCOVBlock : public GCOVRecord {
255 GCOVLines &getFile(StringRef Filename) {
256 GCOVLines *&Lines = LinesByFile[Filename];
258 Lines = new GCOVLines(Filename, os);
263 void addEdge(GCOVBlock &Successor) {
264 OutEdges.push_back(&Successor);
269 SmallVector<StringMapEntry<GCOVLines *> *, 32> SortedLinesByFile;
270 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
271 E = LinesByFile.end(); I != E; ++I) {
272 Len += I->second->length();
273 SortedLinesByFile.push_back(&*I);
276 writeBytes(LinesTag, 4);
280 StringKeySort Sorter;
281 std::sort(SortedLinesByFile.begin(), SortedLinesByFile.end(), Sorter);
282 for (SmallVectorImpl<StringMapEntry<GCOVLines *> *>::iterator
283 I = SortedLinesByFile.begin(), E = SortedLinesByFile.end();
285 (*I)->getValue()->writeOut();
291 DeleteContainerSeconds(LinesByFile);
295 friend class GCOVFunction;
297 GCOVBlock(uint32_t Number, raw_ostream *os)
303 StringMap<GCOVLines *> LinesByFile;
304 SmallVector<GCOVBlock *, 4> OutEdges;
307 // A function has a unique identifier, a checksum (we leave as zero) and a
308 // set of blocks and a map of edges between blocks. This is the only GCOV
309 // object users can construct, the blocks and lines will be rooted here.
310 class GCOVFunction : public GCOVRecord {
312 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
313 bool UseCfgChecksum) :
314 SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0) {
317 Function *F = SP.getFunction();
318 DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
320 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
321 Blocks[BB] = new GCOVBlock(i++, os);
323 ReturnBlock = new GCOVBlock(i++, os);
325 std::string FunctionNameAndLine;
326 raw_string_ostream FNLOS(FunctionNameAndLine);
327 FNLOS << getFunctionName(SP) << SP.getLineNumber();
329 FuncChecksum = hash_value(FunctionNameAndLine);
333 DeleteContainerSeconds(Blocks);
337 GCOVBlock &getBlock(BasicBlock *BB) {
341 GCOVBlock &getReturnBlock() {
345 std::string getEdgeDestinations() {
346 std::string EdgeDestinations;
347 raw_string_ostream EDOS(EdgeDestinations);
348 Function *F = Blocks.begin()->first->getParent();
349 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
350 GCOVBlock &Block = *Blocks[I];
351 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
352 EDOS << Block.OutEdges[i]->Number;
354 return EdgeDestinations;
357 uint32_t getFuncChecksum() {
361 void setCfgChecksum(uint32_t Checksum) {
362 CfgChecksum = Checksum;
366 writeBytes(FunctionTag, 4);
367 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
368 1 + lengthOfGCOVString(SP.getFilename()) + 1;
376 writeGCOVString(getFunctionName(SP));
377 writeGCOVString(SP.getFilename());
378 write(SP.getLineNumber());
380 // Emit count of blocks.
381 writeBytes(BlockTag, 4);
382 write(Blocks.size() + 1);
383 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
384 write(0); // No flags on our blocks.
386 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
388 // Emit edges between blocks.
389 if (Blocks.empty()) return;
390 Function *F = Blocks.begin()->first->getParent();
391 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
392 GCOVBlock &Block = *Blocks[I];
393 if (Block.OutEdges.empty()) continue;
395 writeBytes(EdgeTag, 4);
396 write(Block.OutEdges.size() * 2 + 1);
398 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
399 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
401 write(Block.OutEdges[i]->Number);
402 write(0); // no flags
406 // Emit lines for each block.
407 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
408 Blocks[I]->writeOut();
415 uint32_t FuncChecksum;
417 uint32_t CfgChecksum;
418 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
419 GCOVBlock *ReturnBlock;
423 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
424 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
425 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
426 MDNode *N = GCov->getOperand(i);
427 if (N->getNumOperands() != 2) continue;
428 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
429 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
430 if (!GCovFile || !CompileUnit) continue;
431 if (CompileUnit == CU) {
432 SmallString<128> Filename = GCovFile->getString();
433 sys::path::replace_extension(Filename, NewStem);
434 return Filename.str();
439 SmallString<128> Filename = CU.getFilename();
440 sys::path::replace_extension(Filename, NewStem);
441 StringRef FName = sys::path::filename(Filename);
442 SmallString<128> CurPath;
443 if (sys::fs::current_path(CurPath)) return FName;
444 sys::path::append(CurPath, FName.str());
445 return CurPath.str();
448 bool GCOVProfiler::runOnModule(Module &M) {
450 Ctx = &M.getContext();
452 if (Options.EmitNotes) emitProfileNotes();
453 if (Options.EmitData) return emitProfileArcs();
457 void GCOVProfiler::emitProfileNotes() {
458 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
459 if (!CU_Nodes) return;
461 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
462 // Each compile unit gets its own .gcno file. This means that whether we run
463 // this pass over the original .o's as they're produced, or run it after
464 // LTO, we'll generate the same .gcno files.
466 DICompileUnit CU(CU_Nodes->getOperand(i));
467 std::string ErrorInfo;
468 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
470 std::string EdgeDestinations;
472 DIArray SPs = CU.getSubprograms();
473 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
474 DISubprogram SP(SPs.getElement(i));
475 assert((!SP || SP.isSubprogram()) &&
476 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
480 Function *F = SP.getFunction();
483 // gcov expects every function to start with an entry block that has a
484 // single successor, so split the entry block to make sure of that.
485 BasicBlock &EntryBlock = F->getEntryBlock();
486 BasicBlock::iterator It = EntryBlock.begin();
487 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
489 EntryBlock.splitBasicBlock(It);
492 new GCOVFunction(SP, &out, i, Options.UseCfgChecksum);
493 Funcs.push_back(Func);
495 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
496 GCOVBlock &Block = Func->getBlock(BB);
497 TerminatorInst *TI = BB->getTerminator();
498 if (int successors = TI->getNumSuccessors()) {
499 for (int i = 0; i != successors; ++i) {
500 Block.addEdge(Func->getBlock(TI->getSuccessor(i)));
502 } else if (isa<ReturnInst>(TI)) {
503 Block.addEdge(Func->getReturnBlock());
507 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
509 const DebugLoc &Loc = I->getDebugLoc();
510 if (Loc.isUnknown()) continue;
511 if (Line == Loc.getLine()) continue;
512 Line = Loc.getLine();
513 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
515 GCOVLines &Lines = Block.getFile(SP.getFilename());
516 Lines.addLine(Loc.getLine());
519 EdgeDestinations += Func->getEdgeDestinations();
522 FileChecksums.push_back(hash_value(EdgeDestinations));
523 out.write("oncg", 4);
524 out.write(ReversedVersion, 4);
525 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
527 for (SmallVectorImpl<GCOVFunction *>::iterator I = Funcs.begin(),
528 E = Funcs.end(); I != E; ++I) {
529 GCOVFunction *Func = *I;
530 Func->setCfgChecksum(FileChecksums.back());
534 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
539 bool GCOVProfiler::emitProfileArcs() {
540 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
541 if (!CU_Nodes) return false;
544 bool InsertIndCounterIncrCode = false;
545 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
546 DICompileUnit CU(CU_Nodes->getOperand(i));
547 DIArray SPs = CU.getSubprograms();
548 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
549 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
550 DISubprogram SP(SPs.getElement(i));
551 assert((!SP || SP.isSubprogram()) &&
552 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
555 Function *F = SP.getFunction();
557 if (!Result) Result = true;
559 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
560 TerminatorInst *TI = BB->getTerminator();
561 if (isa<ReturnInst>(TI))
564 Edges += TI->getNumSuccessors();
567 ArrayType *CounterTy =
568 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
569 GlobalVariable *Counters =
570 new GlobalVariable(*M, CounterTy, false,
571 GlobalValue::InternalLinkage,
572 Constant::getNullValue(CounterTy),
574 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
576 UniqueVector<BasicBlock *> ComplexEdgePreds;
577 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
580 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
581 TerminatorInst *TI = BB->getTerminator();
582 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
584 if (Successors == 1) {
585 IRBuilder<> Builder(BB->getFirstInsertionPt());
586 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
588 Value *Count = Builder.CreateLoad(Counter);
589 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
590 Builder.CreateStore(Count, Counter);
591 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
592 IRBuilder<> Builder(BI);
593 Value *Sel = Builder.CreateSelect(BI->getCondition(),
594 Builder.getInt64(Edge),
595 Builder.getInt64(Edge + 1));
596 SmallVector<Value *, 2> Idx;
597 Idx.push_back(Builder.getInt64(0));
599 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
600 Value *Count = Builder.CreateLoad(Counter);
601 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
602 Builder.CreateStore(Count, Counter);
604 ComplexEdgePreds.insert(BB);
605 for (int i = 0; i != Successors; ++i)
606 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
613 if (!ComplexEdgePreds.empty()) {
614 GlobalVariable *EdgeTable =
615 buildEdgeLookupTable(F, Counters,
616 ComplexEdgePreds, ComplexEdgeSuccs);
617 GlobalVariable *EdgeState = getEdgeStateValue();
619 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
620 IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
621 Builder.CreateStore(Builder.getInt32(i), EdgeState);
624 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
625 // Call runtime to perform increment.
626 IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
627 Value *CounterPtrArray =
628 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
629 i * ComplexEdgePreds.size());
631 // Build code to increment the counter.
632 InsertIndCounterIncrCode = true;
633 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
634 EdgeState, CounterPtrArray);
639 Function *WriteoutF = insertCounterWriteout(CountersBySP);
640 Function *FlushF = insertFlush(CountersBySP);
642 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
643 // be executed at exit and the "__llvm_gcov_flush" function to be executed
644 // when "__gcov_flush" is called.
645 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
646 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
647 "__llvm_gcov_init", M);
648 F->setUnnamedAddr(true);
649 F->setLinkage(GlobalValue::InternalLinkage);
650 F->addFnAttr(Attribute::NoInline);
651 if (Options.NoRedZone)
652 F->addFnAttr(Attribute::NoRedZone);
654 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
655 IRBuilder<> Builder(BB);
657 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
659 PointerType::get(FTy, 0),
660 PointerType::get(FTy, 0)
662 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
664 // Initialize the environment and register the local writeout and flush
666 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
667 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
668 Builder.CreateRetVoid();
670 appendToGlobalCtors(*M, F, 0);
673 if (InsertIndCounterIncrCode)
674 insertIndirectCounterIncrement();
679 // All edges with successors that aren't branches are "complex", because it
680 // requires complex logic to pick which counter to update.
681 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
683 GlobalVariable *Counters,
684 const UniqueVector<BasicBlock *> &Preds,
685 const UniqueVector<BasicBlock *> &Succs) {
686 // TODO: support invoke, threads. We rely on the fact that nothing can modify
687 // the whole-Module pred edge# between the time we set it and the time we next
688 // read it. Threads and invoke make this untrue.
690 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
691 size_t TableSize = Succs.size() * Preds.size();
692 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
693 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
695 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
696 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
697 for (size_t i = 0; i != TableSize; ++i)
698 EdgeTable[i] = NullValue;
701 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
702 TerminatorInst *TI = BB->getTerminator();
703 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
704 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
705 for (int i = 0; i != Successors; ++i) {
706 BasicBlock *Succ = TI->getSuccessor(i);
707 IRBuilder<> Builder(Succ);
708 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
710 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
711 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
717 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
718 GlobalVariable *EdgeTableGV =
720 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
721 ConstantArray::get(EdgeTableTy, V),
722 "__llvm_gcda_edge_table");
723 EdgeTableGV->setUnnamedAddr(true);
727 Constant *GCOVProfiler::getStartFileFunc() {
729 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
730 Type::getInt8PtrTy(*Ctx), // const char version[4]
731 Type::getInt32Ty(*Ctx), // uint32_t checksum
733 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
734 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
737 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
738 Type *Int32Ty = Type::getInt32Ty(*Ctx);
739 Type *Int64Ty = Type::getInt64Ty(*Ctx);
741 Int32Ty->getPointerTo(), // uint32_t *predecessor
742 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
744 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
745 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
748 Constant *GCOVProfiler::getEmitFunctionFunc() {
750 Type::getInt32Ty(*Ctx), // uint32_t ident
751 Type::getInt8PtrTy(*Ctx), // const char *function_name
752 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
753 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
754 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
756 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
757 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
760 Constant *GCOVProfiler::getEmitArcsFunc() {
762 Type::getInt32Ty(*Ctx), // uint32_t num_counters
763 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
765 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
766 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
769 Constant *GCOVProfiler::getSummaryInfoFunc() {
770 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
771 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
774 Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
775 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
776 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
779 Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
780 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
781 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
784 Constant *GCOVProfiler::getEndFileFunc() {
785 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
786 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
789 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
790 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
792 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
793 GlobalValue::InternalLinkage,
794 ConstantInt::get(Type::getInt32Ty(*Ctx),
796 "__llvm_gcov_global_state_pred");
797 GV->setUnnamedAddr(true);
802 Function *GCOVProfiler::insertCounterWriteout(
803 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
804 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
805 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
807 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
808 "__llvm_gcov_writeout", M);
809 WriteoutF->setUnnamedAddr(true);
810 WriteoutF->addFnAttr(Attribute::NoInline);
811 if (Options.NoRedZone)
812 WriteoutF->addFnAttr(Attribute::NoRedZone);
814 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
815 IRBuilder<> Builder(BB);
817 Constant *StartFile = getStartFileFunc();
818 Constant *EmitFunction = getEmitFunctionFunc();
819 Constant *EmitArcs = getEmitArcsFunc();
820 Constant *SummaryInfo = getSummaryInfoFunc();
821 Constant *EndFile = getEndFileFunc();
823 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
825 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
826 DICompileUnit CU(CU_Nodes->getOperand(i));
827 std::string FilenameGcda = mangleName(CU, "gcda");
828 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
829 Builder.CreateCall3(StartFile,
830 Builder.CreateGlobalStringPtr(FilenameGcda),
831 Builder.CreateGlobalStringPtr(ReversedVersion),
832 Builder.getInt32(CfgChecksum));
833 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
834 DISubprogram SP(CountersBySP[j].second);
835 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
837 EmitFunction, Builder.getInt32(j),
838 Options.FunctionNamesInData ?
839 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
840 Constant::getNullValue(Builder.getInt8PtrTy()),
841 Builder.getInt32(FuncChecksum),
842 Builder.getInt8(Options.UseCfgChecksum),
843 Builder.getInt32(CfgChecksum));
845 GlobalVariable *GV = CountersBySP[j].first;
847 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
848 Builder.CreateCall2(EmitArcs,
849 Builder.getInt32(Arcs),
850 Builder.CreateConstGEP2_64(GV, 0, 0));
852 Builder.CreateCall(SummaryInfo);
853 Builder.CreateCall(EndFile);
857 Builder.CreateRetVoid();
861 void GCOVProfiler::insertIndirectCounterIncrement() {
863 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
864 Fn->setUnnamedAddr(true);
865 Fn->setLinkage(GlobalValue::InternalLinkage);
866 Fn->addFnAttr(Attribute::NoInline);
867 if (Options.NoRedZone)
868 Fn->addFnAttr(Attribute::NoRedZone);
870 // Create basic blocks for function.
871 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
872 IRBuilder<> Builder(BB);
874 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
875 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
876 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
878 // uint32_t pred = *predecessor;
879 // if (pred == 0xffffffff) return;
880 Argument *Arg = Fn->arg_begin();
881 Arg->setName("predecessor");
882 Value *Pred = Builder.CreateLoad(Arg, "pred");
883 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
884 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
886 Builder.SetInsertPoint(PredNotNegOne);
888 // uint64_t *counter = counters[pred];
889 // if (!counter) return;
890 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
891 Arg = llvm::next(Fn->arg_begin());
892 Arg->setName("counters");
893 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
894 Value *Counter = Builder.CreateLoad(GEP, "counter");
895 Cond = Builder.CreateICmpEQ(Counter,
896 Constant::getNullValue(
897 Builder.getInt64Ty()->getPointerTo()));
898 Builder.CreateCondBr(Cond, Exit, CounterEnd);
901 Builder.SetInsertPoint(CounterEnd);
902 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
903 Builder.getInt64(1));
904 Builder.CreateStore(Add, Counter);
905 Builder.CreateBr(Exit);
907 // Fill in the exit block.
908 Builder.SetInsertPoint(Exit);
909 Builder.CreateRetVoid();
912 Function *GCOVProfiler::
913 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
914 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
915 Function *FlushF = M->getFunction("__llvm_gcov_flush");
917 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
918 "__llvm_gcov_flush", M);
920 FlushF->setLinkage(GlobalValue::InternalLinkage);
921 FlushF->setUnnamedAddr(true);
922 FlushF->addFnAttr(Attribute::NoInline);
923 if (Options.NoRedZone)
924 FlushF->addFnAttr(Attribute::NoRedZone);
926 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
928 // Write out the current counters.
929 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
930 assert(WriteoutF && "Need to create the writeout function first!");
932 IRBuilder<> Builder(Entry);
933 Builder.CreateCall(WriteoutF);
935 // Zero out the counters.
936 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
937 I = CountersBySP.begin(), E = CountersBySP.end();
939 GlobalVariable *GV = I->first;
940 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
941 Builder.CreateStore(Null, GV);
944 Type *RetTy = FlushF->getReturnType();
945 if (RetTy == Type::getVoidTy(*Ctx))
946 Builder.CreateRetVoid();
947 else if (RetTy->isIntegerTy())
948 // Used if __llvm_gcov_flush was implicitly declared.
949 Builder.CreateRet(ConstantInt::get(RetTy, 0));
951 report_fatal_error("invalid return type for __llvm_gcov_flush");