blob: 7a40fe6bbd64b2ca806c025edf12a1b36c8d5177 [file] [log] [blame]
Nick Lewyckyb1928702011-04-16 01:20:23 +00001//===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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"
13// file on exit.
14//
15//===----------------------------------------------------------------------===//
16
17#define DEBUG_TYPE "insert-gcov-profiling"
18
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"
37#include <string>
38#include <utility>
39using namespace llvm;
40
41namespace {
42 class GCOVProfiler : public ModulePass {
43 bool runOnModule(Module &M);
44 public:
45 static char ID;
Nick Lewyckya61e52c2011-04-21 01:56:25 +000046 GCOVProfiler()
47 : ModulePass(ID), EmitNotes(true), EmitData(true) {
48 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
49 }
50 GCOVProfiler(bool EmitNotes, bool EmitData)
51 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData) {
52 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
Nick Lewyckyb1928702011-04-16 01:20:23 +000053 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
54 }
55 virtual const char *getPassName() const {
56 return "GCOV Profiler";
57 }
58
59 private:
60 // Create the GCNO files for the Module based on DebugInfo.
Nick Lewycky1790c9c2011-04-26 03:54:16 +000061 void emitGCNO(DebugInfoFinder &DIF);
Nick Lewyckyb1928702011-04-16 01:20:23 +000062
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000063 // Modify the program to track transitions along edges and call into the
64 // profiling runtime to emit .gcda files when run.
Nick Lewycky1790c9c2011-04-26 03:54:16 +000065 bool emitProfileArcs(DebugInfoFinder &DIF);
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000066
Nick Lewyckyb1928702011-04-16 01:20:23 +000067 // Get pointers to the functions in the runtime library.
68 Constant *getStartFileFunc();
Nick Lewycky1790c9c2011-04-26 03:54:16 +000069 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +000070 Constant *getEmitFunctionFunc();
71 Constant *getEmitArcsFunc();
72 Constant *getEndFileFunc();
73
Nick Lewycky1790c9c2011-04-26 03:54:16 +000074 // Create or retrieve an i32 state value that is used to represent the
75 // pred block number for certain non-trivial edges.
76 GlobalVariable *getEdgeStateValue();
77
78 // Produce a table of pointers to counters, by predecessor and successor
79 // block number.
80 GlobalVariable *buildEdgeLookupTable(Function *F,
81 GlobalVariable *Counter,
82 const UniqueVector<BasicBlock *> &Preds,
83 const UniqueVector<BasicBlock *> &Succs);
84
Nick Lewyckyb1928702011-04-16 01:20:23 +000085 // Add the function to write out all our counters to the global destructor
86 // list.
Nick Lewycky1790c9c2011-04-26 03:54:16 +000087 void insertCounterWriteout(DebugInfoFinder &,
Nick Lewyckyb1928702011-04-16 01:20:23 +000088 SmallVector<std::pair<GlobalVariable *,
89 uint32_t>, 8> &);
90
Nick Lewyckya61e52c2011-04-21 01:56:25 +000091 bool EmitNotes;
92 bool EmitData;
93
Nick Lewycky1790c9c2011-04-26 03:54:16 +000094 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +000095 LLVMContext *Ctx;
96 };
97}
98
99char GCOVProfiler::ID = 0;
100INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
101 "Insert instrumentation for GCOV profiling", false, false)
102
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000103ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData) {
104 return new GCOVProfiler(EmitNotes, EmitData);
105}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000106
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000107static DISubprogram findSubprogram(DIScope Scope) {
108 while (!Scope.isSubprogram()) {
109 assert(Scope.isLexicalBlock() &&
Nick Lewyckyb1928702011-04-16 01:20:23 +0000110 "Debug location not lexical block or subprogram");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000111 Scope = DILexicalBlock(Scope).getContext();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000112 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000113 return DISubprogram(Scope);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000114}
115
116namespace {
117 class GCOVRecord {
118 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000119 static const char *LinesTag;
120 static const char *FunctionTag;
121 static const char *BlockTag;
122 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000123
124 GCOVRecord() {}
125
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000126 void writeBytes(const char *Bytes, int Size) {
127 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000128 }
129
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000130 void write(uint32_t i) {
131 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000132 }
133
134 // Returns the length measured in 4-byte blocks that will be used to
135 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000136 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000137 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000138 // padding out to the next 4-byte word. The length is measured in 4-byte
139 // words including padding, not bytes of actual string.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000140 return (s.size() + 5) / 4;
141 }
142
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000143 void writeGCOVString(StringRef s) {
144 uint32_t Len = lengthOfGCOVString(s);
145 write(Len);
146 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000147
148 // Write 1 to 4 bytes of NUL padding.
149 assert((unsigned)(5 - ((s.size() + 1) % 4)) > 0);
150 assert((unsigned)(5 - ((s.size() + 1) % 4)) <= 4);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000151 writeBytes("\0\0\0\0", 5 - ((s.size() + 1) % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000152 }
153
154 raw_ostream *os;
155 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000156 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
157 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
158 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
159 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000160
161 class GCOVFunction;
162 class GCOVBlock;
163
164 // Constructed only by requesting it from a GCOVBlock, this object stores a
165 // list of line numbers and a single filename, representing lines that belong
166 // to the block.
167 class GCOVLines : public GCOVRecord {
168 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000169 void addLine(uint32_t Line) {
170 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000171 }
172
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000173 uint32_t length() {
174 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000175 }
176
177 private:
178 friend class GCOVBlock;
179
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000180 GCOVLines(std::string Filename, raw_ostream *os)
181 : Filename(Filename) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000182 this->os = os;
183 }
184
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000185 std::string Filename;
186 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000187 };
188
189 // Represent a basic block in GCOV. Each block has a unique number in the
190 // function, number of lines belonging to each block, and a set of edges to
191 // other blocks.
192 class GCOVBlock : public GCOVRecord {
193 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000194 GCOVLines &getFile(std::string Filename) {
195 GCOVLines *&Lines = LinesByFile[Filename];
196 if (!Lines) {
197 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000198 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000199 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000200 }
201
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000202 void addEdge(GCOVBlock &Successor) {
203 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000204 }
205
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000206 void writeOut() {
207 uint32_t Len = 3;
208 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
209 E = LinesByFile.end(); I != E; ++I) {
210 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000211 }
212
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000213 writeBytes(LinesTag, 4);
214 write(Len);
215 write(Number);
216 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
217 E = LinesByFile.end(); I != E; ++I) {
218 write(0);
219 writeGCOVString(I->second->Filename);
220 for (int i = 0, e = I->second->Lines.size(); i != e; ++i) {
221 write(I->second->Lines[i]);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000222 }
223 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000224 write(0);
225 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000226 }
227
228 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000229 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000230 }
231
232 private:
233 friend class GCOVFunction;
234
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000235 GCOVBlock(uint32_t Number, raw_ostream *os)
236 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000237 this->os = os;
238 }
239
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000240 uint32_t Number;
241 StringMap<GCOVLines *> LinesByFile;
242 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000243 };
244
245 // A function has a unique identifier, a checksum (we leave as zero) and a
246 // set of blocks and a map of edges between blocks. This is the only GCOV
247 // object users can construct, the blocks and lines will be rooted here.
248 class GCOVFunction : public GCOVRecord {
249 public:
250 GCOVFunction(DISubprogram SP, raw_ostream *os) {
251 this->os = os;
252
253 Function *F = SP.getFunction();
254 uint32_t i = 0;
255 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000256 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000257 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000258 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000259
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000260 writeBytes(FunctionTag, 4);
261 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
262 1 + lengthOfGCOVString(SP.getFilename()) + 1;
263 write(BlockLen);
264 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
265 write(Ident);
266 write(0); // checksum
267 writeGCOVString(SP.getName());
268 writeGCOVString(SP.getFilename());
269 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000270 }
271
272 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000273 DeleteContainerSeconds(Blocks);
274 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000275 }
276
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000277 GCOVBlock &getBlock(BasicBlock *BB) {
278 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000279 }
280
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000281 GCOVBlock &getReturnBlock() {
282 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000283 }
284
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000285 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000286 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000287 writeBytes(BlockTag, 4);
288 write(Blocks.size() + 1);
289 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
290 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000291 }
292
293 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000294 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
295 E = Blocks.end(); I != E; ++I) {
296 GCOVBlock &Block = *I->second;
297 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000298
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000299 writeBytes(EdgeTag, 4);
300 write(Block.OutEdges.size() * 2 + 1);
301 write(Block.Number);
302 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
303 write(Block.OutEdges[i]->Number);
304 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000305 }
306 }
307
308 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000309 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
310 E = Blocks.end(); I != E; ++I) {
311 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000312 }
313 }
314
315 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000316 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
317 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000318 };
319}
320
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000321// Replace the stem of a file, or add one if missing.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000322static std::string replaceStem(std::string OrigFilename, std::string NewStem) {
323 return (sys::path::stem(OrigFilename) + "." + NewStem).str();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000324}
325
326bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000327 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000328 Ctx = &M.getContext();
329
330 DebugInfoFinder DIF;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000331 DIF.processModule(M);
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000332
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000333 if (EmitNotes) emitGCNO(DIF);
334 if (EmitData) return emitProfileArcs(DIF);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000335 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000336}
337
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000338void GCOVProfiler::emitGCNO(DebugInfoFinder &DIF) {
339 DenseMap<const MDNode *, raw_fd_ostream *> GcnoFiles;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000340 for (DebugInfoFinder::iterator I = DIF.compile_unit_begin(),
341 E = DIF.compile_unit_end(); I != E; ++I) {
342 // Each compile unit gets its own .gcno file. This means that whether we run
343 // this pass over the original .o's as they're produced, or run it after
344 // LTO, we'll generate the same .gcno files.
345
346 DICompileUnit CU(*I);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000347 raw_fd_ostream *&out = GcnoFiles[CU];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000348 std::string ErrorInfo;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000349 out = new raw_fd_ostream(replaceStem(CU.getFilename(), "gcno").c_str(),
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000350 ErrorInfo, raw_fd_ostream::F_Binary);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000351 out->write("oncg*404MVLL", 12);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000352 }
353
354 for (DebugInfoFinder::iterator SPI = DIF.subprogram_begin(),
355 SPE = DIF.subprogram_end(); SPI != SPE; ++SPI) {
356 DISubprogram SP(*SPI);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000357 raw_fd_ostream *&os = GcnoFiles[SP.getCompileUnit()];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000358
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000359 GCOVFunction Func(SP, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000360 Function *F = SP.getFunction();
361 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000362 GCOVBlock &Block = Func.getBlock(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000363 TerminatorInst *TI = BB->getTerminator();
364 if (int successors = TI->getNumSuccessors()) {
365 for (int i = 0; i != successors; ++i) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000366 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000367 }
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000368 } else if (isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000369 Block.addEdge(Func.getReturnBlock());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000370 }
371
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000372 uint32_t Line = 0;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000373 for (BasicBlock::iterator I = BB->begin(), IE = BB->end(); I != IE; ++I) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000374 const DebugLoc &Loc = I->getDebugLoc();
375 if (Loc.isUnknown()) continue;
376 if (Line == Loc.getLine()) continue;
377 Line = Loc.getLine();
378 if (SP != findSubprogram(DIScope(Loc.getScope(*Ctx)))) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000379
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000380 GCOVLines &Lines = Block.getFile(SP.getFilename());
381 Lines.addLine(Loc.getLine());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000382 }
383 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000384 Func.writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000385 }
386
387 for (DenseMap<const MDNode *, raw_fd_ostream *>::iterator
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000388 I = GcnoFiles.begin(), E = GcnoFiles.end(); I != E; ++I) {
389 raw_fd_ostream *&out = I->second;
390 out->write("\0\0\0\0\0\0\0\0", 8); // EOF
391 out->close();
392 delete out;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000393 }
394}
395
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000396bool GCOVProfiler::emitProfileArcs(DebugInfoFinder &DIF) {
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000397 if (DIF.subprogram_begin() == DIF.subprogram_end())
398 return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000399
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000400 SmallVector<std::pair<GlobalVariable *, uint32_t>, 8> CountersByIdent;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000401 for (DebugInfoFinder::iterator SPI = DIF.subprogram_begin(),
402 SPE = DIF.subprogram_end(); SPI != SPE; ++SPI) {
403 DISubprogram SP(*SPI);
404 Function *F = SP.getFunction();
405
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000406 unsigned Edges = 0;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000407 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
408 TerminatorInst *TI = BB->getTerminator();
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000409 if (isa<ReturnInst>(TI))
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000410 ++Edges;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000411 else
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000412 Edges += TI->getNumSuccessors();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000413 }
414
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000415 const ArrayType *CounterTy =
416 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
417 GlobalVariable *Counters =
418 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000419 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000420 Constant::getNullValue(CounterTy),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000421 "__llvm_gcov_ctr", 0, false, 0);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000422 CountersByIdent.push_back(
423 std::make_pair(Counters, reinterpret_cast<intptr_t>((MDNode*)SP)));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000424
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000425 UniqueVector<BasicBlock *> ComplexEdgePreds;
426 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000427
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000428 unsigned Edge = 0;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000429 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
430 TerminatorInst *TI = BB->getTerminator();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000431 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
432 if (Successors) {
433 IRBuilder<> Builder(TI);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000434
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000435 if (Successors == 1) {
436 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
437 Edge);
438 Value *Count = Builder.CreateLoad(Counter);
439 Count = Builder.CreateAdd(Count,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000440 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000441 Builder.CreateStore(Count, Counter);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000442 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000443 Value *Sel = Builder.CreateSelect(
Nick Lewyckyb1928702011-04-16 01:20:23 +0000444 BI->getCondition(),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000445 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
446 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
447 SmallVector<Value *, 2> Idx;
448 Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
449 Idx.push_back(Sel);
450 Value *Counter = Builder.CreateInBoundsGEP(Counters,
451 Idx.begin(), Idx.end());
452 Value *Count = Builder.CreateLoad(Counter);
453 Count = Builder.CreateAdd(Count,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000454 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000455 Builder.CreateStore(Count, Counter);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000456 } else {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000457 ComplexEdgePreds.insert(BB);
458 for (int i = 0; i != Successors; ++i)
459 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000460 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000461 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000462 }
463 }
464
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000465 if (!ComplexEdgePreds.empty()) {
466 GlobalVariable *EdgeTable =
467 buildEdgeLookupTable(F, Counters,
468 ComplexEdgePreds, ComplexEdgeSuccs);
469 GlobalVariable *EdgeState = getEdgeStateValue();
470
471 const Type *Int32Ty = Type::getInt32Ty(*Ctx);
472 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
473 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
474 Builder.CreateStore(ConstantInt::get(Int32Ty, i+1), EdgeState);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000475 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000476 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000477 // call runtime to perform increment
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000478 IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstNonPHI());
479 Value *CounterPtrArray =
480 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
481 i * ComplexEdgePreds.size());
482 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
483 EdgeState, CounterPtrArray);
484 // clear the predecessor number
485 Builder.CreateStore(ConstantInt::get(Int32Ty, 0xffffffff), EdgeState);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000486 }
487 }
488 }
489
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000490 insertCounterWriteout(DIF, CountersByIdent);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000491
492 return true;
493}
494
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000495// All edges with successors that aren't branches are "complex", because it
496// requires complex logic to pick which counter to update.
497GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
498 Function *F,
499 GlobalVariable *Counters,
500 const UniqueVector<BasicBlock *> &Preds,
501 const UniqueVector<BasicBlock *> &Succs) {
502 // TODO: support invoke, threads. We rely on the fact that nothing can modify
503 // the whole-Module pred edge# between the time we set it and the time we next
504 // read it. Threads and invoke make this untrue.
505
506 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
507 const Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
508 const ArrayType *EdgeTableTy = ArrayType::get(
509 Int64PtrTy, Succs.size() * Preds.size());
510
511 Constant **EdgeTable = new Constant*[Succs.size() * Preds.size()];
512 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
513 for (int i = 0, ie = Succs.size() * Preds.size(); i != ie; ++i)
514 EdgeTable[i] = NullValue;
515
516 unsigned Edge = 0;
517 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
518 TerminatorInst *TI = BB->getTerminator();
519 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
520 if (Successors && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
521 for (int i = 0; i != Successors; ++i) {
522 BasicBlock *Succ = TI->getSuccessor(i);
523 IRBuilder<> builder(Succ);
524 Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
525 Edge + i);
526 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
527 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
528 }
529 }
530 Edge += Successors;
531 }
532
533 GlobalVariable *EdgeTableGV =
534 new GlobalVariable(
535 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
536 ConstantArray::get(EdgeTableTy,
537 &EdgeTable[0], Succs.size() * Preds.size()),
538 "__llvm_gcda_edge_table");
539 EdgeTableGV->setUnnamedAddr(true);
540 return EdgeTableGV;
541}
542
Nick Lewyckyb1928702011-04-16 01:20:23 +0000543Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000544 const Type *Args[] = { Type::getInt8PtrTy(*Ctx) };
Nick Lewyckyb1928702011-04-16 01:20:23 +0000545 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
546 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000547 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
548}
549
550Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
551 const Type *Args[] = {
552 Type::getInt32PtrTy(*Ctx), // uint32_t *predecessor
553 Type::getInt64PtrTy(*Ctx)->getPointerTo(), // uint64_t **state_table_row
554 };
555 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
556 Args, false);
557 return M->getOrInsertFunction("llvm_gcda_increment_indirect_counter", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000558}
559
560Constant *GCOVProfiler::getEmitFunctionFunc() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000561 const Type *Args[] = { Type::getInt32Ty(*Ctx) };
Nick Lewyckyb1928702011-04-16 01:20:23 +0000562 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
563 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000564 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000565}
566
567Constant *GCOVProfiler::getEmitArcsFunc() {
568 const Type *Args[] = {
569 Type::getInt32Ty(*Ctx), // uint32_t num_counters
570 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
571 };
572 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
573 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000574 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000575}
576
577Constant *GCOVProfiler::getEndFileFunc() {
578 const FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000579 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000580}
581
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000582GlobalVariable *GCOVProfiler::getEdgeStateValue() {
583 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
584 if (!GV) {
585 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
586 GlobalValue::InternalLinkage,
587 ConstantInt::get(Type::getInt32Ty(*Ctx),
588 0xffffffff),
589 "__llvm_gcov_global_state_pred");
590 GV->setUnnamedAddr(true);
591 }
592 return GV;
593}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000594
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000595void GCOVProfiler::insertCounterWriteout(
596 DebugInfoFinder &DIF,
597 SmallVector<std::pair<GlobalVariable *, uint32_t>, 8> &CountersByIdent) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000598 const FunctionType *WriteoutFTy =
599 FunctionType::get(Type::getVoidTy(*Ctx), false);
600 Function *WriteoutF = Function::Create(WriteoutFTy,
601 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000602 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000603 WriteoutF->setUnnamedAddr(true);
604 BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000605 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000606
607 Constant *StartFile = getStartFileFunc();
608 Constant *EmitFunction = getEmitFunctionFunc();
609 Constant *EmitArcs = getEmitArcsFunc();
610 Constant *EndFile = getEndFileFunc();
611
612 for (DebugInfoFinder::iterator CUI = DIF.compile_unit_begin(),
613 CUE = DIF.compile_unit_end(); CUI != CUE; ++CUI) {
614 DICompileUnit compile_unit(*CUI);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000615 std::string FilenameGcda = replaceStem(compile_unit.getFilename(), "gcda");
616 Builder.CreateCall(StartFile,
617 Builder.CreateGlobalStringPtr(FilenameGcda));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000618 for (SmallVector<std::pair<GlobalVariable *, uint32_t>, 8>::iterator
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000619 I = CountersByIdent.begin(), E = CountersByIdent.end();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000620 I != E; ++I) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000621 Builder.CreateCall(EmitFunction, ConstantInt::get(Type::getInt32Ty(*Ctx),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000622 I->second));
623 GlobalVariable *GV = I->first;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000624 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000625 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000626 Builder.CreateCall2(EmitArcs,
627 ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
628 Builder.CreateConstGEP2_64(GV, 0, 0));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000629 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000630 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000631 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000632 Builder.CreateRetVoid();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000633
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000634 InsertProfilingShutdownCall(WriteoutF, M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000635}