blob: 3ba5d2c74d5d1dd5d24dd972064f7a5e144b191c [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()
Nick Lewyckybba40db2011-11-27 23:22:20 +000046 : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(false),
47 UseExtraChecksum(false) {
Nick Lewyckya61e52c2011-04-21 01:56:25 +000048 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
49 }
Nick Lewyckybba40db2011-11-27 23:22:20 +000050 GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format = false,
51 bool useExtraChecksum = false)
Bill Wendlingf5c95b82011-05-17 23:05:13 +000052 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
Nick Lewyckybba40db2011-11-27 23:22:20 +000053 Use402Format(use402Format), UseExtraChecksum(useExtraChecksum) {
Nick Lewyckya61e52c2011-04-21 01:56:25 +000054 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
Nick Lewyckyb1928702011-04-16 01:20:23 +000055 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
56 }
57 virtual const char *getPassName() const {
58 return "GCOV Profiler";
59 }
60
61 private:
Nick Lewycky269687f2011-05-04 04:03:04 +000062 bool runOnModule(Module &M);
63
Nick Lewyckyb1928702011-04-16 01:20:23 +000064 // Create the GCNO files for the Module based on DebugInfo.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000065 void emitGCNO();
Nick Lewyckyb1928702011-04-16 01:20:23 +000066
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000067 // Modify the program to track transitions along edges and call into the
68 // profiling runtime to emit .gcda files when run.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000069 bool emitProfileArcs();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000070
Nick Lewyckyb1928702011-04-16 01:20:23 +000071 // Get pointers to the functions in the runtime library.
72 Constant *getStartFileFunc();
Nick Lewycky1790c9c2011-04-26 03:54:16 +000073 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +000074 Constant *getEmitFunctionFunc();
75 Constant *getEmitArcsFunc();
76 Constant *getEndFileFunc();
77
Nick Lewycky1790c9c2011-04-26 03:54:16 +000078 // Create or retrieve an i32 state value that is used to represent the
79 // pred block number for certain non-trivial edges.
80 GlobalVariable *getEdgeStateValue();
81
82 // Produce a table of pointers to counters, by predecessor and successor
83 // block number.
84 GlobalVariable *buildEdgeLookupTable(Function *F,
85 GlobalVariable *Counter,
86 const UniqueVector<BasicBlock *> &Preds,
87 const UniqueVector<BasicBlock *> &Succs);
88
Nick Lewyckyb1928702011-04-16 01:20:23 +000089 // Add the function to write out all our counters to the global destructor
90 // list.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000091 void insertCounterWriteout(SmallVector<std::pair<GlobalVariable *,
Nick Lewycky5409a182011-05-05 02:46:38 +000092 MDNode *>, 8> &);
Nick Lewyckyb1928702011-04-16 01:20:23 +000093
Nick Lewycky269687f2011-05-04 04:03:04 +000094 std::string mangleName(DICompileUnit CU, std::string NewStem);
95
Nick Lewyckya61e52c2011-04-21 01:56:25 +000096 bool EmitNotes;
97 bool EmitData;
Bill Wendlingf5c95b82011-05-17 23:05:13 +000098 bool Use402Format;
Nick Lewyckybba40db2011-11-27 23:22:20 +000099 bool UseExtraChecksum;
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000100
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000101 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000102 LLVMContext *Ctx;
103 };
104}
105
106char GCOVProfiler::ID = 0;
107INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
108 "Insert instrumentation for GCOV profiling", false, false)
109
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000110ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
111 bool Use402Format) {
112 return new GCOVProfiler(EmitNotes, EmitData, Use402Format);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000113}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000114
Nick Lewyckyb1928702011-04-16 01:20:23 +0000115namespace {
116 class GCOVRecord {
117 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000118 static const char *LinesTag;
119 static const char *FunctionTag;
120 static const char *BlockTag;
121 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000122
123 GCOVRecord() {}
124
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000125 void writeBytes(const char *Bytes, int Size) {
126 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000127 }
128
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000129 void write(uint32_t i) {
130 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000131 }
132
133 // Returns the length measured in 4-byte blocks that will be used to
134 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000135 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000136 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000137 // padding out to the next 4-byte word. The length is measured in 4-byte
138 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000139 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000140 }
141
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000142 void writeGCOVString(StringRef s) {
143 uint32_t Len = lengthOfGCOVString(s);
144 write(Len);
145 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000146
147 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000148 assert((unsigned)(4 - (s.size() % 4)) > 0);
149 assert((unsigned)(4 - (s.size() % 4)) <= 4);
150 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000151 }
152
153 raw_ostream *os;
154 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000155 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
156 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
157 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
158 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000159
160 class GCOVFunction;
161 class GCOVBlock;
162
163 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Patel16c19a12011-09-20 18:35:00 +0000164 // list of line numbers and a single filename, representing lines that belong
165 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000166 class GCOVLines : public GCOVRecord {
167 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000168 void addLine(uint32_t Line) {
169 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000170 }
171
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000172 uint32_t length() {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000173 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000174 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000175 }
176
Devang Patel16c19a12011-09-20 18:35:00 +0000177 void writeOut() {
178 write(0);
179 writeGCOVString(Filename);
180 for (int i = 0, e = Lines.size(); i != e; ++i)
181 write(Lines[i]);
182 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000183
Devang Patel16c19a12011-09-20 18:35:00 +0000184 GCOVLines(StringRef F, raw_ostream *os)
185 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000186 this->os = os;
187 }
188
Devang Patel680018f2011-09-20 18:48:56 +0000189 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000190 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000191 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000192 };
193
194 // Represent a basic block in GCOV. Each block has a unique number in the
195 // function, number of lines belonging to each block, and a set of edges to
196 // other blocks.
197 class GCOVBlock : public GCOVRecord {
198 public:
Devang Patel68155d32011-09-20 17:55:19 +0000199 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000200 GCOVLines *&Lines = LinesByFile[Filename];
201 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000202 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000203 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000204 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000205 }
206
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000207 void addEdge(GCOVBlock &Successor) {
208 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000209 }
210
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000211 void writeOut() {
212 uint32_t Len = 3;
213 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
214 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000215 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000216 }
217
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000218 writeBytes(LinesTag, 4);
219 write(Len);
220 write(Number);
221 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
Devang Patel16c19a12011-09-20 18:35:00 +0000222 E = LinesByFile.end(); I != E; ++I)
223 I->second->writeOut();
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:
Nick Lewyckybba40db2011-11-27 23:22:20 +0000250 GCOVFunction(DISubprogram SP, raw_ostream *os,
251 bool Use402Format, bool UseExtraChecksum) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000252 this->os = os;
253
254 Function *F = SP.getFunction();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000255 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000256 uint32_t i = 0;
257 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000258 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000259 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000260 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000261
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000262 writeBytes(FunctionTag, 4);
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000263 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000264 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000265 if (UseExtraChecksum)
266 ++BlockLen;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000267 write(BlockLen);
268 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
269 write(Ident);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000270 write(0); // lineno checksum
271 if (UseExtraChecksum)
272 write(0); // cfg checksum
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000273 writeGCOVString(SP.getName());
274 writeGCOVString(SP.getFilename());
275 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000276 }
277
278 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000279 DeleteContainerSeconds(Blocks);
280 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000281 }
282
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000283 GCOVBlock &getBlock(BasicBlock *BB) {
284 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000285 }
286
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000287 GCOVBlock &getReturnBlock() {
288 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000289 }
290
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000291 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000292 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000293 writeBytes(BlockTag, 4);
294 write(Blocks.size() + 1);
295 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
296 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000297 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000298 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000299
300 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000301 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
302 E = Blocks.end(); I != E; ++I) {
303 GCOVBlock &Block = *I->second;
304 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000305
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000306 writeBytes(EdgeTag, 4);
307 write(Block.OutEdges.size() * 2 + 1);
308 write(Block.Number);
309 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000310 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
311 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000312 write(Block.OutEdges[i]->Number);
313 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000314 }
315 }
316
317 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000318 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
319 E = Blocks.end(); I != E; ++I) {
320 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000321 }
322 }
323
324 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000325 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
326 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000327 };
328}
329
Nick Lewycky269687f2011-05-04 04:03:04 +0000330std::string GCOVProfiler::mangleName(DICompileUnit CU, std::string NewStem) {
331 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
332 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
333 MDNode *N = GCov->getOperand(i);
334 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000335 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000336 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000337 if (!GCovFile || !CompileUnit) continue;
338 if (CompileUnit == CU) {
339 SmallString<128> Filename = GCovFile->getString();
340 sys::path::replace_extension(Filename, NewStem);
341 return Filename.str();
342 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000343 }
344 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000345
346 SmallString<128> Filename = CU.getFilename();
347 sys::path::replace_extension(Filename, NewStem);
348 return sys::path::filename(Filename.str());
Nick Lewycky269687f2011-05-04 04:03:04 +0000349}
350
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000351bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000352 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000353 Ctx = &M.getContext();
354
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000355 if (EmitNotes) emitGCNO();
356 if (EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000357 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000358}
359
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000360void GCOVProfiler::emitGCNO() {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000361 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewyckybba40db2011-11-27 23:22:20 +0000362 if (!CU_Nodes) return;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000363
Nick Lewyckybba40db2011-11-27 23:22:20 +0000364 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
365 // Each compile unit gets its own .gcno file. This means that whether we run
366 // this pass over the original .o's as they're produced, or run it after
367 // LTO, we'll generate the same .gcno files.
368
369 DICompileUnit CU(CU_Nodes->getOperand(i));
370 std::string ErrorInfo;
371 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
372 raw_fd_ostream::F_Binary);
373 if (!Use402Format)
374 out.write("oncg*404MVLL", 12);
375 else
376 out.write("oncg*204MVLL", 12);
377
378 DIArray SPs = CU.getSubprograms();
379 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
380 DISubprogram SP(SPs.getElement(i));
381 if (!SP.Verify()) continue;
382
383 Function *F = SP.getFunction();
384 if (!F) continue;
385 GCOVFunction Func(SP, &out, Use402Format, UseExtraChecksum);
386
387 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
388 GCOVBlock &Block = Func.getBlock(BB);
389 TerminatorInst *TI = BB->getTerminator();
390 if (int successors = TI->getNumSuccessors()) {
391 for (int i = 0; i != successors; ++i) {
392 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
393 }
394 } else if (isa<ReturnInst>(TI)) {
395 Block.addEdge(Func.getReturnBlock());
396 }
397
398 uint32_t Line = 0;
399 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
400 I != IE; ++I) {
401 const DebugLoc &Loc = I->getDebugLoc();
402 if (Loc.isUnknown()) continue;
403 if (Line == Loc.getLine()) continue;
404 Line = Loc.getLine();
405 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
406
407 GCOVLines &Lines = Block.getFile(SP.getFilename());
408 Lines.addLine(Loc.getLine());
409 }
410 }
411 Func.writeOut();
412 }
413 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
414 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000415 }
416}
417
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000418bool GCOVProfiler::emitProfileArcs() {
419 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
420 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000421
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000422 bool Result = false;
423 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
424 DICompileUnit CU(CU_Nodes->getOperand(i));
425 DIArray SPs = CU.getSubprograms();
426 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
427 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
428 DISubprogram SP(SPs.getElement(i));
429 if (!SP.Verify()) continue;
430 Function *F = SP.getFunction();
431 if (!F) continue;
432 if (!Result) Result = true;
433 unsigned Edges = 0;
434 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
435 TerminatorInst *TI = BB->getTerminator();
436 if (isa<ReturnInst>(TI))
437 ++Edges;
438 else
439 Edges += TI->getNumSuccessors();
440 }
441
442 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000443 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000444 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000445 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000446 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000447 Constant::getNullValue(CounterTy),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000448 "__llvm_gcov_ctr", 0, false, 0);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000449 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
450
451 UniqueVector<BasicBlock *> ComplexEdgePreds;
452 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
453
454 unsigned Edge = 0;
455 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
456 TerminatorInst *TI = BB->getTerminator();
457 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
458 if (Successors) {
459 IRBuilder<> Builder(TI);
460
461 if (Successors == 1) {
462 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
463 Edge);
464 Value *Count = Builder.CreateLoad(Counter);
465 Count = Builder.CreateAdd(Count,
466 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
467 Builder.CreateStore(Count, Counter);
468 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
469 Value *Sel = Builder.CreateSelect(
Nick Lewyckyb1928702011-04-16 01:20:23 +0000470 BI->getCondition(),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000471 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
472 ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000473 SmallVector<Value *, 2> Idx;
474 Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
475 Idx.push_back(Sel);
476 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
477 Value *Count = Builder.CreateLoad(Counter);
478 Count = Builder.CreateAdd(Count,
479 ConstantInt::get(Type::getInt64Ty(*Ctx),1));
480 Builder.CreateStore(Count, Counter);
481 } else {
482 ComplexEdgePreds.insert(BB);
483 for (int i = 0; i != Successors; ++i)
484 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
485 }
486 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000487 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000488 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000489
490 if (!ComplexEdgePreds.empty()) {
491 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000492 buildEdgeLookupTable(F, Counters,
493 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000494 GlobalVariable *EdgeState = getEdgeStateValue();
495
496 Type *Int32Ty = Type::getInt32Ty(*Ctx);
497 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
498 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
499 Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
500 }
501 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
502 // call runtime to perform increment
503 BasicBlock::iterator InsertPt =
504 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
505 IRBuilder<> Builder(InsertPt);
506 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000507 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
508 i * ComplexEdgePreds.size());
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000509 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
510 EdgeState, CounterPtrArray);
511 // clear the predecessor number
512 Builder.CreateStore(ConstantInt::get(Int32Ty, 0xffffffff), EdgeState);
513 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000514 }
515 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000516 insertCounterWriteout(CountersBySP);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000517 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000518 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000519}
520
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000521// All edges with successors that aren't branches are "complex", because it
522// requires complex logic to pick which counter to update.
523GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
524 Function *F,
525 GlobalVariable *Counters,
526 const UniqueVector<BasicBlock *> &Preds,
527 const UniqueVector<BasicBlock *> &Succs) {
528 // TODO: support invoke, threads. We rely on the fact that nothing can modify
529 // the whole-Module pred edge# between the time we set it and the time we next
530 // read it. Threads and invoke make this untrue.
531
532 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000533 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
534 ArrayType *EdgeTableTy = ArrayType::get(
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000535 Int64PtrTy, Succs.size() * Preds.size());
536
537 Constant **EdgeTable = new Constant*[Succs.size() * Preds.size()];
538 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
539 for (int i = 0, ie = Succs.size() * Preds.size(); i != ie; ++i)
540 EdgeTable[i] = NullValue;
541
542 unsigned Edge = 0;
543 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
544 TerminatorInst *TI = BB->getTerminator();
545 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000546 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000547 for (int i = 0; i != Successors; ++i) {
548 BasicBlock *Succ = TI->getSuccessor(i);
549 IRBuilder<> builder(Succ);
550 Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
551 Edge + i);
552 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
553 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
554 }
555 }
556 Edge += Successors;
557 }
558
Jay Foad26701082011-06-22 09:24:39 +0000559 ArrayRef<Constant*> V(&EdgeTable[0], Succs.size() * Preds.size());
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000560 GlobalVariable *EdgeTableGV =
561 new GlobalVariable(
562 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000563 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000564 "__llvm_gcda_edge_table");
565 EdgeTableGV->setUnnamedAddr(true);
566 return EdgeTableGV;
567}
568
Nick Lewyckyb1928702011-04-16 01:20:23 +0000569Constant *GCOVProfiler::getStartFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000570 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Jay Foad5fdd6c82011-07-12 14:06:48 +0000571 Type::getInt8PtrTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000572 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
573}
574
575Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000576 Type *Args[] = {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000577 Type::getInt32PtrTy(*Ctx), // uint32_t *predecessor
578 Type::getInt64PtrTy(*Ctx)->getPointerTo(), // uint64_t **state_table_row
579 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000580 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000581 Args, false);
582 return M->getOrInsertFunction("llvm_gcda_increment_indirect_counter", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000583}
584
585Constant *GCOVProfiler::getEmitFunctionFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000586 Type *Args[2] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000587 Type::getInt32Ty(*Ctx), // uint32_t ident
588 Type::getInt8PtrTy(*Ctx), // const char *function_name
589 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000590 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000591 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000592 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000593}
594
595Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000596 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000597 Type::getInt32Ty(*Ctx), // uint32_t num_counters
598 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
599 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000600 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000601 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000602 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000603}
604
605Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000606 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000607 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000608}
609
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000610GlobalVariable *GCOVProfiler::getEdgeStateValue() {
611 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
612 if (!GV) {
613 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
614 GlobalValue::InternalLinkage,
615 ConstantInt::get(Type::getInt32Ty(*Ctx),
616 0xffffffff),
617 "__llvm_gcov_global_state_pred");
618 GV->setUnnamedAddr(true);
619 }
620 return GV;
621}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000622
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000623void GCOVProfiler::insertCounterWriteout(
Nick Lewycky5409a182011-05-05 02:46:38 +0000624 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> &CountersBySP) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000625 FunctionType *WriteoutFTy =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000626 FunctionType::get(Type::getVoidTy(*Ctx), false);
627 Function *WriteoutF = Function::Create(WriteoutFTy,
628 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000629 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000630 WriteoutF->setUnnamedAddr(true);
631 BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000632 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000633
634 Constant *StartFile = getStartFileFunc();
635 Constant *EmitFunction = getEmitFunctionFunc();
636 Constant *EmitArcs = getEmitArcsFunc();
637 Constant *EndFile = getEndFileFunc();
638
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000639 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
640 if (CU_Nodes) {
641 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
642 DICompileUnit compile_unit(CU_Nodes->getOperand(i));
643 std::string FilenameGcda = mangleName(compile_unit, "gcda");
644 Builder.CreateCall(StartFile,
645 Builder.CreateGlobalStringPtr(FilenameGcda));
646 for (SmallVector<std::pair<GlobalVariable *, MDNode *>, 8>::iterator
Nick Lewycky5409a182011-05-05 02:46:38 +0000647 I = CountersBySP.begin(), E = CountersBySP.end();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000648 I != E; ++I) {
649 DISubprogram SP(I->second);
650 intptr_t ident = reinterpret_cast<intptr_t>(I->second);
651 Builder.CreateCall2(EmitFunction,
652 ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
653 Builder.CreateGlobalStringPtr(SP.getName()));
654
655 GlobalVariable *GV = I->first;
656 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000657 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000658 Builder.CreateCall2(EmitArcs,
659 ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
660 Builder.CreateConstGEP2_64(GV, 0, 0));
661 }
662 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000663 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000664 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000665 Builder.CreateRetVoid();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000666
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000667 InsertProfilingShutdownCall(WriteoutF, M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000668}