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 "ProfilingUtils.h"
20 #include "llvm/Transforms/Instrumentation.h"
21 #include "llvm/DebugInfo.h"
22 #include "llvm/IRBuilder.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/UniqueVector.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/DebugLoc.h"
34 #include "llvm/Support/InstIterator.h"
35 #include "llvm/Support/PathV2.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Transforms/Utils/ModuleUtils.h"
44 class GCOVProfiler : public ModulePass {
48 : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(false),
49 UseExtraChecksum(false) {
50 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
52 GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format = false,
53 bool useExtraChecksum = false)
54 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
55 Use402Format(use402Format), UseExtraChecksum(useExtraChecksum) {
56 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
57 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
59 virtual const char *getPassName() const {
60 return "GCOV Profiler";
63 bool runOnModule(Module &M);
65 // Create the GCNO files for the Module based on DebugInfo.
68 // Modify the program to track transitions along edges and call into the
69 // profiling runtime to emit .gcda files when run.
70 bool emitProfileArcs();
72 // Get pointers to the functions in the runtime library.
73 Constant *getStartFileFunc();
74 Constant *getIncrementIndirectCounterFunc();
75 Constant *getEmitFunctionFunc();
76 Constant *getEmitArcsFunc();
77 Constant *getEndFileFunc();
79 // Create or retrieve an i32 state value that is used to represent the
80 // pred block number for certain non-trivial edges.
81 GlobalVariable *getEdgeStateValue();
83 // Produce a table of pointers to counters, by predecessor and successor
85 GlobalVariable *buildEdgeLookupTable(Function *F,
86 GlobalVariable *Counter,
87 const UniqueVector<BasicBlock *> &Preds,
88 const UniqueVector<BasicBlock *> &Succs);
90 // Add the function to write out all our counters to the global destructor
92 void insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
93 void insertIndirectCounterIncrement();
94 void insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
96 std::string mangleName(DICompileUnit CU, const char *NewStem);
101 bool UseExtraChecksum;
105 const TargetData *TD;
109 char GCOVProfiler::ID = 0;
110 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
111 "Insert instrumentation for GCOV profiling", false, false)
113 ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
115 bool UseExtraChecksum) {
116 return new GCOVProfiler(EmitNotes, EmitData, Use402Format, UseExtraChecksum);
122 static const char *LinesTag;
123 static const char *FunctionTag;
124 static const char *BlockTag;
125 static const char *EdgeTag;
129 void writeBytes(const char *Bytes, int Size) {
130 os->write(Bytes, Size);
133 void write(uint32_t i) {
134 writeBytes(reinterpret_cast<char*>(&i), 4);
137 // Returns the length measured in 4-byte blocks that will be used to
138 // represent this string in a GCOV file
139 unsigned lengthOfGCOVString(StringRef s) {
140 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
141 // padding out to the next 4-byte word. The length is measured in 4-byte
142 // words including padding, not bytes of actual string.
143 return (s.size() / 4) + 1;
146 void writeGCOVString(StringRef s) {
147 uint32_t Len = lengthOfGCOVString(s);
149 writeBytes(s.data(), s.size());
151 // Write 1 to 4 bytes of NUL padding.
152 assert((unsigned)(4 - (s.size() % 4)) > 0);
153 assert((unsigned)(4 - (s.size() % 4)) <= 4);
154 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
159 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
160 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
161 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
162 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
167 // Constructed only by requesting it from a GCOVBlock, this object stores a
168 // list of line numbers and a single filename, representing lines that belong
170 class GCOVLines : public GCOVRecord {
172 void addLine(uint32_t Line) {
173 Lines.push_back(Line);
177 // Here 2 = 1 for string length + 1 for '0' id#.
178 return lengthOfGCOVString(Filename) + 2 + Lines.size();
183 writeGCOVString(Filename);
184 for (int i = 0, e = Lines.size(); i != e; ++i)
188 GCOVLines(StringRef F, raw_ostream *os)
195 SmallVector<uint32_t, 32> Lines;
198 // Represent a basic block in GCOV. Each block has a unique number in the
199 // function, number of lines belonging to each block, and a set of edges to
201 class GCOVBlock : public GCOVRecord {
203 GCOVLines &getFile(StringRef Filename) {
204 GCOVLines *&Lines = LinesByFile[Filename];
206 Lines = new GCOVLines(Filename, os);
211 void addEdge(GCOVBlock &Successor) {
212 OutEdges.push_back(&Successor);
217 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
218 E = LinesByFile.end(); I != E; ++I) {
219 Len += I->second->length();
222 writeBytes(LinesTag, 4);
225 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
226 E = LinesByFile.end(); I != E; ++I)
227 I->second->writeOut();
233 DeleteContainerSeconds(LinesByFile);
237 friend class GCOVFunction;
239 GCOVBlock(uint32_t Number, raw_ostream *os)
245 StringMap<GCOVLines *> LinesByFile;
246 SmallVector<GCOVBlock *, 4> OutEdges;
249 // A function has a unique identifier, a checksum (we leave as zero) and a
250 // set of blocks and a map of edges between blocks. This is the only GCOV
251 // object users can construct, the blocks and lines will be rooted here.
252 class GCOVFunction : public GCOVRecord {
254 GCOVFunction(DISubprogram SP, raw_ostream *os,
255 bool Use402Format, bool UseExtraChecksum) {
258 Function *F = SP.getFunction();
259 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
261 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
262 Blocks[BB] = new GCOVBlock(i++, os);
264 ReturnBlock = new GCOVBlock(i++, os);
266 writeBytes(FunctionTag, 4);
267 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
268 1 + lengthOfGCOVString(SP.getFilename()) + 1;
269 if (UseExtraChecksum)
272 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
274 write(0); // lineno checksum
275 if (UseExtraChecksum)
276 write(0); // cfg checksum
277 writeGCOVString(SP.getName());
278 writeGCOVString(SP.getFilename());
279 write(SP.getLineNumber());
283 DeleteContainerSeconds(Blocks);
287 GCOVBlock &getBlock(BasicBlock *BB) {
291 GCOVBlock &getReturnBlock() {
296 // Emit count of blocks.
297 writeBytes(BlockTag, 4);
298 write(Blocks.size() + 1);
299 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
300 write(0); // No flags on our blocks.
302 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
304 // Emit edges between blocks.
305 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
306 E = Blocks.end(); I != E; ++I) {
307 GCOVBlock &Block = *I->second;
308 if (Block.OutEdges.empty()) continue;
310 writeBytes(EdgeTag, 4);
311 write(Block.OutEdges.size() * 2 + 1);
313 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
314 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
316 write(Block.OutEdges[i]->Number);
317 write(0); // no flags
321 // Emit lines for each block.
322 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
323 E = Blocks.end(); I != E; ++I) {
324 I->second->writeOut();
329 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
330 GCOVBlock *ReturnBlock;
334 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
335 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
336 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
337 MDNode *N = GCov->getOperand(i);
338 if (N->getNumOperands() != 2) continue;
339 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
340 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
341 if (!GCovFile || !CompileUnit) continue;
342 if (CompileUnit == CU) {
343 SmallString<128> Filename = GCovFile->getString();
344 sys::path::replace_extension(Filename, NewStem);
345 return Filename.str();
350 SmallString<128> Filename = CU.getFilename();
351 sys::path::replace_extension(Filename, NewStem);
352 return sys::path::filename(Filename.str());
355 bool GCOVProfiler::runOnModule(Module &M) {
357 TD = getAnalysisIfAvailable<TargetData>();
358 Ctx = &M.getContext();
360 if (EmitNotes) emitGCNO();
361 if (EmitData) return emitProfileArcs();
365 void GCOVProfiler::emitGCNO() {
366 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
367 if (!CU_Nodes) return;
369 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
370 // Each compile unit gets its own .gcno file. This means that whether we run
371 // this pass over the original .o's as they're produced, or run it after
372 // LTO, we'll generate the same .gcno files.
374 DICompileUnit CU(CU_Nodes->getOperand(i));
375 std::string ErrorInfo;
376 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
377 raw_fd_ostream::F_Binary);
379 out.write("oncg*404MVLL", 12);
381 out.write("oncg*204MVLL", 12);
383 DIArray SPs = CU.getSubprograms();
384 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
385 DISubprogram SP(SPs.getElement(i));
386 if (!SP.Verify()) continue;
388 Function *F = SP.getFunction();
390 GCOVFunction Func(SP, &out, Use402Format, UseExtraChecksum);
392 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
393 GCOVBlock &Block = Func.getBlock(BB);
394 TerminatorInst *TI = BB->getTerminator();
395 if (int successors = TI->getNumSuccessors()) {
396 for (int i = 0; i != successors; ++i) {
397 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
399 } else if (isa<ReturnInst>(TI)) {
400 Block.addEdge(Func.getReturnBlock());
404 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
406 const DebugLoc &Loc = I->getDebugLoc();
407 if (Loc.isUnknown()) continue;
408 if (Line == Loc.getLine()) continue;
409 Line = Loc.getLine();
410 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
412 GCOVLines &Lines = Block.getFile(SP.getFilename());
413 Lines.addLine(Loc.getLine());
418 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
423 bool GCOVProfiler::emitProfileArcs() {
424 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
425 if (!CU_Nodes) return false;
428 bool InsertIndCounterIncrCode = false;
429 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
430 DICompileUnit CU(CU_Nodes->getOperand(i));
431 DIArray SPs = CU.getSubprograms();
432 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
433 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
434 DISubprogram SP(SPs.getElement(i));
435 if (!SP.Verify()) continue;
436 Function *F = SP.getFunction();
438 if (!Result) Result = true;
440 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
441 TerminatorInst *TI = BB->getTerminator();
442 if (isa<ReturnInst>(TI))
445 Edges += TI->getNumSuccessors();
448 ArrayType *CounterTy =
449 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
450 GlobalVariable *Counters =
451 new GlobalVariable(*M, CounterTy, false,
452 GlobalValue::InternalLinkage,
453 Constant::getNullValue(CounterTy),
455 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
457 UniqueVector<BasicBlock *> ComplexEdgePreds;
458 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
461 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
462 TerminatorInst *TI = BB->getTerminator();
463 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
465 IRBuilder<> Builder(TI);
467 if (Successors == 1) {
468 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
470 Value *Count = Builder.CreateLoad(Counter);
471 Count = Builder.CreateAdd(Count,
472 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
473 Builder.CreateStore(Count, Counter);
474 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
475 Value *Sel = Builder.CreateSelect(
477 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
478 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
479 SmallVector<Value *, 2> Idx;
480 Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
482 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
483 Value *Count = Builder.CreateLoad(Counter);
484 Count = Builder.CreateAdd(Count,
485 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
486 Builder.CreateStore(Count, Counter);
488 ComplexEdgePreds.insert(BB);
489 for (int i = 0; i != Successors; ++i)
490 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
496 if (!ComplexEdgePreds.empty()) {
497 GlobalVariable *EdgeTable =
498 buildEdgeLookupTable(F, Counters,
499 ComplexEdgePreds, ComplexEdgeSuccs);
500 GlobalVariable *EdgeState = getEdgeStateValue();
502 Type *Int32Ty = Type::getInt32Ty(*Ctx);
503 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
504 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
505 Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
507 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
508 // call runtime to perform increment
509 BasicBlock::iterator InsertPt =
510 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
511 IRBuilder<> Builder(InsertPt);
512 Value *CounterPtrArray =
513 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
514 i * ComplexEdgePreds.size());
516 // Build code to increment the counter.
517 InsertIndCounterIncrCode = true;
518 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
519 EdgeState, CounterPtrArray);
524 insertCounterWriteout(CountersBySP);
525 insertFlush(CountersBySP);
528 if (InsertIndCounterIncrCode)
529 insertIndirectCounterIncrement();
534 // All edges with successors that aren't branches are "complex", because it
535 // requires complex logic to pick which counter to update.
536 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
538 GlobalVariable *Counters,
539 const UniqueVector<BasicBlock *> &Preds,
540 const UniqueVector<BasicBlock *> &Succs) {
541 // TODO: support invoke, threads. We rely on the fact that nothing can modify
542 // the whole-Module pred edge# between the time we set it and the time we next
543 // read it. Threads and invoke make this untrue.
545 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
546 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
547 ArrayType *EdgeTableTy = ArrayType::get(
548 Int64PtrTy, Succs.size() * Preds.size());
550 Constant **EdgeTable = new Constant*[Succs.size() * Preds.size()];
551 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
552 for (int i = 0, ie = Succs.size() * Preds.size(); i != ie; ++i)
553 EdgeTable[i] = NullValue;
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();
559 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
560 for (int i = 0; i != Successors; ++i) {
561 BasicBlock *Succ = TI->getSuccessor(i);
562 IRBuilder<> builder(Succ);
563 Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
565 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
566 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
572 ArrayRef<Constant*> V(&EdgeTable[0], Succs.size() * Preds.size());
573 GlobalVariable *EdgeTableGV =
575 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
576 ConstantArray::get(EdgeTableTy, V),
577 "__llvm_gcda_edge_table");
578 EdgeTableGV->setUnnamedAddr(true);
582 Constant *GCOVProfiler::getStartFileFunc() {
583 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
584 Type::getInt8PtrTy(*Ctx), false);
585 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
588 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
589 Type *Int32Ty = Type::getInt32Ty(*Ctx);
590 Type *Int64Ty = Type::getInt64Ty(*Ctx);
592 Int32Ty->getPointerTo(), // uint32_t *predecessor
593 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
595 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
596 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
599 Constant *GCOVProfiler::getEmitFunctionFunc() {
601 Type::getInt32Ty(*Ctx), // uint32_t ident
602 Type::getInt8PtrTy(*Ctx), // const char *function_name
604 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
605 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
608 Constant *GCOVProfiler::getEmitArcsFunc() {
610 Type::getInt32Ty(*Ctx), // uint32_t num_counters
611 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
613 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
615 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
618 Constant *GCOVProfiler::getEndFileFunc() {
619 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
620 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
623 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
624 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
626 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
627 GlobalValue::InternalLinkage,
628 ConstantInt::get(Type::getInt32Ty(*Ctx),
630 "__llvm_gcov_global_state_pred");
631 GV->setUnnamedAddr(true);
636 void GCOVProfiler::insertCounterWriteout(
637 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
638 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
639 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
641 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
642 "__llvm_gcov_writeout", M);
643 WriteoutF->setUnnamedAddr(true);
645 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
646 IRBuilder<> Builder(BB);
648 Constant *StartFile = getStartFileFunc();
649 Constant *EmitFunction = getEmitFunctionFunc();
650 Constant *EmitArcs = getEmitArcsFunc();
651 Constant *EndFile = getEndFileFunc();
653 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
655 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
656 DICompileUnit compile_unit(CU_Nodes->getOperand(i));
657 std::string FilenameGcda = mangleName(compile_unit, "gcda");
658 Builder.CreateCall(StartFile,
659 Builder.CreateGlobalStringPtr(FilenameGcda));
660 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
661 I = CountersBySP.begin(), E = CountersBySP.end();
663 DISubprogram SP(I->second);
664 intptr_t ident = reinterpret_cast<intptr_t>(I->second);
665 Builder.CreateCall2(EmitFunction,
666 ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
667 Builder.CreateGlobalStringPtr(SP.getName()));
669 GlobalVariable *GV = I->first;
671 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
672 Builder.CreateCall2(EmitArcs,
673 ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
674 Builder.CreateConstGEP2_64(GV, 0, 0));
676 Builder.CreateCall(EndFile);
679 Builder.CreateRetVoid();
681 // Create a small bit of code that registers the "__llvm_gcov_writeout"
682 // function to be executed at exit.
683 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
684 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
685 "__llvm_gcov_init", M);
686 F->setUnnamedAddr(true);
687 F->setLinkage(GlobalValue::InternalLinkage);
688 F->addFnAttr(Attribute::NoInline);
690 BB = BasicBlock::Create(*Ctx, "entry", F);
691 Builder.SetInsertPoint(BB);
693 FTy = FunctionType::get(Type::getInt32Ty(*Ctx),
694 PointerType::get(FTy, 0), false);
695 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
696 Builder.CreateCall(AtExitFn, WriteoutF);
697 Builder.CreateRetVoid();
699 appendToGlobalCtors(*M, F, 0);
702 void GCOVProfiler::insertIndirectCounterIncrement() {
704 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
705 Fn->setUnnamedAddr(true);
706 Fn->setLinkage(GlobalValue::InternalLinkage);
707 Fn->addFnAttr(Attribute::NoInline);
709 Type *Int32Ty = Type::getInt32Ty(*Ctx);
710 Type *Int64Ty = Type::getInt64Ty(*Ctx);
711 Constant *NegOne = ConstantInt::get(Int32Ty, 0xffffffff);
713 // Create basic blocks for function.
714 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
715 IRBuilder<> Builder(BB);
717 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
718 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
719 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
721 // uint32_t pred = *predecessor;
722 // if (pred == 0xffffffff) return;
723 Argument *Arg = Fn->arg_begin();
724 Arg->setName("predecessor");
725 Value *Pred = Builder.CreateLoad(Arg, "pred");
726 Value *Cond = Builder.CreateICmpEQ(Pred, NegOne);
727 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
729 Builder.SetInsertPoint(PredNotNegOne);
731 // uint64_t *counter = counters[pred];
732 // if (!counter) return;
733 Value *ZExtPred = Builder.CreateZExt(Pred, Int64Ty);
734 Arg = llvm::next(Fn->arg_begin());
735 Arg->setName("counters");
736 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
737 Value *Counter = Builder.CreateLoad(GEP, "counter");
738 Cond = Builder.CreateICmpEQ(Counter,
739 Constant::getNullValue(Int64Ty->getPointerTo()));
740 Builder.CreateCondBr(Cond, Exit, CounterEnd);
743 Builder.SetInsertPoint(CounterEnd);
744 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
745 ConstantInt::get(Int64Ty, 1));
746 Builder.CreateStore(Add, Counter);
747 Builder.CreateBr(Exit);
749 // Fill in the exit block.
750 Builder.SetInsertPoint(Exit);
751 Builder.CreateRetVoid();
755 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
756 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
757 Function *FlushF = M->getFunction("__llvm_gcov_flush");
759 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
760 "__llvm_gcov_flush", M);
762 FlushF->setLinkage(GlobalValue::InternalLinkage);
763 FlushF->setUnnamedAddr(true);
765 Type *Int8Ty = Type::getInt8Ty(*Ctx);
766 Type *Int64Ty = Type::getInt64Ty(*Ctx);
767 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
769 // Write out the current counters.
770 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
771 assert(WriteoutF && "Need to create the writeout function first!");
773 IRBuilder<> Builder(Entry);
774 Builder.CreateCall(WriteoutF);
777 // Zero out the counters.
778 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
779 I = CountersBySP.begin(), E = CountersBySP.end();
781 GlobalVariable *GV = I->first;
782 uint64_t NumBytes = TD->getTypeAllocSize(GV->getType()->getElementType());
783 Builder.CreateMemSet(Builder.CreateConstGEP2_64(GV, 0, 0),
784 ConstantInt::get(Int8Ty, 0),
785 ConstantInt::get(Int64Ty, NumBytes), false);
788 Type *RetTy = FlushF->getReturnType();
789 if (RetTy == Type::getVoidTy(*Ctx))
790 Builder.CreateRetVoid();
791 else if (RetTy->isIntegerTy())
792 // Used if __llvm_gcov_flush was implicitly declared.
793 Builder.CreateRet(ConstantInt::get(RetTy, 0));
795 report_fatal_error("invalid return type for __llvm_gcov_flush");