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/IRBuilder.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/Module.h"
31 #include "llvm/Pass.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/Transforms/Utils/ModuleUtils.h"
43 class GCOVProfiler : public ModulePass {
47 : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(false),
48 UseExtraChecksum(false), NoRedZone(false) {
49 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
51 GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format,
52 bool useExtraChecksum, bool NoRedZone_)
53 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
54 Use402Format(use402Format), UseExtraChecksum(useExtraChecksum),
55 NoRedZone(NoRedZone_) {
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;
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,
117 return new GCOVProfiler(EmitNotes, EmitData, Use402Format, UseExtraChecksum,
124 static const char *LinesTag;
125 static const char *FunctionTag;
126 static const char *BlockTag;
127 static const char *EdgeTag;
131 void writeBytes(const char *Bytes, int Size) {
132 os->write(Bytes, Size);
135 void write(uint32_t i) {
136 writeBytes(reinterpret_cast<char*>(&i), 4);
139 // Returns the length measured in 4-byte blocks that will be used to
140 // represent this string in a GCOV file
141 unsigned lengthOfGCOVString(StringRef s) {
142 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
143 // padding out to the next 4-byte word. The length is measured in 4-byte
144 // words including padding, not bytes of actual string.
145 return (s.size() / 4) + 1;
148 void writeGCOVString(StringRef s) {
149 uint32_t Len = lengthOfGCOVString(s);
151 writeBytes(s.data(), s.size());
153 // Write 1 to 4 bytes of NUL padding.
154 assert((unsigned)(4 - (s.size() % 4)) > 0);
155 assert((unsigned)(4 - (s.size() % 4)) <= 4);
156 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
161 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
162 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
163 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
164 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
169 // Constructed only by requesting it from a GCOVBlock, this object stores a
170 // list of line numbers and a single filename, representing lines that belong
172 class GCOVLines : public GCOVRecord {
174 void addLine(uint32_t Line) {
175 Lines.push_back(Line);
179 // Here 2 = 1 for string length + 1 for '0' id#.
180 return lengthOfGCOVString(Filename) + 2 + Lines.size();
185 writeGCOVString(Filename);
186 for (int i = 0, e = Lines.size(); i != e; ++i)
190 GCOVLines(StringRef F, raw_ostream *os)
197 SmallVector<uint32_t, 32> Lines;
200 // Represent a basic block in GCOV. Each block has a unique number in the
201 // function, number of lines belonging to each block, and a set of edges to
203 class GCOVBlock : public GCOVRecord {
205 GCOVLines &getFile(StringRef Filename) {
206 GCOVLines *&Lines = LinesByFile[Filename];
208 Lines = new GCOVLines(Filename, os);
213 void addEdge(GCOVBlock &Successor) {
214 OutEdges.push_back(&Successor);
219 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
220 E = LinesByFile.end(); I != E; ++I) {
221 Len += I->second->length();
224 writeBytes(LinesTag, 4);
227 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
228 E = LinesByFile.end(); I != E; ++I)
229 I->second->writeOut();
235 DeleteContainerSeconds(LinesByFile);
239 friend class GCOVFunction;
241 GCOVBlock(uint32_t Number, raw_ostream *os)
247 StringMap<GCOVLines *> LinesByFile;
248 SmallVector<GCOVBlock *, 4> OutEdges;
251 // A function has a unique identifier, a checksum (we leave as zero) and a
252 // set of blocks and a map of edges between blocks. This is the only GCOV
253 // object users can construct, the blocks and lines will be rooted here.
254 class GCOVFunction : public GCOVRecord {
256 GCOVFunction(DISubprogram SP, raw_ostream *os,
257 bool Use402Format, bool UseExtraChecksum) {
260 Function *F = SP.getFunction();
261 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
263 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
264 Blocks[BB] = new GCOVBlock(i++, os);
266 ReturnBlock = new GCOVBlock(i++, os);
268 writeBytes(FunctionTag, 4);
269 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
270 1 + lengthOfGCOVString(SP.getFilename()) + 1;
271 if (UseExtraChecksum)
274 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
276 write(0); // lineno checksum
277 if (UseExtraChecksum)
278 write(0); // cfg checksum
279 writeGCOVString(SP.getName());
280 writeGCOVString(SP.getFilename());
281 write(SP.getLineNumber());
285 DeleteContainerSeconds(Blocks);
289 GCOVBlock &getBlock(BasicBlock *BB) {
293 GCOVBlock &getReturnBlock() {
298 // Emit count of blocks.
299 writeBytes(BlockTag, 4);
300 write(Blocks.size() + 1);
301 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
302 write(0); // No flags on our blocks.
304 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
306 // Emit edges between blocks.
307 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
308 E = Blocks.end(); I != E; ++I) {
309 GCOVBlock &Block = *I->second;
310 if (Block.OutEdges.empty()) continue;
312 writeBytes(EdgeTag, 4);
313 write(Block.OutEdges.size() * 2 + 1);
315 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
316 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
318 write(Block.OutEdges[i]->Number);
319 write(0); // no flags
323 // Emit lines for each block.
324 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
325 E = Blocks.end(); I != E; ++I) {
326 I->second->writeOut();
331 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
332 GCOVBlock *ReturnBlock;
336 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
337 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
338 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
339 MDNode *N = GCov->getOperand(i);
340 if (N->getNumOperands() != 2) continue;
341 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
342 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
343 if (!GCovFile || !CompileUnit) continue;
344 if (CompileUnit == CU) {
345 SmallString<128> Filename = GCovFile->getString();
346 sys::path::replace_extension(Filename, NewStem);
347 return Filename.str();
352 SmallString<128> Filename = CU.getFilename();
353 sys::path::replace_extension(Filename, NewStem);
354 return sys::path::filename(Filename.str());
357 bool GCOVProfiler::runOnModule(Module &M) {
359 Ctx = &M.getContext();
361 if (EmitNotes) emitGCNO();
362 if (EmitData) return emitProfileArcs();
366 void GCOVProfiler::emitGCNO() {
367 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
368 if (!CU_Nodes) return;
370 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
371 // Each compile unit gets its own .gcno file. This means that whether we run
372 // this pass over the original .o's as they're produced, or run it after
373 // LTO, we'll generate the same .gcno files.
375 DICompileUnit CU(CU_Nodes->getOperand(i));
376 std::string ErrorInfo;
377 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
378 raw_fd_ostream::F_Binary);
380 out.write("oncg*404MVLL", 12);
382 out.write("oncg*204MVLL", 12);
384 DIArray SPs = CU.getSubprograms();
385 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
386 DISubprogram SP(SPs.getElement(i));
387 if (!SP.Verify()) continue;
389 Function *F = SP.getFunction();
391 GCOVFunction Func(SP, &out, Use402Format, UseExtraChecksum);
393 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
394 GCOVBlock &Block = Func.getBlock(BB);
395 TerminatorInst *TI = BB->getTerminator();
396 if (int successors = TI->getNumSuccessors()) {
397 for (int i = 0; i != successors; ++i) {
398 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
400 } else if (isa<ReturnInst>(TI)) {
401 Block.addEdge(Func.getReturnBlock());
405 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
407 const DebugLoc &Loc = I->getDebugLoc();
408 if (Loc.isUnknown()) continue;
409 if (Line == Loc.getLine()) continue;
410 Line = Loc.getLine();
411 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
413 GCOVLines &Lines = Block.getFile(SP.getFilename());
414 Lines.addLine(Loc.getLine());
419 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
424 bool GCOVProfiler::emitProfileArcs() {
425 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
426 if (!CU_Nodes) return false;
429 bool InsertIndCounterIncrCode = false;
430 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
431 DICompileUnit CU(CU_Nodes->getOperand(i));
432 DIArray SPs = CU.getSubprograms();
433 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
434 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
435 DISubprogram SP(SPs.getElement(i));
436 if (!SP.Verify()) continue;
437 Function *F = SP.getFunction();
439 if (!Result) Result = true;
441 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
442 TerminatorInst *TI = BB->getTerminator();
443 if (isa<ReturnInst>(TI))
446 Edges += TI->getNumSuccessors();
449 ArrayType *CounterTy =
450 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
451 GlobalVariable *Counters =
452 new GlobalVariable(*M, CounterTy, false,
453 GlobalValue::InternalLinkage,
454 Constant::getNullValue(CounterTy),
456 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
458 UniqueVector<BasicBlock *> ComplexEdgePreds;
459 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
462 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
463 TerminatorInst *TI = BB->getTerminator();
464 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
466 IRBuilder<> Builder(TI);
468 if (Successors == 1) {
469 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
471 Value *Count = Builder.CreateLoad(Counter);
472 Count = Builder.CreateAdd(Count,
473 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
474 Builder.CreateStore(Count, Counter);
475 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
476 Value *Sel = Builder.CreateSelect(
478 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
479 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
480 SmallVector<Value *, 2> Idx;
481 Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
483 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
484 Value *Count = Builder.CreateLoad(Counter);
485 Count = Builder.CreateAdd(Count,
486 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
487 Builder.CreateStore(Count, Counter);
489 ComplexEdgePreds.insert(BB);
490 for (int i = 0; i != Successors; ++i)
491 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
497 if (!ComplexEdgePreds.empty()) {
498 GlobalVariable *EdgeTable =
499 buildEdgeLookupTable(F, Counters,
500 ComplexEdgePreds, ComplexEdgeSuccs);
501 GlobalVariable *EdgeState = getEdgeStateValue();
503 Type *Int32Ty = Type::getInt32Ty(*Ctx);
504 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
505 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
506 Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
508 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
509 // call runtime to perform increment
510 BasicBlock::iterator InsertPt =
511 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
512 IRBuilder<> Builder(InsertPt);
513 Value *CounterPtrArray =
514 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
515 i * ComplexEdgePreds.size());
517 // Build code to increment the counter.
518 InsertIndCounterIncrCode = true;
519 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
520 EdgeState, CounterPtrArray);
525 insertCounterWriteout(CountersBySP);
526 insertFlush(CountersBySP);
529 if (InsertIndCounterIncrCode)
530 insertIndirectCounterIncrement();
535 // All edges with successors that aren't branches are "complex", because it
536 // requires complex logic to pick which counter to update.
537 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
539 GlobalVariable *Counters,
540 const UniqueVector<BasicBlock *> &Preds,
541 const UniqueVector<BasicBlock *> &Succs) {
542 // TODO: support invoke, threads. We rely on the fact that nothing can modify
543 // the whole-Module pred edge# between the time we set it and the time we next
544 // read it. Threads and invoke make this untrue.
546 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
547 size_t TableSize = Succs.size() * Preds.size();
548 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
549 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
551 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
552 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
553 for (size_t i = 0; i != TableSize; ++i)
554 EdgeTable[i] = NullValue;
557 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
558 TerminatorInst *TI = BB->getTerminator();
559 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
560 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
561 for (int i = 0; i != Successors; ++i) {
562 BasicBlock *Succ = TI->getSuccessor(i);
563 IRBuilder<> builder(Succ);
564 Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
566 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
567 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
573 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
574 GlobalVariable *EdgeTableGV =
576 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
577 ConstantArray::get(EdgeTableTy, V),
578 "__llvm_gcda_edge_table");
579 EdgeTableGV->setUnnamedAddr(true);
583 Constant *GCOVProfiler::getStartFileFunc() {
584 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
585 Type::getInt8PtrTy(*Ctx), false);
586 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
589 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
590 Type *Int32Ty = Type::getInt32Ty(*Ctx);
591 Type *Int64Ty = Type::getInt64Ty(*Ctx);
593 Int32Ty->getPointerTo(), // uint32_t *predecessor
594 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
596 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
597 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
600 Constant *GCOVProfiler::getEmitFunctionFunc() {
602 Type::getInt32Ty(*Ctx), // uint32_t ident
603 Type::getInt8PtrTy(*Ctx), // const char *function_name
605 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
606 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
609 Constant *GCOVProfiler::getEmitArcsFunc() {
611 Type::getInt32Ty(*Ctx), // uint32_t num_counters
612 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
614 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
616 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
619 Constant *GCOVProfiler::getEndFileFunc() {
620 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
621 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
624 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
625 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
627 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
628 GlobalValue::InternalLinkage,
629 ConstantInt::get(Type::getInt32Ty(*Ctx),
631 "__llvm_gcov_global_state_pred");
632 GV->setUnnamedAddr(true);
637 void GCOVProfiler::insertCounterWriteout(
638 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
639 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
640 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
642 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
643 "__llvm_gcov_writeout", M);
644 WriteoutF->setUnnamedAddr(true);
645 WriteoutF->addFnAttr(Attribute::NoInline);
647 WriteoutF->addFnAttr(Attribute::NoRedZone);
649 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
650 IRBuilder<> Builder(BB);
652 Constant *StartFile = getStartFileFunc();
653 Constant *EmitFunction = getEmitFunctionFunc();
654 Constant *EmitArcs = getEmitArcsFunc();
655 Constant *EndFile = getEndFileFunc();
657 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
659 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
660 DICompileUnit CU(CU_Nodes->getOperand(i));
661 std::string FilenameGcda = mangleName(CU, "gcda");
662 Builder.CreateCall(StartFile,
663 Builder.CreateGlobalStringPtr(FilenameGcda));
664 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
665 I = CountersBySP.begin(), E = CountersBySP.end();
667 DISubprogram SP(I->second);
668 intptr_t ident = reinterpret_cast<intptr_t>(I->second);
669 Builder.CreateCall2(EmitFunction,
670 ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
671 Builder.CreateGlobalStringPtr(SP.getName()));
673 GlobalVariable *GV = I->first;
675 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
676 Builder.CreateCall2(EmitArcs,
677 ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
678 Builder.CreateConstGEP2_64(GV, 0, 0));
680 Builder.CreateCall(EndFile);
683 Builder.CreateRetVoid();
685 // Create a small bit of code that registers the "__llvm_gcov_writeout"
686 // function to be executed at exit.
687 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
688 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
689 "__llvm_gcov_init", M);
690 F->setUnnamedAddr(true);
691 F->setLinkage(GlobalValue::InternalLinkage);
692 F->addFnAttr(Attribute::NoInline);
694 F->addFnAttr(Attribute::NoRedZone);
696 BB = BasicBlock::Create(*Ctx, "entry", F);
697 Builder.SetInsertPoint(BB);
699 FTy = FunctionType::get(Type::getInt32Ty(*Ctx),
700 PointerType::get(FTy, 0), false);
701 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
702 Builder.CreateCall(AtExitFn, WriteoutF);
703 Builder.CreateRetVoid();
705 appendToGlobalCtors(*M, F, 0);
708 void GCOVProfiler::insertIndirectCounterIncrement() {
710 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
711 Fn->setUnnamedAddr(true);
712 Fn->setLinkage(GlobalValue::InternalLinkage);
713 Fn->addFnAttr(Attribute::NoInline);
715 Fn->addFnAttr(Attribute::NoRedZone);
717 Type *Int32Ty = Type::getInt32Ty(*Ctx);
718 Type *Int64Ty = Type::getInt64Ty(*Ctx);
719 Constant *NegOne = ConstantInt::get(Int32Ty, 0xffffffff);
721 // Create basic blocks for function.
722 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
723 IRBuilder<> Builder(BB);
725 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
726 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
727 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
729 // uint32_t pred = *predecessor;
730 // if (pred == 0xffffffff) return;
731 Argument *Arg = Fn->arg_begin();
732 Arg->setName("predecessor");
733 Value *Pred = Builder.CreateLoad(Arg, "pred");
734 Value *Cond = Builder.CreateICmpEQ(Pred, NegOne);
735 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
737 Builder.SetInsertPoint(PredNotNegOne);
739 // uint64_t *counter = counters[pred];
740 // if (!counter) return;
741 Value *ZExtPred = Builder.CreateZExt(Pred, Int64Ty);
742 Arg = llvm::next(Fn->arg_begin());
743 Arg->setName("counters");
744 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
745 Value *Counter = Builder.CreateLoad(GEP, "counter");
746 Cond = Builder.CreateICmpEQ(Counter,
747 Constant::getNullValue(Int64Ty->getPointerTo()));
748 Builder.CreateCondBr(Cond, Exit, CounterEnd);
751 Builder.SetInsertPoint(CounterEnd);
752 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
753 ConstantInt::get(Int64Ty, 1));
754 Builder.CreateStore(Add, Counter);
755 Builder.CreateBr(Exit);
757 // Fill in the exit block.
758 Builder.SetInsertPoint(Exit);
759 Builder.CreateRetVoid();
763 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
764 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
765 Function *FlushF = M->getFunction("__gcov_flush");
767 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
770 FlushF->setLinkage(GlobalValue::InternalLinkage);
771 FlushF->setUnnamedAddr(true);
772 FlushF->addFnAttr(Attribute::NoInline);
774 FlushF->addFnAttr(Attribute::NoRedZone);
776 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
778 // Write out the current counters.
779 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
780 assert(WriteoutF && "Need to create the writeout function first!");
782 IRBuilder<> Builder(Entry);
783 Builder.CreateCall(WriteoutF);
785 // Zero out the counters.
786 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
787 I = CountersBySP.begin(), E = CountersBySP.end();
789 GlobalVariable *GV = I->first;
790 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
791 Builder.CreateStore(Null, GV);
794 Type *RetTy = FlushF->getReturnType();
795 if (RetTy == Type::getVoidTy(*Ctx))
796 Builder.CreateRetVoid();
797 else if (RetTy->isIntegerTy())
798 // Used if __gcov_flush was implicitly declared.
799 Builder.CreateRet(ConstantInt::get(RetTy, 0));
801 report_fatal_error("invalid return type for __gcov_flush");