blob: e701f995785b83fc21f887c628e80c63b6392d2a [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 {
Nick Lewyckyb1928702011-04-16 01:20:23 +000043 public:
44 static char ID;
Nick Lewyckya61e52c2011-04-21 01:56:25 +000045 GCOVProfiler()
Bill Wendlingf5c95b82011-05-17 23:05:13 +000046 : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(false) {
Nick Lewyckya61e52c2011-04-21 01:56:25 +000047 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
48 }
Bill Wendlingf5c95b82011-05-17 23:05:13 +000049 GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format = false)
50 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
51 Use402Format(use402Format) {
Nick Lewyckya61e52c2011-04-21 01:56:25 +000052 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:
Nick Lewycky269687f2011-05-04 04:03:04 +000060 bool runOnModule(Module &M);
61
Nick Lewyckyb1928702011-04-16 01:20:23 +000062 // Create the GCNO files for the Module based on DebugInfo.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000063 void emitGCNO();
Nick Lewyckyb1928702011-04-16 01:20:23 +000064
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000065 // Modify the program to track transitions along edges and call into the
66 // profiling runtime to emit .gcda files when run.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000067 bool emitProfileArcs();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000068
Nick Lewyckyb1928702011-04-16 01:20:23 +000069 // Get pointers to the functions in the runtime library.
70 Constant *getStartFileFunc();
Nick Lewycky1790c9c2011-04-26 03:54:16 +000071 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +000072 Constant *getEmitFunctionFunc();
73 Constant *getEmitArcsFunc();
74 Constant *getEndFileFunc();
75
Nick Lewycky1790c9c2011-04-26 03:54:16 +000076 // Create or retrieve an i32 state value that is used to represent the
77 // pred block number for certain non-trivial edges.
78 GlobalVariable *getEdgeStateValue();
79
80 // Produce a table of pointers to counters, by predecessor and successor
81 // block number.
82 GlobalVariable *buildEdgeLookupTable(Function *F,
83 GlobalVariable *Counter,
84 const UniqueVector<BasicBlock *> &Preds,
85 const UniqueVector<BasicBlock *> &Succs);
86
Nick Lewyckyb1928702011-04-16 01:20:23 +000087 // Add the function to write out all our counters to the global destructor
88 // list.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000089 void insertCounterWriteout(SmallVector<std::pair<GlobalVariable *,
Nick Lewycky5409a182011-05-05 02:46:38 +000090 MDNode *>, 8> &);
Nick Lewyckyb1928702011-04-16 01:20:23 +000091
Nick Lewycky269687f2011-05-04 04:03:04 +000092 std::string mangleName(DICompileUnit CU, std::string NewStem);
93
Nick Lewyckya61e52c2011-04-21 01:56:25 +000094 bool EmitNotes;
95 bool EmitData;
Bill Wendlingf5c95b82011-05-17 23:05:13 +000096 bool Use402Format;
Nick Lewyckya61e52c2011-04-21 01:56:25 +000097
Nick Lewycky1790c9c2011-04-26 03:54:16 +000098 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +000099 LLVMContext *Ctx;
100 };
101}
102
103char GCOVProfiler::ID = 0;
104INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
105 "Insert instrumentation for GCOV profiling", false, false)
106
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000107ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
108 bool Use402Format) {
109 return new GCOVProfiler(EmitNotes, EmitData, Use402Format);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000110}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000111
Nick Lewyckyb1928702011-04-16 01:20:23 +0000112namespace {
113 class GCOVRecord {
114 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000115 static const char *LinesTag;
116 static const char *FunctionTag;
117 static const char *BlockTag;
118 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000119
120 GCOVRecord() {}
121
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000122 void writeBytes(const char *Bytes, int Size) {
123 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000124 }
125
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000126 void write(uint32_t i) {
127 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000128 }
129
130 // Returns the length measured in 4-byte blocks that will be used to
131 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000132 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000133 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000134 // padding out to the next 4-byte word. The length is measured in 4-byte
135 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000136 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000137 }
138
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000139 void writeGCOVString(StringRef s) {
140 uint32_t Len = lengthOfGCOVString(s);
141 write(Len);
142 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000143
144 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000145 assert((unsigned)(4 - (s.size() % 4)) > 0);
146 assert((unsigned)(4 - (s.size() % 4)) <= 4);
147 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000148 }
149
150 raw_ostream *os;
151 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000152 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
153 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
154 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
155 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000156
157 class GCOVFunction;
158 class GCOVBlock;
159
160 // Constructed only by requesting it from a GCOVBlock, this object stores a
161 // list of line numbers and a single filename, representing lines that belong
162 // to the block.
163 class GCOVLines : public GCOVRecord {
164 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000165 void addLine(uint32_t Line) {
166 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000167 }
168
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000169 uint32_t length() {
Devang Patel865375c2011-09-20 17:43:14 +0000170 // FIXME: ??? What is the significance of 2 here ?
171 return 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000172 }
173
174 private:
175 friend class GCOVBlock;
176
Devang Patel865375c2011-09-20 17:43:14 +0000177 GCOVLines(raw_ostream *os) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000178 this->os = os;
179 }
180
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000181 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000182 };
183
184 // Represent a basic block in GCOV. Each block has a unique number in the
185 // function, number of lines belonging to each block, and a set of edges to
186 // other blocks.
187 class GCOVBlock : public GCOVRecord {
188 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000189 GCOVLines &getFile(std::string Filename) {
190 GCOVLines *&Lines = LinesByFile[Filename];
191 if (!Lines) {
Devang Patel865375c2011-09-20 17:43:14 +0000192 Lines = new GCOVLines(os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000193 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000194 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000195 }
196
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000197 void addEdge(GCOVBlock &Successor) {
198 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000199 }
200
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000201 void writeOut() {
202 uint32_t Len = 3;
203 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
204 E = LinesByFile.end(); I != E; ++I) {
Devang Patel865375c2011-09-20 17:43:14 +0000205 Len = Len + lengthOfGCOVString(I->first()) + I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000206 }
207
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000208 writeBytes(LinesTag, 4);
209 write(Len);
210 write(Number);
211 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
212 E = LinesByFile.end(); I != E; ++I) {
213 write(0);
Devang Patel865375c2011-09-20 17:43:14 +0000214 writeGCOVString(I->first());
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000215 for (int i = 0, e = I->second->Lines.size(); i != e; ++i) {
216 write(I->second->Lines[i]);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000217 }
218 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000219 write(0);
220 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000221 }
222
223 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000224 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000225 }
226
227 private:
228 friend class GCOVFunction;
229
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000230 GCOVBlock(uint32_t Number, raw_ostream *os)
231 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000232 this->os = os;
233 }
234
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000235 uint32_t Number;
236 StringMap<GCOVLines *> LinesByFile;
237 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000238 };
239
240 // A function has a unique identifier, a checksum (we leave as zero) and a
241 // set of blocks and a map of edges between blocks. This is the only GCOV
242 // object users can construct, the blocks and lines will be rooted here.
243 class GCOVFunction : public GCOVRecord {
244 public:
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000245 GCOVFunction(DISubprogram SP, raw_ostream *os, bool Use402Format) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000246 this->os = os;
247
248 Function *F = SP.getFunction();
249 uint32_t i = 0;
250 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000251 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000252 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000253 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000254
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000255 writeBytes(FunctionTag, 4);
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000256 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000257 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000258 if (!Use402Format)
259 ++BlockLen; // For second checksum.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000260 write(BlockLen);
261 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
262 write(Ident);
Nick Lewycky5409a182011-05-05 02:46:38 +0000263 write(0); // checksum #1
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000264 if (!Use402Format)
265 write(0); // checksum #2
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000266 writeGCOVString(SP.getName());
267 writeGCOVString(SP.getFilename());
268 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000269 }
270
271 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000272 DeleteContainerSeconds(Blocks);
273 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000274 }
275
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000276 GCOVBlock &getBlock(BasicBlock *BB) {
277 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000278 }
279
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000280 GCOVBlock &getReturnBlock() {
281 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000282 }
283
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000284 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000285 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000286 writeBytes(BlockTag, 4);
287 write(Blocks.size() + 1);
288 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
289 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000290 }
291
292 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000293 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
294 E = Blocks.end(); I != E; ++I) {
295 GCOVBlock &Block = *I->second;
296 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000297
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000298 writeBytes(EdgeTag, 4);
299 write(Block.OutEdges.size() * 2 + 1);
300 write(Block.Number);
301 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
302 write(Block.OutEdges[i]->Number);
303 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000304 }
305 }
306
307 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000308 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
309 E = Blocks.end(); I != E; ++I) {
310 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000311 }
312 }
313
314 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000315 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
316 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000317 };
318}
319
Nick Lewycky269687f2011-05-04 04:03:04 +0000320std::string GCOVProfiler::mangleName(DICompileUnit CU, std::string NewStem) {
321 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
322 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
323 MDNode *N = GCov->getOperand(i);
324 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000325 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000326 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000327 if (!GCovFile || !CompileUnit) continue;
328 if (CompileUnit == CU) {
329 SmallString<128> Filename = GCovFile->getString();
330 sys::path::replace_extension(Filename, NewStem);
331 return Filename.str();
332 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000333 }
334 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000335
336 SmallString<128> Filename = CU.getFilename();
337 sys::path::replace_extension(Filename, NewStem);
338 return sys::path::filename(Filename.str());
Nick Lewycky269687f2011-05-04 04:03:04 +0000339}
340
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000341bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000342 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000343 Ctx = &M.getContext();
344
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000345 if (EmitNotes) emitGCNO();
346 if (EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000347 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000348}
349
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000350void GCOVProfiler::emitGCNO() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000351 DenseMap<const MDNode *, raw_fd_ostream *> GcnoFiles;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000352 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
353 if (CU_Nodes) {
354 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
355 // Each compile unit gets its own .gcno file. This means that whether we run
356 // this pass over the original .o's as they're produced, or run it after
357 // LTO, we'll generate the same .gcno files.
358
359 DICompileUnit CU(CU_Nodes->getOperand(i));
360 raw_fd_ostream *&out = GcnoFiles[CU];
361 std::string ErrorInfo;
362 out = new raw_fd_ostream(mangleName(CU, "gcno").c_str(), ErrorInfo,
363 raw_fd_ostream::F_Binary);
364 if (!Use402Format)
365 out->write("oncg*404MVLL", 12);
366 else
367 out->write("oncg*204MVLL", 12);
368
369 DIArray SPs = CU.getSubprograms();
370 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
371 DISubprogram SP(SPs.getElement(i));
372 if (!SP.Verify()) continue;
Nick Lewycky58e2cdf2011-08-18 19:07:42 +0000373 raw_fd_ostream *&os = GcnoFiles[CU];
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000374
375 Function *F = SP.getFunction();
376 if (!F) continue;
377 GCOVFunction Func(SP, os, Use402Format);
378
379 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
380 GCOVBlock &Block = Func.getBlock(BB);
381 TerminatorInst *TI = BB->getTerminator();
382 if (int successors = TI->getNumSuccessors()) {
383 for (int i = 0; i != successors; ++i) {
384 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
385 }
386 } else if (isa<ReturnInst>(TI)) {
387 Block.addEdge(Func.getReturnBlock());
388 }
389
390 uint32_t Line = 0;
391 for (BasicBlock::iterator I = BB->begin(), IE = BB->end(); I != IE; ++I) {
392 const DebugLoc &Loc = I->getDebugLoc();
393 if (Loc.isUnknown()) continue;
394 if (Line == Loc.getLine()) continue;
395 Line = Loc.getLine();
Devang Patelec6f2552011-09-20 15:57:19 +0000396 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000397
398 GCOVLines &Lines = Block.getFile(SP.getFilename());
399 Lines.addLine(Loc.getLine());
400 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000401 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000402 Func.writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000403 }
404 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000405 }
406
407 for (DenseMap<const MDNode *, raw_fd_ostream *>::iterator
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000408 I = GcnoFiles.begin(), E = GcnoFiles.end(); I != E; ++I) {
409 raw_fd_ostream *&out = I->second;
410 out->write("\0\0\0\0\0\0\0\0", 8); // EOF
411 out->close();
412 delete out;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000413 }
414}
415
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000416bool GCOVProfiler::emitProfileArcs() {
417 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
418 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000419
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000420 bool Result = false;
421 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
422 DICompileUnit CU(CU_Nodes->getOperand(i));
423 DIArray SPs = CU.getSubprograms();
424 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
425 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
426 DISubprogram SP(SPs.getElement(i));
427 if (!SP.Verify()) continue;
428 Function *F = SP.getFunction();
429 if (!F) continue;
430 if (!Result) Result = true;
431 unsigned Edges = 0;
432 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
433 TerminatorInst *TI = BB->getTerminator();
434 if (isa<ReturnInst>(TI))
435 ++Edges;
436 else
437 Edges += TI->getNumSuccessors();
438 }
439
440 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000441 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000442 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000443 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000444 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000445 Constant::getNullValue(CounterTy),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000446 "__llvm_gcov_ctr", 0, false, 0);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000447 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
448
449 UniqueVector<BasicBlock *> ComplexEdgePreds;
450 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
451
452 unsigned Edge = 0;
453 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
454 TerminatorInst *TI = BB->getTerminator();
455 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
456 if (Successors) {
457 IRBuilder<> Builder(TI);
458
459 if (Successors == 1) {
460 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
461 Edge);
462 Value *Count = Builder.CreateLoad(Counter);
463 Count = Builder.CreateAdd(Count,
464 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
465 Builder.CreateStore(Count, Counter);
466 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
467 Value *Sel = Builder.CreateSelect(
Nick Lewyckyb1928702011-04-16 01:20:23 +0000468 BI->getCondition(),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000469 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
470 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000471 SmallVector<Value *, 2> Idx;
472 Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
473 Idx.push_back(Sel);
474 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
475 Value *Count = Builder.CreateLoad(Counter);
476 Count = Builder.CreateAdd(Count,
477 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
478 Builder.CreateStore(Count, Counter);
479 } else {
480 ComplexEdgePreds.insert(BB);
481 for (int i = 0; i != Successors; ++i)
482 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
483 }
484 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000485 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000486 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000487
488 if (!ComplexEdgePreds.empty()) {
489 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000490 buildEdgeLookupTable(F, Counters,
491 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000492 GlobalVariable *EdgeState = getEdgeStateValue();
493
494 Type *Int32Ty = Type::getInt32Ty(*Ctx);
495 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
496 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
497 Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
498 }
499 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
500 // call runtime to perform increment
501 BasicBlock::iterator InsertPt =
502 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
503 IRBuilder<> Builder(InsertPt);
504 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000505 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
506 i * ComplexEdgePreds.size());
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000507 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
508 EdgeState, CounterPtrArray);
509 // clear the predecessor number
510 Builder.CreateStore(ConstantInt::get(Int32Ty, 0xffffffff), EdgeState);
511 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000512 }
513 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000514 insertCounterWriteout(CountersBySP);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000515 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000516 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000517}
518
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000519// All edges with successors that aren't branches are "complex", because it
520// requires complex logic to pick which counter to update.
521GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
522 Function *F,
523 GlobalVariable *Counters,
524 const UniqueVector<BasicBlock *> &Preds,
525 const UniqueVector<BasicBlock *> &Succs) {
526 // TODO: support invoke, threads. We rely on the fact that nothing can modify
527 // the whole-Module pred edge# between the time we set it and the time we next
528 // read it. Threads and invoke make this untrue.
529
530 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000531 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
532 ArrayType *EdgeTableTy = ArrayType::get(
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000533 Int64PtrTy, Succs.size() * Preds.size());
534
535 Constant **EdgeTable = new Constant*[Succs.size() * Preds.size()];
536 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
537 for (int i = 0, ie = Succs.size() * Preds.size(); i != ie; ++i)
538 EdgeTable[i] = NullValue;
539
540 unsigned Edge = 0;
541 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
542 TerminatorInst *TI = BB->getTerminator();
543 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000544 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000545 for (int i = 0; i != Successors; ++i) {
546 BasicBlock *Succ = TI->getSuccessor(i);
547 IRBuilder<> builder(Succ);
548 Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
549 Edge + i);
550 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
551 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
552 }
553 }
554 Edge += Successors;
555 }
556
Jay Foad26701082011-06-22 09:24:39 +0000557 ArrayRef<Constant*> V(&EdgeTable[0], Succs.size() * Preds.size());
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000558 GlobalVariable *EdgeTableGV =
559 new GlobalVariable(
560 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000561 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000562 "__llvm_gcda_edge_table");
563 EdgeTableGV->setUnnamedAddr(true);
564 return EdgeTableGV;
565}
566
Nick Lewyckyb1928702011-04-16 01:20:23 +0000567Constant *GCOVProfiler::getStartFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000568 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Jay Foad5fdd6c82011-07-12 14:06:48 +0000569 Type::getInt8PtrTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000570 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
571}
572
573Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000574 Type *Args[] = {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000575 Type::getInt32PtrTy(*Ctx), // uint32_t *predecessor
576 Type::getInt64PtrTy(*Ctx)->getPointerTo(), // uint64_t **state_table_row
577 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000578 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000579 Args, false);
580 return M->getOrInsertFunction("llvm_gcda_increment_indirect_counter", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000581}
582
583Constant *GCOVProfiler::getEmitFunctionFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000584 Type *Args[2] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000585 Type::getInt32Ty(*Ctx), // uint32_t ident
586 Type::getInt8PtrTy(*Ctx), // const char *function_name
587 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000588 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000589 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000590 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000591}
592
593Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000594 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000595 Type::getInt32Ty(*Ctx), // uint32_t num_counters
596 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
597 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000598 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000599 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000600 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000601}
602
603Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000604 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000605 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000606}
607
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000608GlobalVariable *GCOVProfiler::getEdgeStateValue() {
609 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
610 if (!GV) {
611 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
612 GlobalValue::InternalLinkage,
613 ConstantInt::get(Type::getInt32Ty(*Ctx),
614 0xffffffff),
615 "__llvm_gcov_global_state_pred");
616 GV->setUnnamedAddr(true);
617 }
618 return GV;
619}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000620
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000621void GCOVProfiler::insertCounterWriteout(
Nick Lewycky5409a182011-05-05 02:46:38 +0000622 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> &CountersBySP) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000623 FunctionType *WriteoutFTy =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000624 FunctionType::get(Type::getVoidTy(*Ctx), false);
625 Function *WriteoutF = Function::Create(WriteoutFTy,
626 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000627 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000628 WriteoutF->setUnnamedAddr(true);
629 BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000630 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000631
632 Constant *StartFile = getStartFileFunc();
633 Constant *EmitFunction = getEmitFunctionFunc();
634 Constant *EmitArcs = getEmitArcsFunc();
635 Constant *EndFile = getEndFileFunc();
636
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000637 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
638 if (CU_Nodes) {
639 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
640 DICompileUnit compile_unit(CU_Nodes->getOperand(i));
641 std::string FilenameGcda = mangleName(compile_unit, "gcda");
642 Builder.CreateCall(StartFile,
643 Builder.CreateGlobalStringPtr(FilenameGcda));
644 for (SmallVector<std::pair<GlobalVariable *, MDNode *>, 8>::iterator
Nick Lewycky5409a182011-05-05 02:46:38 +0000645 I = CountersBySP.begin(), E = CountersBySP.end();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000646 I != E; ++I) {
647 DISubprogram SP(I->second);
648 intptr_t ident = reinterpret_cast<intptr_t>(I->second);
649 Builder.CreateCall2(EmitFunction,
650 ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
651 Builder.CreateGlobalStringPtr(SP.getName()));
652
653 GlobalVariable *GV = I->first;
654 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000655 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000656 Builder.CreateCall2(EmitArcs,
657 ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
658 Builder.CreateConstGEP2_64(GV, 0, 0));
659 }
660 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000661 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000662 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000663 Builder.CreateRetVoid();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000664
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000665 InsertProfilingShutdownCall(WriteoutF, M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000666}