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 "ProfilingUtils.h"
21 #include "llvm/ADT/DenseMap.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/InstIterator.h"
36 #include "llvm/Support/PathV2.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/Utils/ModuleUtils.h"
43 static cl::opt<std::string>
44 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
47 GCOVOptions GCOVOptions::getDefault() {
49 Options.EmitNotes = true;
50 Options.EmitData = true;
51 Options.UseCfgChecksum = false;
52 Options.NoRedZone = false;
53 Options.FunctionNamesInData = true;
55 if (DefaultGCOVVersion.size() != 4) {
56 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
59 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
64 class GCOVProfiler : public ModulePass {
67 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
68 ReversedVersion[0] = Options.Version[3];
69 ReversedVersion[1] = Options.Version[2];
70 ReversedVersion[2] = Options.Version[1];
71 ReversedVersion[3] = Options.Version[0];
72 ReversedVersion[4] = '\0';
73 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
75 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
76 assert((Options.EmitNotes || Options.EmitData) &&
77 "GCOVProfiler asked to do nothing?");
78 ReversedVersion[0] = Options.Version[3];
79 ReversedVersion[1] = Options.Version[2];
80 ReversedVersion[2] = Options.Version[1];
81 ReversedVersion[3] = Options.Version[0];
82 ReversedVersion[4] = '\0';
83 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
85 virtual const char *getPassName() const {
86 return "GCOV Profiler";
90 bool runOnModule(Module &M);
92 // Create the .gcno files for the Module based on DebugInfo.
93 void emitProfileNotes();
95 // Modify the program to track transitions along edges and call into the
96 // profiling runtime to emit .gcda files when run.
97 bool emitProfileArcs();
99 // Get pointers to the functions in the runtime library.
100 Constant *getStartFileFunc();
101 Constant *getIncrementIndirectCounterFunc();
102 Constant *getEmitFunctionFunc();
103 Constant *getEmitArcsFunc();
104 Constant *getDeleteFlushFunctionListFunc();
105 Constant *getEndFileFunc();
107 // Create or retrieve an i32 state value that is used to represent the
108 // pred block number for certain non-trivial edges.
109 GlobalVariable *getEdgeStateValue();
111 // Produce a table of pointers to counters, by predecessor and successor
113 GlobalVariable *buildEdgeLookupTable(Function *F,
114 GlobalVariable *Counter,
115 const UniqueVector<BasicBlock *>&Preds,
116 const UniqueVector<BasicBlock*>&Succs);
118 // Add the function to write out all our counters to the global destructor
120 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
122 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
123 void insertIndirectCounterIncrement();
125 std::string mangleName(DICompileUnit CU, const char *NewStem);
129 // Reversed, NUL-terminated copy of Options.Version.
130 char ReversedVersion[5];
137 char GCOVProfiler::ID = 0;
138 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
139 "Insert instrumentation for GCOV profiling", false, false)
141 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
142 return new GCOVProfiler(Options);
145 static std::string getFunctionName(DISubprogram SP) {
146 if (!SP.getLinkageName().empty())
147 return SP.getLinkageName();
154 static const char *LinesTag;
155 static const char *FunctionTag;
156 static const char *BlockTag;
157 static const char *EdgeTag;
161 void writeBytes(const char *Bytes, int Size) {
162 os->write(Bytes, Size);
165 void write(uint32_t i) {
166 writeBytes(reinterpret_cast<char*>(&i), 4);
169 // Returns the length measured in 4-byte blocks that will be used to
170 // represent this string in a GCOV file
171 unsigned lengthOfGCOVString(StringRef s) {
172 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
173 // padding out to the next 4-byte word. The length is measured in 4-byte
174 // words including padding, not bytes of actual string.
175 return (s.size() / 4) + 1;
178 void writeGCOVString(StringRef s) {
179 uint32_t Len = lengthOfGCOVString(s);
181 writeBytes(s.data(), s.size());
183 // Write 1 to 4 bytes of NUL padding.
184 assert((unsigned)(4 - (s.size() % 4)) > 0);
185 assert((unsigned)(4 - (s.size() % 4)) <= 4);
186 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
191 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
192 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
193 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
194 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
199 // Constructed only by requesting it from a GCOVBlock, this object stores a
200 // list of line numbers and a single filename, representing lines that belong
202 class GCOVLines : public GCOVRecord {
204 void addLine(uint32_t Line) {
205 Lines.push_back(Line);
209 // Here 2 = 1 for string length + 1 for '0' id#.
210 return lengthOfGCOVString(Filename) + 2 + Lines.size();
215 writeGCOVString(Filename);
216 for (int i = 0, e = Lines.size(); i != e; ++i)
220 GCOVLines(StringRef F, raw_ostream *os)
227 SmallVector<uint32_t, 32> Lines;
230 // Represent a basic block in GCOV. Each block has a unique number in the
231 // function, number of lines belonging to each block, and a set of edges to
233 class GCOVBlock : public GCOVRecord {
235 GCOVLines &getFile(StringRef Filename) {
236 GCOVLines *&Lines = LinesByFile[Filename];
238 Lines = new GCOVLines(Filename, os);
243 void addEdge(GCOVBlock &Successor) {
244 OutEdges.push_back(&Successor);
249 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
250 E = LinesByFile.end(); I != E; ++I) {
251 Len += I->second->length();
254 writeBytes(LinesTag, 4);
257 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
258 E = LinesByFile.end(); I != E; ++I)
259 I->second->writeOut();
265 DeleteContainerSeconds(LinesByFile);
269 friend class GCOVFunction;
271 GCOVBlock(uint32_t Number, raw_ostream *os)
277 StringMap<GCOVLines *> LinesByFile;
278 SmallVector<GCOVBlock *, 4> OutEdges;
281 // A function has a unique identifier, a checksum (we leave as zero) and a
282 // set of blocks and a map of edges between blocks. This is the only GCOV
283 // object users can construct, the blocks and lines will be rooted here.
284 class GCOVFunction : public GCOVRecord {
286 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
287 bool UseCfgChecksum) {
290 Function *F = SP.getFunction();
291 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
293 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
294 Blocks[BB] = new GCOVBlock(i++, os);
296 ReturnBlock = new GCOVBlock(i++, os);
298 writeBytes(FunctionTag, 4);
299 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
300 1 + lengthOfGCOVString(SP.getFilename()) + 1;
305 write(0); // lineno checksum
307 write(0); // cfg checksum
308 writeGCOVString(getFunctionName(SP));
309 writeGCOVString(SP.getFilename());
310 write(SP.getLineNumber());
314 DeleteContainerSeconds(Blocks);
318 GCOVBlock &getBlock(BasicBlock *BB) {
322 GCOVBlock &getReturnBlock() {
327 // Emit count of blocks.
328 writeBytes(BlockTag, 4);
329 write(Blocks.size() + 1);
330 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
331 write(0); // No flags on our blocks.
333 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
335 // Emit edges between blocks.
336 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
337 E = Blocks.end(); I != E; ++I) {
338 GCOVBlock &Block = *I->second;
339 if (Block.OutEdges.empty()) continue;
341 writeBytes(EdgeTag, 4);
342 write(Block.OutEdges.size() * 2 + 1);
344 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
345 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
347 write(Block.OutEdges[i]->Number);
348 write(0); // no flags
352 // Emit lines for each block.
353 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
354 E = Blocks.end(); I != E; ++I) {
355 I->second->writeOut();
360 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
361 GCOVBlock *ReturnBlock;
365 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
366 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
367 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
368 MDNode *N = GCov->getOperand(i);
369 if (N->getNumOperands() != 2) continue;
370 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
371 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
372 if (!GCovFile || !CompileUnit) continue;
373 if (CompileUnit == CU) {
374 SmallString<128> Filename = GCovFile->getString();
375 sys::path::replace_extension(Filename, NewStem);
376 return Filename.str();
381 SmallString<128> Filename = CU.getFilename();
382 sys::path::replace_extension(Filename, NewStem);
383 return sys::path::filename(Filename.str());
386 bool GCOVProfiler::runOnModule(Module &M) {
388 Ctx = &M.getContext();
390 if (Options.EmitNotes) emitProfileNotes();
391 if (Options.EmitData) return emitProfileArcs();
395 void GCOVProfiler::emitProfileNotes() {
396 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
397 if (!CU_Nodes) return;
399 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
400 // Each compile unit gets its own .gcno file. This means that whether we run
401 // this pass over the original .o's as they're produced, or run it after
402 // LTO, we'll generate the same .gcno files.
404 DICompileUnit CU(CU_Nodes->getOperand(i));
405 std::string ErrorInfo;
406 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
407 raw_fd_ostream::F_Binary);
408 out.write("oncg", 4);
409 out.write(ReversedVersion, 4);
410 out.write("MVLL", 4);
412 DIArray SPs = CU.getSubprograms();
413 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
414 DISubprogram SP(SPs.getElement(i));
415 if (!SP.Verify()) continue;
417 Function *F = SP.getFunction();
419 GCOVFunction Func(SP, &out, i, Options.UseCfgChecksum);
421 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
422 GCOVBlock &Block = Func.getBlock(BB);
423 TerminatorInst *TI = BB->getTerminator();
424 if (int successors = TI->getNumSuccessors()) {
425 for (int i = 0; i != successors; ++i) {
426 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
428 } else if (isa<ReturnInst>(TI)) {
429 Block.addEdge(Func.getReturnBlock());
433 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
435 const DebugLoc &Loc = I->getDebugLoc();
436 if (Loc.isUnknown()) continue;
437 if (Line == Loc.getLine()) continue;
438 Line = Loc.getLine();
439 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
441 GCOVLines &Lines = Block.getFile(SP.getFilename());
442 Lines.addLine(Loc.getLine());
447 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
452 bool GCOVProfiler::emitProfileArcs() {
453 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
454 if (!CU_Nodes) return false;
457 bool InsertIndCounterIncrCode = false;
458 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
459 DICompileUnit CU(CU_Nodes->getOperand(i));
460 DIArray SPs = CU.getSubprograms();
461 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
462 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
463 DISubprogram SP(SPs.getElement(i));
464 if (!SP.Verify()) continue;
465 Function *F = SP.getFunction();
467 if (!Result) Result = true;
469 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
470 TerminatorInst *TI = BB->getTerminator();
471 if (isa<ReturnInst>(TI))
474 Edges += TI->getNumSuccessors();
477 ArrayType *CounterTy =
478 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
479 GlobalVariable *Counters =
480 new GlobalVariable(*M, CounterTy, false,
481 GlobalValue::InternalLinkage,
482 Constant::getNullValue(CounterTy),
484 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
486 UniqueVector<BasicBlock *> ComplexEdgePreds;
487 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
490 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
491 TerminatorInst *TI = BB->getTerminator();
492 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
494 IRBuilder<> Builder(TI);
496 if (Successors == 1) {
497 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
499 Value *Count = Builder.CreateLoad(Counter);
500 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
501 Builder.CreateStore(Count, Counter);
502 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
503 Value *Sel = Builder.CreateSelect(BI->getCondition(),
504 Builder.getInt64(Edge),
505 Builder.getInt64(Edge + 1));
506 SmallVector<Value *, 2> Idx;
507 Idx.push_back(Builder.getInt64(0));
509 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
510 Value *Count = Builder.CreateLoad(Counter);
511 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
512 Builder.CreateStore(Count, Counter);
514 ComplexEdgePreds.insert(BB);
515 for (int i = 0; i != Successors; ++i)
516 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
522 if (!ComplexEdgePreds.empty()) {
523 GlobalVariable *EdgeTable =
524 buildEdgeLookupTable(F, Counters,
525 ComplexEdgePreds, ComplexEdgeSuccs);
526 GlobalVariable *EdgeState = getEdgeStateValue();
528 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
529 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
530 Builder.CreateStore(Builder.getInt32(i), EdgeState);
532 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
533 // call runtime to perform increment
534 BasicBlock::iterator InsertPt =
535 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
536 IRBuilder<> Builder(InsertPt);
537 Value *CounterPtrArray =
538 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
539 i * ComplexEdgePreds.size());
541 // Build code to increment the counter.
542 InsertIndCounterIncrCode = true;
543 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
544 EdgeState, CounterPtrArray);
549 Function *WriteoutF = insertCounterWriteout(CountersBySP);
550 Function *FlushF = insertFlush(CountersBySP);
552 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
553 // be executed at exit and the "__llvm_gcov_flush" function to be executed
554 // when "__gcov_flush" is called.
555 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
556 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
557 "__llvm_gcov_init", M);
558 F->setUnnamedAddr(true);
559 F->setLinkage(GlobalValue::InternalLinkage);
560 F->addFnAttr(Attribute::NoInline);
561 if (Options.NoRedZone)
562 F->addFnAttr(Attribute::NoRedZone);
564 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
565 IRBuilder<> Builder(BB);
567 FTy = FunctionType::get(Builder.getInt32Ty(),
568 PointerType::get(FTy, 0), false);
569 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
570 Builder.CreateCall(AtExitFn, WriteoutF);
572 // Register the local flush function.
573 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
574 FTy = FunctionType::get(Builder.getVoidTy(),
575 PointerType::get(FTy, 0), false);
577 M->getOrInsertFunction("llvm_register_flush_function", FTy);
578 Builder.CreateCall(RegFlush, FlushF);
580 // Make sure that all the flush function list is deleted.
581 Builder.CreateCall(AtExitFn, getDeleteFlushFunctionListFunc());
582 Builder.CreateRetVoid();
584 appendToGlobalCtors(*M, F, 0);
587 if (InsertIndCounterIncrCode)
588 insertIndirectCounterIncrement();
593 // All edges with successors that aren't branches are "complex", because it
594 // requires complex logic to pick which counter to update.
595 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
597 GlobalVariable *Counters,
598 const UniqueVector<BasicBlock *> &Preds,
599 const UniqueVector<BasicBlock *> &Succs) {
600 // TODO: support invoke, threads. We rely on the fact that nothing can modify
601 // the whole-Module pred edge# between the time we set it and the time we next
602 // read it. Threads and invoke make this untrue.
604 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
605 size_t TableSize = Succs.size() * Preds.size();
606 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
607 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
609 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
610 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
611 for (size_t i = 0; i != TableSize; ++i)
612 EdgeTable[i] = NullValue;
615 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
616 TerminatorInst *TI = BB->getTerminator();
617 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
618 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
619 for (int i = 0; i != Successors; ++i) {
620 BasicBlock *Succ = TI->getSuccessor(i);
621 IRBuilder<> Builder(Succ);
622 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
624 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
625 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
631 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
632 GlobalVariable *EdgeTableGV =
634 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
635 ConstantArray::get(EdgeTableTy, V),
636 "__llvm_gcda_edge_table");
637 EdgeTableGV->setUnnamedAddr(true);
641 Constant *GCOVProfiler::getStartFileFunc() {
643 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
644 Type::getInt8PtrTy(*Ctx), // const char version[4]
646 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
647 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
650 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
651 Type *Int32Ty = Type::getInt32Ty(*Ctx);
652 Type *Int64Ty = Type::getInt64Ty(*Ctx);
654 Int32Ty->getPointerTo(), // uint32_t *predecessor
655 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
657 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
658 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
661 Constant *GCOVProfiler::getEmitFunctionFunc() {
663 Type::getInt32Ty(*Ctx), // uint32_t ident
664 Type::getInt8PtrTy(*Ctx), // const char *function_name
665 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
667 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
668 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
671 Constant *GCOVProfiler::getEmitArcsFunc() {
673 Type::getInt32Ty(*Ctx), // uint32_t num_counters
674 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
676 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
677 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
680 Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
681 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
682 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
685 Constant *GCOVProfiler::getEndFileFunc() {
686 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
687 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
690 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
691 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
693 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
694 GlobalValue::InternalLinkage,
695 ConstantInt::get(Type::getInt32Ty(*Ctx),
697 "__llvm_gcov_global_state_pred");
698 GV->setUnnamedAddr(true);
703 Function *GCOVProfiler::insertCounterWriteout(
704 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
705 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
706 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
708 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
709 "__llvm_gcov_writeout", M);
710 WriteoutF->setUnnamedAddr(true);
711 WriteoutF->addFnAttr(Attribute::NoInline);
712 if (Options.NoRedZone)
713 WriteoutF->addFnAttr(Attribute::NoRedZone);
715 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
716 IRBuilder<> Builder(BB);
718 Constant *StartFile = getStartFileFunc();
719 Constant *EmitFunction = getEmitFunctionFunc();
720 Constant *EmitArcs = getEmitArcsFunc();
721 Constant *EndFile = getEndFileFunc();
723 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
725 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
726 DICompileUnit CU(CU_Nodes->getOperand(i));
727 std::string FilenameGcda = mangleName(CU, "gcda");
728 Builder.CreateCall2(StartFile,
729 Builder.CreateGlobalStringPtr(FilenameGcda),
730 Builder.CreateGlobalStringPtr(ReversedVersion));
731 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
732 DISubprogram SP(CountersBySP[j].second);
734 EmitFunction, Builder.getInt32(j),
735 Options.FunctionNamesInData ?
736 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
737 Constant::getNullValue(Builder.getInt8PtrTy()),
738 Builder.getInt8(Options.UseCfgChecksum));
740 GlobalVariable *GV = CountersBySP[j].first;
742 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
743 Builder.CreateCall2(EmitArcs,
744 Builder.getInt32(Arcs),
745 Builder.CreateConstGEP2_64(GV, 0, 0));
747 Builder.CreateCall(EndFile);
751 Builder.CreateRetVoid();
755 void GCOVProfiler::insertIndirectCounterIncrement() {
757 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
758 Fn->setUnnamedAddr(true);
759 Fn->setLinkage(GlobalValue::InternalLinkage);
760 Fn->addFnAttr(Attribute::NoInline);
761 if (Options.NoRedZone)
762 Fn->addFnAttr(Attribute::NoRedZone);
764 // Create basic blocks for function.
765 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
766 IRBuilder<> Builder(BB);
768 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
769 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
770 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
772 // uint32_t pred = *predecessor;
773 // if (pred == 0xffffffff) return;
774 Argument *Arg = Fn->arg_begin();
775 Arg->setName("predecessor");
776 Value *Pred = Builder.CreateLoad(Arg, "pred");
777 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
778 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
780 Builder.SetInsertPoint(PredNotNegOne);
782 // uint64_t *counter = counters[pred];
783 // if (!counter) return;
784 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
785 Arg = llvm::next(Fn->arg_begin());
786 Arg->setName("counters");
787 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
788 Value *Counter = Builder.CreateLoad(GEP, "counter");
789 Cond = Builder.CreateICmpEQ(Counter,
790 Constant::getNullValue(
791 Builder.getInt64Ty()->getPointerTo()));
792 Builder.CreateCondBr(Cond, Exit, CounterEnd);
795 Builder.SetInsertPoint(CounterEnd);
796 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
797 Builder.getInt64(1));
798 Builder.CreateStore(Add, Counter);
799 Builder.CreateBr(Exit);
801 // Fill in the exit block.
802 Builder.SetInsertPoint(Exit);
803 Builder.CreateRetVoid();
806 Function *GCOVProfiler::
807 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
808 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
809 Function *FlushF = M->getFunction("__llvm_gcov_flush");
811 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
812 "__llvm_gcov_flush", M);
814 FlushF->setLinkage(GlobalValue::InternalLinkage);
815 FlushF->setUnnamedAddr(true);
816 FlushF->addFnAttr(Attribute::NoInline);
817 if (Options.NoRedZone)
818 FlushF->addFnAttr(Attribute::NoRedZone);
820 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
822 // Write out the current counters.
823 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
824 assert(WriteoutF && "Need to create the writeout function first!");
826 IRBuilder<> Builder(Entry);
827 Builder.CreateCall(WriteoutF);
829 // Zero out the counters.
830 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
831 I = CountersBySP.begin(), E = CountersBySP.end();
833 GlobalVariable *GV = I->first;
834 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
835 Builder.CreateStore(Null, GV);
838 Type *RetTy = FlushF->getReturnType();
839 if (RetTy == Type::getVoidTy(*Ctx))
840 Builder.CreateRetVoid();
841 else if (RetTy->isIntegerTy())
842 // Used if __llvm_gcov_flush was implicitly declared.
843 Builder.CreateRet(ConstantInt::get(RetTy, 0));
845 report_fatal_error("invalid return type for __llvm_gcov_flush");