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/Analysis/DebugInfo.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/DebugLoc.h"
28 #include "llvm/Support/InstIterator.h"
29 #include "llvm/Support/IRBuilder.h"
30 #include "llvm/Support/PathV2.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/ADT/StringMap.h"
36 #include "llvm/ADT/UniqueVector.h"
42 class GCOVProfiler : public ModulePass {
43 bool runOnModule(Module &M);
47 : ModulePass(ID), EmitNotes(true), EmitData(true) {
48 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
50 GCOVProfiler(bool EmitNotes, bool EmitData)
51 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData) {
52 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
53 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
55 virtual const char *getPassName() const {
56 return "GCOV Profiler";
60 // Create the GCNO files for the Module based on DebugInfo.
61 void EmitGCNO(DebugInfoFinder &DIF);
63 // Modify the program to track transitions along edges and call into the
64 // profiling runtime to emit .gcda files when run.
65 bool EmitProfileArcs(DebugInfoFinder &DIF);
67 // Get pointers to the functions in the runtime library.
68 Constant *getStartFileFunc();
69 Constant *getEmitFunctionFunc();
70 Constant *getEmitArcsFunc();
71 Constant *getEndFileFunc();
73 // Add the function to write out all our counters to the global destructor
75 void InsertCounterWriteout(DebugInfoFinder &,
76 SmallVector<std::pair<GlobalVariable *,
87 char GCOVProfiler::ID = 0;
88 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
89 "Insert instrumentation for GCOV profiling", false, false)
91 ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData) {
92 return new GCOVProfiler(EmitNotes, EmitData);
95 static DISubprogram FindSubprogram(DIScope scope) {
96 while (!scope.isSubprogram()) {
97 assert(scope.isLexicalBlock() &&
98 "Debug location not lexical block or subprogram");
99 scope = DILexicalBlock(scope).getContext();
101 return DISubprogram(scope);
107 static const char *lines_tag;
108 static const char *function_tag;
109 static const char *block_tag;
110 static const char *edge_tag;
114 void WriteBytes(const char *b, int size) {
118 void Write(uint32_t i) {
119 WriteBytes(reinterpret_cast<char*>(&i), 4);
122 // Returns the length measured in 4-byte blocks that will be used to
123 // represent this string in a GCOV file
124 unsigned LengthOfGCOVString(StringRef s) {
125 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
126 // padding out to the next 4-byte word. The length is measured in 4-byte
127 // words including padding, not bytes of actual string.
128 return (s.size() + 5) / 4;
131 void WriteGCOVString(StringRef s) {
132 uint32_t len = LengthOfGCOVString(s);
134 WriteBytes(s.data(), s.size());
136 // Write 1 to 4 bytes of NUL padding.
137 assert((unsigned)(5 - ((s.size() + 1) % 4)) > 0);
138 assert((unsigned)(5 - ((s.size() + 1) % 4)) <= 4);
139 WriteBytes("\0\0\0\0", 5 - ((s.size() + 1) % 4));
144 const char *GCOVRecord::lines_tag = "\0\0\x45\x01";
145 const char *GCOVRecord::function_tag = "\0\0\0\1";
146 const char *GCOVRecord::block_tag = "\0\0\x41\x01";
147 const char *GCOVRecord::edge_tag = "\0\0\x43\x01";
152 // Constructed only by requesting it from a GCOVBlock, this object stores a
153 // list of line numbers and a single filename, representing lines that belong
155 class GCOVLines : public GCOVRecord {
157 void AddLine(uint32_t line) {
158 lines.push_back(line);
162 return LengthOfGCOVString(filename) + 2 + lines.size();
166 friend class GCOVBlock;
168 GCOVLines(std::string filename, raw_ostream *os)
169 : filename(filename) {
173 std::string filename;
174 SmallVector<uint32_t, 32> lines;
177 // Represent a basic block in GCOV. Each block has a unique number in the
178 // function, number of lines belonging to each block, and a set of edges to
180 class GCOVBlock : public GCOVRecord {
182 GCOVLines &GetFile(std::string filename) {
183 GCOVLines *&lines = lines_by_file[filename];
185 lines = new GCOVLines(filename, os);
190 void AddEdge(GCOVBlock &successor) {
191 out_edges.push_back(&successor);
196 for (StringMap<GCOVLines *>::iterator I = lines_by_file.begin(),
197 E = lines_by_file.end(); I != E; ++I) {
198 len += I->second->Length();
201 WriteBytes(lines_tag, 4);
204 for (StringMap<GCOVLines *>::iterator I = lines_by_file.begin(),
205 E = lines_by_file.end(); I != E; ++I) {
207 WriteGCOVString(I->second->filename);
208 for (int i = 0, e = I->second->lines.size(); i != e; ++i) {
209 Write(I->second->lines[i]);
217 DeleteContainerSeconds(lines_by_file);
221 friend class GCOVFunction;
223 GCOVBlock(uint32_t number, raw_ostream *os)
230 StringMap<GCOVLines *> lines_by_file;
231 SmallVector<GCOVBlock *, 4> out_edges;
234 // A function has a unique identifier, a checksum (we leave as zero) and a
235 // set of blocks and a map of edges between blocks. This is the only GCOV
236 // object users can construct, the blocks and lines will be rooted here.
237 class GCOVFunction : public GCOVRecord {
239 GCOVFunction(DISubprogram SP, raw_ostream *os) {
242 Function *F = SP.getFunction();
244 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
245 blocks[BB] = new GCOVBlock(i++, os);
248 WriteBytes(function_tag, 4);
249 uint32_t block_len = 1 + 1 + 1 + LengthOfGCOVString(SP.getName()) +
250 1 + LengthOfGCOVString(SP.getFilename()) + 1;
252 uint32_t ident = reinterpret_cast<intptr_t>((MDNode*)SP);
254 Write(0); // checksum
255 WriteGCOVString(SP.getName());
256 WriteGCOVString(SP.getFilename());
257 Write(SP.getLineNumber());
261 DeleteContainerSeconds(blocks);
264 GCOVBlock &GetBlock(BasicBlock *BB) {
269 // Emit count of blocks.
270 WriteBytes(block_tag, 4);
271 Write(blocks.size());
272 for (int i = 0, e = blocks.size(); i != e; ++i) {
273 Write(0); // No flags on our blocks.
276 // Emit edges between blocks.
277 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = blocks.begin(),
278 E = blocks.end(); I != E; ++I) {
279 GCOVBlock &block = *I->second;
280 if (block.out_edges.empty()) continue;
282 WriteBytes(edge_tag, 4);
283 Write(block.out_edges.size() * 2 + 1);
285 for (int i = 0, e = block.out_edges.size(); i != e; ++i) {
286 Write(block.out_edges[i]->number);
287 Write(0); // no flags
291 // Emit lines for each block.
292 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = blocks.begin(),
293 E = blocks.end(); I != E; ++I) {
294 I->second->WriteOut();
299 DenseMap<BasicBlock *, GCOVBlock *> blocks;
303 // Replace the stem of a file, or add one if missing.
304 static std::string ReplaceStem(std::string orig_filename, std::string new_stem){
305 return (sys::path::stem(orig_filename) + "." + new_stem).str();
308 bool GCOVProfiler::runOnModule(Module &M) {
310 Ctx = &M.getContext();
313 DIF.processModule(*Mod);
315 if (EmitNotes) EmitGCNO(DIF);
316 if (EmitData) return EmitProfileArcs(DIF);
320 void GCOVProfiler::EmitGCNO(DebugInfoFinder &DIF) {
321 DenseMap<const MDNode *, raw_fd_ostream *> gcno_files;
322 for (DebugInfoFinder::iterator I = DIF.compile_unit_begin(),
323 E = DIF.compile_unit_end(); I != E; ++I) {
324 // Each compile unit gets its own .gcno file. This means that whether we run
325 // this pass over the original .o's as they're produced, or run it after
326 // LTO, we'll generate the same .gcno files.
328 DICompileUnit CU(*I);
329 raw_fd_ostream *&Out = gcno_files[CU];
330 std::string ErrorInfo;
331 Out = new raw_fd_ostream(ReplaceStem(CU.getFilename(), "gcno").c_str(),
332 ErrorInfo, raw_fd_ostream::F_Binary);
333 Out->write("oncg*404MVLL", 12);
336 for (DebugInfoFinder::iterator SPI = DIF.subprogram_begin(),
337 SPE = DIF.subprogram_end(); SPI != SPE; ++SPI) {
338 DISubprogram SP(*SPI);
339 raw_fd_ostream *&os = gcno_files[SP.getCompileUnit()];
341 GCOVFunction function(SP, os);
342 Function *F = SP.getFunction();
343 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
344 GCOVBlock &block = function.GetBlock(BB);
345 TerminatorInst *TI = BB->getTerminator();
346 if (int successors = TI->getNumSuccessors()) {
347 for (int i = 0; i != successors; ++i) {
348 block.AddEdge(function.GetBlock(TI->getSuccessor(i)));
353 for (BasicBlock::iterator I = BB->begin(), IE = BB->end(); I != IE; ++I) {
354 const DebugLoc &loc = I->getDebugLoc();
355 if (loc.isUnknown()) continue;
356 if (line == loc.getLine()) continue;
357 line = loc.getLine();
358 if (SP != FindSubprogram(DIScope(loc.getScope(*Ctx)))) continue;
360 GCOVLines &lines = block.GetFile(SP.getFilename());
361 lines.AddLine(loc.getLine());
367 for (DenseMap<const MDNode *, raw_fd_ostream *>::iterator
368 I = gcno_files.begin(), E = gcno_files.end(); I != E; ++I) {
369 raw_fd_ostream *&Out = I->second;
370 Out->write("\0\0\0\0\0\0\0\0", 8); // EOF
376 bool GCOVProfiler::EmitProfileArcs(DebugInfoFinder &DIF) {
377 if (DIF.subprogram_begin() == DIF.subprogram_end())
380 SmallVector<std::pair<GlobalVariable *, uint32_t>, 8> counters_by_ident;
381 for (DebugInfoFinder::iterator SPI = DIF.subprogram_begin(),
382 SPE = DIF.subprogram_end(); SPI != SPE; ++SPI) {
383 DISubprogram SP(*SPI);
384 Function *F = SP.getFunction();
386 // TODO: GCOV format requires a distinct unified exit block.
388 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
389 TerminatorInst *TI = BB->getTerminator();
390 edges += TI->getNumSuccessors();
393 const ArrayType *counter_type =
394 ArrayType::get(Type::getInt64Ty(*Ctx), edges);
395 GlobalVariable *counter =
396 new GlobalVariable(*Mod, counter_type, false,
397 GlobalValue::InternalLinkage,
398 Constant::getNullValue(counter_type),
399 "__llvm_gcov_ctr", 0, false, 0);
400 counters_by_ident.push_back(
401 std::make_pair(counter, reinterpret_cast<intptr_t>((MDNode*)SP)));
403 UniqueVector<BasicBlock *> complex_edge_preds;
404 UniqueVector<BasicBlock *> complex_edge_succs;
406 unsigned edge_num = 0;
407 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
408 TerminatorInst *TI = BB->getTerminator();
409 if (int successors = TI->getNumSuccessors()) {
410 IRBuilder<> builder(TI);
412 if (successors == 1) {
413 Value *ctr = builder.CreateConstInBoundsGEP2_64(counter, 0, edge_num);
414 Value *count = builder.CreateLoad(ctr);
415 count = builder.CreateAdd(count,
416 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
417 builder.CreateStore(count, ctr);
418 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
419 Value *sel = builder.CreateSelect(
421 ConstantInt::get(Type::getInt64Ty(*Ctx), edge_num),
422 ConstantInt::get(Type::getInt64Ty(*Ctx), edge_num + 1));
423 SmallVector<Value *, 2> idx;
424 idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
426 Value *ctr = builder.CreateInBoundsGEP(counter,
427 idx.begin(), idx.end());
428 Value *count = builder.CreateLoad(ctr);
429 count = builder.CreateAdd(count,
430 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
431 builder.CreateStore(count, ctr);
433 complex_edge_preds.insert(BB);
434 for (int i = 0; i != successors; ++i) {
435 complex_edge_succs.insert(TI->getSuccessor(i));
438 edge_num += successors;
442 // TODO: support switch, invoke, indirectbr
443 if (!complex_edge_preds.empty()) {
444 // emit a [preds x [succs x i64*]].
445 for (int i = 0, e = complex_edge_preds.size(); i != e; ++i) {
446 // call runtime to state save
448 for (int i = 0, e = complex_edge_succs.size(); i != e; ++i) {
449 // call runtime to perform increment
454 InsertCounterWriteout(DIF, counters_by_ident);
459 Constant *GCOVProfiler::getStartFileFunc() {
460 const Type *Args[1] = { Type::getInt8PtrTy(*Ctx) };
461 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
463 return Mod->getOrInsertFunction("llvm_gcda_start_file", FTy);
466 Constant *GCOVProfiler::getEmitFunctionFunc() {
467 const Type *Args[1] = { Type::getInt32Ty(*Ctx) };
468 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
470 return Mod->getOrInsertFunction("llvm_gcda_emit_function", FTy);
473 Constant *GCOVProfiler::getEmitArcsFunc() {
474 const Type *Args[] = {
475 Type::getInt32Ty(*Ctx), // uint32_t num_counters
476 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
478 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
480 return Mod->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
483 Constant *GCOVProfiler::getEndFileFunc() {
484 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
485 return Mod->getOrInsertFunction("llvm_gcda_end_file", FTy);
488 void GCOVProfiler::InsertCounterWriteout(
489 DebugInfoFinder &DIF,
490 SmallVector<std::pair<GlobalVariable *, uint32_t>, 8> &counters_by_ident) {
492 const FunctionType *WriteoutFTy =
493 FunctionType::get(Type::getVoidTy(*Ctx), false);
494 Function *WriteoutF = Function::Create(WriteoutFTy,
495 GlobalValue::InternalLinkage,
496 "__llvm_gcda_writeout", Mod);
497 WriteoutF->setUnnamedAddr(true);
498 BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
499 IRBuilder<> builder(BB);
501 Constant *StartFile = getStartFileFunc();
502 Constant *EmitFunction = getEmitFunctionFunc();
503 Constant *EmitArcs = getEmitArcsFunc();
504 Constant *EndFile = getEndFileFunc();
506 for (DebugInfoFinder::iterator CUI = DIF.compile_unit_begin(),
507 CUE = DIF.compile_unit_end(); CUI != CUE; ++CUI) {
508 DICompileUnit compile_unit(*CUI);
509 std::string filename_gcda = ReplaceStem(compile_unit.getFilename(), "gcda");
510 builder.CreateCall(StartFile,
511 builder.CreateGlobalStringPtr(filename_gcda));
512 for (SmallVector<std::pair<GlobalVariable *, uint32_t>, 8>::iterator
513 I = counters_by_ident.begin(), E = counters_by_ident.end();
515 builder.CreateCall(EmitFunction, ConstantInt::get(Type::getInt32Ty(*Ctx),
517 GlobalVariable *GV = I->first;
519 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
522 ConstantInt::get(Type::getInt32Ty(*Ctx), num_arcs),
523 builder.CreateConstGEP2_64(GV, 0, 0));
525 builder.CreateCall(EndFile);
527 builder.CreateRetVoid();
529 InsertProfilingShutdownCall(WriteoutF, Mod);