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 *getDeleteWriteoutFunctionListFunc();
105 Constant *getDeleteFlushFunctionListFunc();
106 Constant *getEndFileFunc();
108 // Create or retrieve an i32 state value that is used to represent the
109 // pred block number for certain non-trivial edges.
110 GlobalVariable *getEdgeStateValue();
112 // Produce a table of pointers to counters, by predecessor and successor
114 GlobalVariable *buildEdgeLookupTable(Function *F,
115 GlobalVariable *Counter,
116 const UniqueVector<BasicBlock *>&Preds,
117 const UniqueVector<BasicBlock*>&Succs);
119 // Add the function to write out all our counters to the global destructor
121 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
123 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
124 void insertIndirectCounterIncrement();
126 std::string mangleName(DICompileUnit CU, const char *NewStem);
130 // Reversed, NUL-terminated copy of Options.Version.
131 char ReversedVersion[5];
138 char GCOVProfiler::ID = 0;
139 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
140 "Insert instrumentation for GCOV profiling", false, false)
142 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
143 return new GCOVProfiler(Options);
146 static std::string getFunctionName(DISubprogram SP) {
147 if (!SP.getLinkageName().empty())
148 return SP.getLinkageName();
155 static const char *LinesTag;
156 static const char *FunctionTag;
157 static const char *BlockTag;
158 static const char *EdgeTag;
162 void writeBytes(const char *Bytes, int Size) {
163 os->write(Bytes, Size);
166 void write(uint32_t i) {
167 writeBytes(reinterpret_cast<char*>(&i), 4);
170 // Returns the length measured in 4-byte blocks that will be used to
171 // represent this string in a GCOV file
172 unsigned lengthOfGCOVString(StringRef s) {
173 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
174 // padding out to the next 4-byte word. The length is measured in 4-byte
175 // words including padding, not bytes of actual string.
176 return (s.size() / 4) + 1;
179 void writeGCOVString(StringRef s) {
180 uint32_t Len = lengthOfGCOVString(s);
182 writeBytes(s.data(), s.size());
184 // Write 1 to 4 bytes of NUL padding.
185 assert((unsigned)(4 - (s.size() % 4)) > 0);
186 assert((unsigned)(4 - (s.size() % 4)) <= 4);
187 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
192 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
193 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
194 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
195 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
200 // Constructed only by requesting it from a GCOVBlock, this object stores a
201 // list of line numbers and a single filename, representing lines that belong
203 class GCOVLines : public GCOVRecord {
205 void addLine(uint32_t Line) {
206 Lines.push_back(Line);
210 // Here 2 = 1 for string length + 1 for '0' id#.
211 return lengthOfGCOVString(Filename) + 2 + Lines.size();
216 writeGCOVString(Filename);
217 for (int i = 0, e = Lines.size(); i != e; ++i)
221 GCOVLines(StringRef F, raw_ostream *os)
228 SmallVector<uint32_t, 32> Lines;
231 // Represent a basic block in GCOV. Each block has a unique number in the
232 // function, number of lines belonging to each block, and a set of edges to
234 class GCOVBlock : public GCOVRecord {
236 GCOVLines &getFile(StringRef Filename) {
237 GCOVLines *&Lines = LinesByFile[Filename];
239 Lines = new GCOVLines(Filename, os);
244 void addEdge(GCOVBlock &Successor) {
245 OutEdges.push_back(&Successor);
250 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
251 E = LinesByFile.end(); I != E; ++I) {
252 Len += I->second->length();
255 writeBytes(LinesTag, 4);
258 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
259 E = LinesByFile.end(); I != E; ++I)
260 I->second->writeOut();
266 DeleteContainerSeconds(LinesByFile);
270 friend class GCOVFunction;
272 GCOVBlock(uint32_t Number, raw_ostream *os)
278 StringMap<GCOVLines *> LinesByFile;
279 SmallVector<GCOVBlock *, 4> OutEdges;
282 // A function has a unique identifier, a checksum (we leave as zero) and a
283 // set of blocks and a map of edges between blocks. This is the only GCOV
284 // object users can construct, the blocks and lines will be rooted here.
285 class GCOVFunction : public GCOVRecord {
287 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
288 bool UseCfgChecksum) {
291 Function *F = SP.getFunction();
292 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
294 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
295 Blocks[BB] = new GCOVBlock(i++, os);
297 ReturnBlock = new GCOVBlock(i++, os);
299 writeBytes(FunctionTag, 4);
300 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
301 1 + lengthOfGCOVString(SP.getFilename()) + 1;
306 write(0); // lineno checksum
308 write(0); // cfg checksum
309 writeGCOVString(getFunctionName(SP));
310 writeGCOVString(SP.getFilename());
311 write(SP.getLineNumber());
315 DeleteContainerSeconds(Blocks);
319 GCOVBlock &getBlock(BasicBlock *BB) {
323 GCOVBlock &getReturnBlock() {
328 // Emit count of blocks.
329 writeBytes(BlockTag, 4);
330 write(Blocks.size() + 1);
331 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
332 write(0); // No flags on our blocks.
334 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
336 // Emit edges between blocks.
337 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
338 E = Blocks.end(); I != E; ++I) {
339 GCOVBlock &Block = *I->second;
340 if (Block.OutEdges.empty()) continue;
342 writeBytes(EdgeTag, 4);
343 write(Block.OutEdges.size() * 2 + 1);
345 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
346 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
348 write(Block.OutEdges[i]->Number);
349 write(0); // no flags
353 // Emit lines for each block.
354 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
355 E = Blocks.end(); I != E; ++I) {
356 I->second->writeOut();
361 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
362 GCOVBlock *ReturnBlock;
366 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
367 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
368 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
369 MDNode *N = GCov->getOperand(i);
370 if (N->getNumOperands() != 2) continue;
371 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
372 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
373 if (!GCovFile || !CompileUnit) continue;
374 if (CompileUnit == CU) {
375 SmallString<128> Filename = GCovFile->getString();
376 sys::path::replace_extension(Filename, NewStem);
377 return Filename.str();
382 SmallString<128> Filename = CU.getFilename();
383 sys::path::replace_extension(Filename, NewStem);
384 return sys::path::filename(Filename.str());
387 bool GCOVProfiler::runOnModule(Module &M) {
389 Ctx = &M.getContext();
391 if (Options.EmitNotes) emitProfileNotes();
392 if (Options.EmitData) return emitProfileArcs();
396 void GCOVProfiler::emitProfileNotes() {
397 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
398 if (!CU_Nodes) return;
400 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
401 // Each compile unit gets its own .gcno file. This means that whether we run
402 // this pass over the original .o's as they're produced, or run it after
403 // LTO, we'll generate the same .gcno files.
405 DICompileUnit CU(CU_Nodes->getOperand(i));
406 std::string ErrorInfo;
407 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
408 raw_fd_ostream::F_Binary);
409 out.write("oncg", 4);
410 out.write(ReversedVersion, 4);
411 out.write("MVLL", 4);
413 DIArray SPs = CU.getSubprograms();
414 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
415 DISubprogram SP(SPs.getElement(i));
416 if (!SP.Verify()) continue;
418 Function *F = SP.getFunction();
420 GCOVFunction Func(SP, &out, i, Options.UseCfgChecksum);
422 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
423 GCOVBlock &Block = Func.getBlock(BB);
424 TerminatorInst *TI = BB->getTerminator();
425 if (int successors = TI->getNumSuccessors()) {
426 for (int i = 0; i != successors; ++i) {
427 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
429 } else if (isa<ReturnInst>(TI)) {
430 Block.addEdge(Func.getReturnBlock());
434 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
436 const DebugLoc &Loc = I->getDebugLoc();
437 if (Loc.isUnknown()) continue;
438 if (Line == Loc.getLine()) continue;
439 Line = Loc.getLine();
440 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
442 GCOVLines &Lines = Block.getFile(SP.getFilename());
443 Lines.addLine(Loc.getLine());
448 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
453 bool GCOVProfiler::emitProfileArcs() {
454 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
455 if (!CU_Nodes) return false;
458 bool InsertIndCounterIncrCode = false;
459 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
460 DICompileUnit CU(CU_Nodes->getOperand(i));
461 DIArray SPs = CU.getSubprograms();
462 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
463 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
464 DISubprogram SP(SPs.getElement(i));
465 if (!SP.Verify()) continue;
466 Function *F = SP.getFunction();
468 if (!Result) Result = true;
470 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
471 TerminatorInst *TI = BB->getTerminator();
472 if (isa<ReturnInst>(TI))
475 Edges += TI->getNumSuccessors();
478 ArrayType *CounterTy =
479 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
480 GlobalVariable *Counters =
481 new GlobalVariable(*M, CounterTy, false,
482 GlobalValue::InternalLinkage,
483 Constant::getNullValue(CounterTy),
485 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
487 UniqueVector<BasicBlock *> ComplexEdgePreds;
488 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
491 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
492 TerminatorInst *TI = BB->getTerminator();
493 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
495 IRBuilder<> Builder(TI);
497 if (Successors == 1) {
498 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
500 Value *Count = Builder.CreateLoad(Counter);
501 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
502 Builder.CreateStore(Count, Counter);
503 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
504 Value *Sel = Builder.CreateSelect(BI->getCondition(),
505 Builder.getInt64(Edge),
506 Builder.getInt64(Edge + 1));
507 SmallVector<Value *, 2> Idx;
508 Idx.push_back(Builder.getInt64(0));
510 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
511 Value *Count = Builder.CreateLoad(Counter);
512 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
513 Builder.CreateStore(Count, Counter);
515 ComplexEdgePreds.insert(BB);
516 for (int i = 0; i != Successors; ++i)
517 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
523 if (!ComplexEdgePreds.empty()) {
524 GlobalVariable *EdgeTable =
525 buildEdgeLookupTable(F, Counters,
526 ComplexEdgePreds, ComplexEdgeSuccs);
527 GlobalVariable *EdgeState = getEdgeStateValue();
529 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
530 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
531 Builder.CreateStore(Builder.getInt32(i), EdgeState);
533 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
534 // call runtime to perform increment
535 BasicBlock::iterator InsertPt =
536 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
537 IRBuilder<> Builder(InsertPt);
538 Value *CounterPtrArray =
539 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
540 i * ComplexEdgePreds.size());
542 // Build code to increment the counter.
543 InsertIndCounterIncrCode = true;
544 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
545 EdgeState, CounterPtrArray);
550 Function *WriteoutF = insertCounterWriteout(CountersBySP);
551 Function *FlushF = insertFlush(CountersBySP);
553 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
554 // be executed at exit and the "__llvm_gcov_flush" function to be executed
555 // when "__gcov_flush" is called.
556 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
557 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
558 "__llvm_gcov_init", M);
559 F->setUnnamedAddr(true);
560 F->setLinkage(GlobalValue::InternalLinkage);
561 F->addFnAttr(Attribute::NoInline);
562 if (Options.NoRedZone)
563 F->addFnAttr(Attribute::NoRedZone);
565 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
566 IRBuilder<> Builder(BB);
568 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
570 PointerType::get(FTy, 0),
571 PointerType::get(FTy, 0)
573 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
575 // Inialize the environment and register the local writeout and flush
577 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
578 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
579 Builder.CreateRetVoid();
581 appendToGlobalCtors(*M, F, 0);
584 if (InsertIndCounterIncrCode)
585 insertIndirectCounterIncrement();
590 // All edges with successors that aren't branches are "complex", because it
591 // requires complex logic to pick which counter to update.
592 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
594 GlobalVariable *Counters,
595 const UniqueVector<BasicBlock *> &Preds,
596 const UniqueVector<BasicBlock *> &Succs) {
597 // TODO: support invoke, threads. We rely on the fact that nothing can modify
598 // the whole-Module pred edge# between the time we set it and the time we next
599 // read it. Threads and invoke make this untrue.
601 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
602 size_t TableSize = Succs.size() * Preds.size();
603 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
604 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
606 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
607 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
608 for (size_t i = 0; i != TableSize; ++i)
609 EdgeTable[i] = NullValue;
612 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
613 TerminatorInst *TI = BB->getTerminator();
614 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
615 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
616 for (int i = 0; i != Successors; ++i) {
617 BasicBlock *Succ = TI->getSuccessor(i);
618 IRBuilder<> Builder(Succ);
619 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
621 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
622 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
628 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
629 GlobalVariable *EdgeTableGV =
631 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
632 ConstantArray::get(EdgeTableTy, V),
633 "__llvm_gcda_edge_table");
634 EdgeTableGV->setUnnamedAddr(true);
638 Constant *GCOVProfiler::getStartFileFunc() {
640 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
641 Type::getInt8PtrTy(*Ctx), // const char version[4]
643 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
644 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
647 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
648 Type *Int32Ty = Type::getInt32Ty(*Ctx);
649 Type *Int64Ty = Type::getInt64Ty(*Ctx);
651 Int32Ty->getPointerTo(), // uint32_t *predecessor
652 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
654 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
655 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
658 Constant *GCOVProfiler::getEmitFunctionFunc() {
660 Type::getInt32Ty(*Ctx), // uint32_t ident
661 Type::getInt8PtrTy(*Ctx), // const char *function_name
662 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
664 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
665 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
668 Constant *GCOVProfiler::getEmitArcsFunc() {
670 Type::getInt32Ty(*Ctx), // uint32_t num_counters
671 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
673 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
674 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
677 Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
678 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
679 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
682 Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
683 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
684 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
687 Constant *GCOVProfiler::getEndFileFunc() {
688 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
689 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
692 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
693 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
695 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
696 GlobalValue::InternalLinkage,
697 ConstantInt::get(Type::getInt32Ty(*Ctx),
699 "__llvm_gcov_global_state_pred");
700 GV->setUnnamedAddr(true);
705 Function *GCOVProfiler::insertCounterWriteout(
706 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
707 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
708 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
710 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
711 "__llvm_gcov_writeout", M);
712 WriteoutF->setUnnamedAddr(true);
713 WriteoutF->addFnAttr(Attribute::NoInline);
714 if (Options.NoRedZone)
715 WriteoutF->addFnAttr(Attribute::NoRedZone);
717 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
718 IRBuilder<> Builder(BB);
720 Constant *StartFile = getStartFileFunc();
721 Constant *EmitFunction = getEmitFunctionFunc();
722 Constant *EmitArcs = getEmitArcsFunc();
723 Constant *EndFile = getEndFileFunc();
725 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
727 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
728 DICompileUnit CU(CU_Nodes->getOperand(i));
729 std::string FilenameGcda = mangleName(CU, "gcda");
730 Builder.CreateCall2(StartFile,
731 Builder.CreateGlobalStringPtr(FilenameGcda),
732 Builder.CreateGlobalStringPtr(ReversedVersion));
733 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
734 DISubprogram SP(CountersBySP[j].second);
736 EmitFunction, Builder.getInt32(j),
737 Options.FunctionNamesInData ?
738 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
739 Constant::getNullValue(Builder.getInt8PtrTy()),
740 Builder.getInt8(Options.UseCfgChecksum));
742 GlobalVariable *GV = CountersBySP[j].first;
744 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
745 Builder.CreateCall2(EmitArcs,
746 Builder.getInt32(Arcs),
747 Builder.CreateConstGEP2_64(GV, 0, 0));
749 Builder.CreateCall(EndFile);
753 Builder.CreateRetVoid();
757 void GCOVProfiler::insertIndirectCounterIncrement() {
759 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
760 Fn->setUnnamedAddr(true);
761 Fn->setLinkage(GlobalValue::InternalLinkage);
762 Fn->addFnAttr(Attribute::NoInline);
763 if (Options.NoRedZone)
764 Fn->addFnAttr(Attribute::NoRedZone);
766 // Create basic blocks for function.
767 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
768 IRBuilder<> Builder(BB);
770 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
771 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
772 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
774 // uint32_t pred = *predecessor;
775 // if (pred == 0xffffffff) return;
776 Argument *Arg = Fn->arg_begin();
777 Arg->setName("predecessor");
778 Value *Pred = Builder.CreateLoad(Arg, "pred");
779 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
780 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
782 Builder.SetInsertPoint(PredNotNegOne);
784 // uint64_t *counter = counters[pred];
785 // if (!counter) return;
786 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
787 Arg = llvm::next(Fn->arg_begin());
788 Arg->setName("counters");
789 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
790 Value *Counter = Builder.CreateLoad(GEP, "counter");
791 Cond = Builder.CreateICmpEQ(Counter,
792 Constant::getNullValue(
793 Builder.getInt64Ty()->getPointerTo()));
794 Builder.CreateCondBr(Cond, Exit, CounterEnd);
797 Builder.SetInsertPoint(CounterEnd);
798 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
799 Builder.getInt64(1));
800 Builder.CreateStore(Add, Counter);
801 Builder.CreateBr(Exit);
803 // Fill in the exit block.
804 Builder.SetInsertPoint(Exit);
805 Builder.CreateRetVoid();
808 Function *GCOVProfiler::
809 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
810 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
811 Function *FlushF = M->getFunction("__llvm_gcov_flush");
813 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
814 "__llvm_gcov_flush", M);
816 FlushF->setLinkage(GlobalValue::InternalLinkage);
817 FlushF->setUnnamedAddr(true);
818 FlushF->addFnAttr(Attribute::NoInline);
819 if (Options.NoRedZone)
820 FlushF->addFnAttr(Attribute::NoRedZone);
822 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
824 // Write out the current counters.
825 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
826 assert(WriteoutF && "Need to create the writeout function first!");
828 IRBuilder<> Builder(Entry);
829 Builder.CreateCall(WriteoutF);
831 // Zero out the counters.
832 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
833 I = CountersBySP.begin(), E = CountersBySP.end();
835 GlobalVariable *GV = I->first;
836 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
837 Builder.CreateStore(Null, GV);
840 Type *RetTy = FlushF->getReturnType();
841 if (RetTy == Type::getVoidTy(*Ctx))
842 Builder.CreateRetVoid();
843 else if (RetTy->isIntegerTy())
844 // Used if __llvm_gcov_flush was implicitly declared.
845 Builder.CreateRet(ConstantInt::get(RetTy, 0));
847 report_fatal_error("invalid return type for __llvm_gcov_flush");