blob: db1dd41283080bdd14f4ab54a1ea3cdd9957ffee [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
Nick Lewyckyb1928702011-04-16 01:20:23 +000019#include "llvm/Transforms/Instrumentation.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "ProfilingUtils.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000021#include "llvm/ADT/DenseMap.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000022#include "llvm/ADT/STLExtras.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000023#include "llvm/ADT/Statistic.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000024#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/UniqueVector.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/DebugInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000028#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Module.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000031#include "llvm/Pass.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/DebugLoc.h"
34#include "llvm/Support/InstIterator.h"
35#include "llvm/Support/PathV2.h"
36#include "llvm/Support/raw_ostream.h"
37#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000038#include <string>
39#include <utility>
40using namespace llvm;
41
42namespace {
43 class GCOVProfiler : public ModulePass {
Nick Lewyckyb1928702011-04-16 01:20:23 +000044 public:
45 static char ID;
Nick Lewyckya61e52c2011-04-21 01:56:25 +000046 GCOVProfiler()
Nick Lewyckyd9686a92013-03-07 08:28:49 +000047 : ModulePass(ID), EmitNotes(true), EmitData(true),
Nick Lewycky52b4edf2013-02-27 06:22:56 +000048 UseExtraChecksum(false), NoRedZone(false),
49 NoFunctionNamesInData(false) {
Nick Lewyckyd9686a92013-03-07 08:28:49 +000050 memcpy(Version, DefaultGCovVersion, 4);
Nick Lewyckya61e52c2011-04-21 01:56:25 +000051 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
52 }
Nick Lewyckyd9686a92013-03-07 08:28:49 +000053 GCOVProfiler(bool EmitNotes, bool EmitData, const char (&Version)[4],
Nick Lewycky52b4edf2013-02-27 06:22:56 +000054 bool UseExtraChecksum, bool NoRedZone,
55 bool NoFunctionNamesInData)
Bill Wendlingf5c95b82011-05-17 23:05:13 +000056 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
Nick Lewyckyd9686a92013-03-07 08:28:49 +000057 UseExtraChecksum(UseExtraChecksum), NoRedZone(NoRedZone),
58 NoFunctionNamesInData(NoFunctionNamesInData) {
59 memcpy(this->Version, Version, 4);
Nick Lewyckya61e52c2011-04-21 01:56:25 +000060 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
Nick Lewyckyb1928702011-04-16 01:20:23 +000061 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
62 }
63 virtual const char *getPassName() const {
64 return "GCOV Profiler";
65 }
Nick Lewyckyb1928702011-04-16 01:20:23 +000066 private:
Nick Lewycky269687f2011-05-04 04:03:04 +000067 bool runOnModule(Module &M);
68
Nick Lewyckyb1928702011-04-16 01:20:23 +000069 // Create the GCNO files for the Module based on DebugInfo.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000070 void emitGCNO();
Nick Lewyckyb1928702011-04-16 01:20:23 +000071
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000072 // Modify the program to track transitions along edges and call into the
73 // profiling runtime to emit .gcda files when run.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000074 bool emitProfileArcs();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000075
Nick Lewyckyb1928702011-04-16 01:20:23 +000076 // Get pointers to the functions in the runtime library.
77 Constant *getStartFileFunc();
Bill Wendling77b19132012-05-28 06:10:56 +000078 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +000079 Constant *getEmitFunctionFunc();
80 Constant *getEmitArcsFunc();
81 Constant *getEndFileFunc();
82
Nick Lewycky1790c9c2011-04-26 03:54:16 +000083 // Create or retrieve an i32 state value that is used to represent the
84 // pred block number for certain non-trivial edges.
85 GlobalVariable *getEdgeStateValue();
86
87 // Produce a table of pointers to counters, by predecessor and successor
88 // block number.
89 GlobalVariable *buildEdgeLookupTable(Function *F,
90 GlobalVariable *Counter,
91 const UniqueVector<BasicBlock *> &Preds,
92 const UniqueVector<BasicBlock *> &Succs);
93
Nick Lewyckyb1928702011-04-16 01:20:23 +000094 // Add the function to write out all our counters to the global destructor
95 // list.
Bill Wendling21b742f2012-08-29 18:45:41 +000096 void insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Bill Wendling77b19132012-05-28 06:10:56 +000097 void insertIndirectCounterIncrement();
Bill Wendling253353c2012-09-13 00:09:55 +000098 void insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Nick Lewyckyb1928702011-04-16 01:20:23 +000099
Bill Wendling73996f42012-08-30 01:32:31 +0000100 std::string mangleName(DICompileUnit CU, const char *NewStem);
Nick Lewycky269687f2011-05-04 04:03:04 +0000101
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000102 bool EmitNotes;
103 bool EmitData;
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000104 char Version[4];
Nick Lewyckybba40db2011-11-27 23:22:20 +0000105 bool UseExtraChecksum;
Bill Wendling08e13e42012-12-10 19:46:49 +0000106 bool NoRedZone;
Nick Lewycky52b4edf2013-02-27 06:22:56 +0000107 bool NoFunctionNamesInData;
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000108
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000109 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000110 LLVMContext *Ctx;
111 };
112}
113
114char GCOVProfiler::ID = 0;
115INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
116 "Insert instrumentation for GCOV profiling", false, false)
117
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000118ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000119 const char (&Version)[4],
Bill Wendling08e13e42012-12-10 19:46:49 +0000120 bool UseExtraChecksum,
Nick Lewycky52b4edf2013-02-27 06:22:56 +0000121 bool NoRedZone,
122 bool NoFunctionNamesInData) {
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000123 return new GCOVProfiler(EmitNotes, EmitData, Version, UseExtraChecksum,
Nick Lewycky52b4edf2013-02-27 06:22:56 +0000124 NoRedZone, NoFunctionNamesInData);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000125}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000126
Nick Lewyckyb1928702011-04-16 01:20:23 +0000127namespace {
128 class GCOVRecord {
129 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000130 static const char *LinesTag;
131 static const char *FunctionTag;
132 static const char *BlockTag;
133 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000134
135 GCOVRecord() {}
136
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000137 void writeBytes(const char *Bytes, int Size) {
138 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000139 }
140
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000141 void write(uint32_t i) {
142 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000143 }
144
145 // Returns the length measured in 4-byte blocks that will be used to
146 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000147 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000148 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000149 // padding out to the next 4-byte word. The length is measured in 4-byte
150 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000151 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000152 }
153
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000154 void writeGCOVString(StringRef s) {
155 uint32_t Len = lengthOfGCOVString(s);
156 write(Len);
157 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000158
159 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000160 assert((unsigned)(4 - (s.size() % 4)) > 0);
161 assert((unsigned)(4 - (s.size() % 4)) <= 4);
162 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000163 }
164
165 raw_ostream *os;
166 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000167 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
168 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
169 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
170 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000171
172 class GCOVFunction;
173 class GCOVBlock;
174
175 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Patel16c19a12011-09-20 18:35:00 +0000176 // list of line numbers and a single filename, representing lines that belong
177 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000178 class GCOVLines : public GCOVRecord {
179 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000180 void addLine(uint32_t Line) {
181 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000182 }
183
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000184 uint32_t length() {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000185 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000186 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000187 }
188
Devang Patel16c19a12011-09-20 18:35:00 +0000189 void writeOut() {
190 write(0);
191 writeGCOVString(Filename);
192 for (int i = 0, e = Lines.size(); i != e; ++i)
193 write(Lines[i]);
194 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000195
Devang Patel16c19a12011-09-20 18:35:00 +0000196 GCOVLines(StringRef F, raw_ostream *os)
197 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000198 this->os = os;
199 }
200
Devang Patel680018f2011-09-20 18:48:56 +0000201 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000202 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000203 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000204 };
205
206 // Represent a basic block in GCOV. Each block has a unique number in the
207 // function, number of lines belonging to each block, and a set of edges to
208 // other blocks.
209 class GCOVBlock : public GCOVRecord {
210 public:
Devang Patel68155d32011-09-20 17:55:19 +0000211 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000212 GCOVLines *&Lines = LinesByFile[Filename];
213 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000214 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000215 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000216 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000217 }
218
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000219 void addEdge(GCOVBlock &Successor) {
220 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000221 }
222
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000223 void writeOut() {
224 uint32_t Len = 3;
225 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
226 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000227 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000228 }
229
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000230 writeBytes(LinesTag, 4);
231 write(Len);
232 write(Number);
233 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
Devang Patel16c19a12011-09-20 18:35:00 +0000234 E = LinesByFile.end(); I != E; ++I)
235 I->second->writeOut();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000236 write(0);
237 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000238 }
239
240 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000241 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000242 }
243
244 private:
245 friend class GCOVFunction;
246
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000247 GCOVBlock(uint32_t Number, raw_ostream *os)
248 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000249 this->os = os;
250 }
251
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000252 uint32_t Number;
253 StringMap<GCOVLines *> LinesByFile;
254 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000255 };
256
257 // A function has a unique identifier, a checksum (we leave as zero) and a
258 // set of blocks and a map of edges between blocks. This is the only GCOV
259 // object users can construct, the blocks and lines will be rooted here.
260 class GCOVFunction : public GCOVRecord {
261 public:
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000262 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
263 bool UseExtraChecksum) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000264 this->os = os;
265
266 Function *F = SP.getFunction();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000267 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000268 uint32_t i = 0;
269 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000270 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000271 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000272 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000273
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000274 writeBytes(FunctionTag, 4);
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000275 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000276 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000277 if (UseExtraChecksum)
278 ++BlockLen;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000279 write(BlockLen);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000280 write(Ident);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000281 write(0); // lineno checksum
282 if (UseExtraChecksum)
283 write(0); // cfg checksum
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000284 writeGCOVString(SP.getName());
285 writeGCOVString(SP.getFilename());
286 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000287 }
288
289 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000290 DeleteContainerSeconds(Blocks);
291 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000292 }
293
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000294 GCOVBlock &getBlock(BasicBlock *BB) {
295 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000296 }
297
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000298 GCOVBlock &getReturnBlock() {
299 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000300 }
301
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000302 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000303 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000304 writeBytes(BlockTag, 4);
305 write(Blocks.size() + 1);
306 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
307 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000308 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000309 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000310
311 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000312 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
313 E = Blocks.end(); I != E; ++I) {
314 GCOVBlock &Block = *I->second;
315 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000316
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000317 writeBytes(EdgeTag, 4);
318 write(Block.OutEdges.size() * 2 + 1);
319 write(Block.Number);
320 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000321 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
322 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000323 write(Block.OutEdges[i]->Number);
324 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000325 }
326 }
327
328 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000329 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
330 E = Blocks.end(); I != E; ++I) {
331 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000332 }
333 }
334
335 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000336 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
337 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000338 };
339}
340
Bill Wendling73996f42012-08-30 01:32:31 +0000341std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
Nick Lewycky269687f2011-05-04 04:03:04 +0000342 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
343 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
344 MDNode *N = GCov->getOperand(i);
345 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000346 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000347 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000348 if (!GCovFile || !CompileUnit) continue;
349 if (CompileUnit == CU) {
Bill Wendling6e5190c2012-08-30 00:34:21 +0000350 SmallString<128> Filename = GCovFile->getString();
351 sys::path::replace_extension(Filename, NewStem);
352 return Filename.str();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000353 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000354 }
355 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000356
Bill Wendling6e5190c2012-08-30 00:34:21 +0000357 SmallString<128> Filename = CU.getFilename();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000358 sys::path::replace_extension(Filename, NewStem);
Bill Wendling6e5190c2012-08-30 00:34:21 +0000359 return sys::path::filename(Filename.str());
Nick Lewycky269687f2011-05-04 04:03:04 +0000360}
361
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000362bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000363 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000364 Ctx = &M.getContext();
365
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000366 if (EmitNotes) emitGCNO();
367 if (EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000368 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000369}
370
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000371void GCOVProfiler::emitGCNO() {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000372 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewyckybba40db2011-11-27 23:22:20 +0000373 if (!CU_Nodes) return;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000374
Nick Lewyckybba40db2011-11-27 23:22:20 +0000375 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
376 // Each compile unit gets its own .gcno file. This means that whether we run
377 // this pass over the original .o's as they're produced, or run it after
378 // LTO, we'll generate the same .gcno files.
379
380 DICompileUnit CU(CU_Nodes->getOperand(i));
381 std::string ErrorInfo;
382 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
383 raw_fd_ostream::F_Binary);
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000384 out.write("oncg", 4);
385 out.write(Version, 4);
386 out.write("MVLL", 4);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000387
388 DIArray SPs = CU.getSubprograms();
389 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
390 DISubprogram SP(SPs.getElement(i));
391 if (!SP.Verify()) continue;
392
393 Function *F = SP.getFunction();
394 if (!F) continue;
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000395 GCOVFunction Func(SP, &out, i, UseExtraChecksum);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000396
397 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
398 GCOVBlock &Block = Func.getBlock(BB);
399 TerminatorInst *TI = BB->getTerminator();
400 if (int successors = TI->getNumSuccessors()) {
401 for (int i = 0; i != successors; ++i) {
402 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
403 }
404 } else if (isa<ReturnInst>(TI)) {
405 Block.addEdge(Func.getReturnBlock());
406 }
407
408 uint32_t Line = 0;
409 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
410 I != IE; ++I) {
411 const DebugLoc &Loc = I->getDebugLoc();
412 if (Loc.isUnknown()) continue;
413 if (Line == Loc.getLine()) continue;
414 Line = Loc.getLine();
415 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
416
417 GCOVLines &Lines = Block.getFile(SP.getFilename());
418 Lines.addLine(Loc.getLine());
419 }
420 }
421 Func.writeOut();
422 }
423 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
424 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000425 }
426}
427
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000428bool GCOVProfiler::emitProfileArcs() {
429 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
430 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000431
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000432 bool Result = false;
Bill Wendling77b19132012-05-28 06:10:56 +0000433 bool InsertIndCounterIncrCode = false;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000434 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
435 DICompileUnit CU(CU_Nodes->getOperand(i));
436 DIArray SPs = CU.getSubprograms();
437 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
438 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
439 DISubprogram SP(SPs.getElement(i));
440 if (!SP.Verify()) continue;
441 Function *F = SP.getFunction();
442 if (!F) continue;
443 if (!Result) Result = true;
444 unsigned Edges = 0;
445 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
446 TerminatorInst *TI = BB->getTerminator();
447 if (isa<ReturnInst>(TI))
448 ++Edges;
449 else
450 Edges += TI->getNumSuccessors();
451 }
452
453 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000454 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000455 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000456 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000457 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000458 Constant::getNullValue(CounterTy),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000459 "__llvm_gcov_ctr");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000460 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
461
462 UniqueVector<BasicBlock *> ComplexEdgePreds;
463 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
464
465 unsigned Edge = 0;
466 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
467 TerminatorInst *TI = BB->getTerminator();
468 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
469 if (Successors) {
470 IRBuilder<> Builder(TI);
471
472 if (Successors == 1) {
473 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
474 Edge);
475 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000476 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000477 Builder.CreateStore(Count, Counter);
478 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000479 Value *Sel = Builder.CreateSelect(BI->getCondition(),
480 Builder.getInt64(Edge),
481 Builder.getInt64(Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000482 SmallVector<Value *, 2> Idx;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000483 Idx.push_back(Builder.getInt64(0));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000484 Idx.push_back(Sel);
485 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
486 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000487 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000488 Builder.CreateStore(Count, Counter);
489 } else {
490 ComplexEdgePreds.insert(BB);
491 for (int i = 0; i != Successors; ++i)
492 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
493 }
494 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000495 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000496 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000497
498 if (!ComplexEdgePreds.empty()) {
499 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000500 buildEdgeLookupTable(F, Counters,
501 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000502 GlobalVariable *EdgeState = getEdgeStateValue();
503
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000504 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
505 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000506 Builder.CreateStore(Builder.getInt32(i), EdgeState);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000507 }
508 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
509 // call runtime to perform increment
Bill Wendling77b19132012-05-28 06:10:56 +0000510 BasicBlock::iterator InsertPt =
511 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000512 IRBuilder<> Builder(InsertPt);
513 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000514 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
515 i * ComplexEdgePreds.size());
Bill Wendlingc7a88402012-05-25 23:55:00 +0000516
517 // Build code to increment the counter.
Bill Wendling77b19132012-05-28 06:10:56 +0000518 InsertIndCounterIncrCode = true;
519 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
520 EdgeState, CounterPtrArray);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000521 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000522 }
523 }
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000524
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000525 insertCounterWriteout(CountersBySP);
Bill Wendling253353c2012-09-13 00:09:55 +0000526 insertFlush(CountersBySP);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000527 }
Bill Wendling77b19132012-05-28 06:10:56 +0000528
529 if (InsertIndCounterIncrCode)
530 insertIndirectCounterIncrement();
531
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000532 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000533}
534
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000535// All edges with successors that aren't branches are "complex", because it
536// requires complex logic to pick which counter to update.
537GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
538 Function *F,
539 GlobalVariable *Counters,
540 const UniqueVector<BasicBlock *> &Preds,
541 const UniqueVector<BasicBlock *> &Succs) {
542 // TODO: support invoke, threads. We rely on the fact that nothing can modify
543 // the whole-Module pred edge# between the time we set it and the time we next
544 // read it. Threads and invoke make this untrue.
545
546 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000547 size_t TableSize = Succs.size() * Preds.size();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000548 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000549 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000550
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000551 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000552 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000553 for (size_t i = 0; i != TableSize; ++i)
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000554 EdgeTable[i] = NullValue;
555
556 unsigned Edge = 0;
557 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
558 TerminatorInst *TI = BB->getTerminator();
559 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000560 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000561 for (int i = 0; i != Successors; ++i) {
562 BasicBlock *Succ = TI->getSuccessor(i);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000563 IRBuilder<> Builder(Succ);
564 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000565 Edge + i);
566 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
567 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
568 }
569 }
570 Edge += Successors;
571 }
572
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000573 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000574 GlobalVariable *EdgeTableGV =
575 new GlobalVariable(
576 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000577 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000578 "__llvm_gcda_edge_table");
579 EdgeTableGV->setUnnamedAddr(true);
580 return EdgeTableGV;
581}
582
Nick Lewyckyb1928702011-04-16 01:20:23 +0000583Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000584 Type *Args[] = {
585 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
586 Type::getInt8PtrTy(*Ctx), // const char version[4]
587 };
588 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000589 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
590}
591
Bill Wendling77b19132012-05-28 06:10:56 +0000592Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
593 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendlingc7a88402012-05-25 23:55:00 +0000594 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling77b19132012-05-28 06:10:56 +0000595 Type *Args[] = {
Micah Villmowb8bce922012-10-24 17:25:11 +0000596 Int32Ty->getPointerTo(), // uint32_t *predecessor
597 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling77b19132012-05-28 06:10:56 +0000598 };
599 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
600 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000601}
602
603Constant *GCOVProfiler::getEmitFunctionFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000604 Type *Args[2] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000605 Type::getInt32Ty(*Ctx), // uint32_t ident
606 Type::getInt8PtrTy(*Ctx), // const char *function_name
607 };
Bill Wendlingc7a88402012-05-25 23:55:00 +0000608 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000609 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000610}
611
612Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000613 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000614 Type::getInt32Ty(*Ctx), // uint32_t num_counters
615 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
616 };
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000617 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000618 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000619}
620
621Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000622 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000623 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000624}
625
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000626GlobalVariable *GCOVProfiler::getEdgeStateValue() {
627 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
628 if (!GV) {
629 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
630 GlobalValue::InternalLinkage,
631 ConstantInt::get(Type::getInt32Ty(*Ctx),
632 0xffffffff),
633 "__llvm_gcov_global_state_pred");
634 GV->setUnnamedAddr(true);
635 }
636 return GV;
637}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000638
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000639void GCOVProfiler::insertCounterWriteout(
Bill Wendling21b742f2012-08-29 18:45:41 +0000640 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling253353c2012-09-13 00:09:55 +0000641 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
642 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
643 if (!WriteoutF)
644 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
645 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000646 WriteoutF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000647 WriteoutF->addFnAttr(Attribute::NoInline);
Bill Wendling08e13e42012-12-10 19:46:49 +0000648 if (NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000649 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000650
651 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000652 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000653
654 Constant *StartFile = getStartFileFunc();
655 Constant *EmitFunction = getEmitFunctionFunc();
656 Constant *EmitArcs = getEmitArcsFunc();
657 Constant *EndFile = getEndFileFunc();
658
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000659 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
660 if (CU_Nodes) {
661 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Bill Wendling032dbee2012-09-13 14:32:30 +0000662 DICompileUnit CU(CU_Nodes->getOperand(i));
663 std::string FilenameGcda = mangleName(CU, "gcda");
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000664 Builder.CreateCall2(StartFile,
665 Builder.CreateGlobalStringPtr(FilenameGcda),
666 Builder.CreateGlobalStringPtr(Version));
Bill Wendling21b742f2012-08-29 18:45:41 +0000667 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
Nick Lewycky5409a182011-05-05 02:46:38 +0000668 I = CountersBySP.begin(), E = CountersBySP.end();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000669 I != E; ++I) {
670 DISubprogram SP(I->second);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000671 Builder.CreateCall2(EmitFunction,
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000672 Builder.getInt32(i),
Nick Lewycky52b4edf2013-02-27 06:22:56 +0000673 NoFunctionNamesInData ?
674 Constant::getNullValue(Builder.getInt8PtrTy()) :
675 Builder.CreateGlobalStringPtr(SP.getName()));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000676
677 GlobalVariable *GV = I->first;
678 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000679 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000680 Builder.CreateCall2(EmitArcs,
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000681 Builder.getInt32(Arcs),
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000682 Builder.CreateConstGEP2_64(GV, 0, 0));
683 }
684 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000685 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000686 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000687 Builder.CreateRetVoid();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000688
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000689 // Create a small bit of code that registers the "__llvm_gcov_writeout"
690 // function to be executed at exit.
691 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
692 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
693 "__llvm_gcov_init", M);
694 F->setUnnamedAddr(true);
695 F->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling034b94b2012-12-19 07:18:57 +0000696 F->addFnAttr(Attribute::NoInline);
Bill Wendling08e13e42012-12-10 19:46:49 +0000697 if (NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000698 F->addFnAttr(Attribute::NoRedZone);
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000699
700 BB = BasicBlock::Create(*Ctx, "entry", F);
701 Builder.SetInsertPoint(BB);
702
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000703 FTy = FunctionType::get(Builder.getInt32Ty(),
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000704 PointerType::get(FTy, 0), false);
Bill Wendlingc1b6ea72012-06-30 20:21:19 +0000705 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000706 Builder.CreateCall(AtExitFn, WriteoutF);
707 Builder.CreateRetVoid();
708
709 appendToGlobalCtors(*M, F, 0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000710}
Bill Wendling77b19132012-05-28 06:10:56 +0000711
712void GCOVProfiler::insertIndirectCounterIncrement() {
713 Function *Fn =
714 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
715 Fn->setUnnamedAddr(true);
716 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling034b94b2012-12-19 07:18:57 +0000717 Fn->addFnAttr(Attribute::NoInline);
Bill Wendling08e13e42012-12-10 19:46:49 +0000718 if (NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000719 Fn->addFnAttr(Attribute::NoRedZone);
Bill Wendling77b19132012-05-28 06:10:56 +0000720
Bill Wendling77b19132012-05-28 06:10:56 +0000721 // Create basic blocks for function.
722 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
723 IRBuilder<> Builder(BB);
724
725 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
726 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
727 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
728
729 // uint32_t pred = *predecessor;
730 // if (pred == 0xffffffff) return;
731 Argument *Arg = Fn->arg_begin();
732 Arg->setName("predecessor");
733 Value *Pred = Builder.CreateLoad(Arg, "pred");
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000734 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
Bill Wendling77b19132012-05-28 06:10:56 +0000735 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
736
737 Builder.SetInsertPoint(PredNotNegOne);
738
739 // uint64_t *counter = counters[pred];
740 // if (!counter) return;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000741 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
Bill Wendling77b19132012-05-28 06:10:56 +0000742 Arg = llvm::next(Fn->arg_begin());
743 Arg->setName("counters");
744 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
745 Value *Counter = Builder.CreateLoad(GEP, "counter");
Nick Lewycky58591b12013-02-27 06:21:30 +0000746 Cond = Builder.CreateICmpEQ(Counter,
747 Constant::getNullValue(
748 Builder.getInt64Ty()->getPointerTo()));
Bill Wendling77b19132012-05-28 06:10:56 +0000749 Builder.CreateCondBr(Cond, Exit, CounterEnd);
750
751 // ++*counter;
752 Builder.SetInsertPoint(CounterEnd);
753 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000754 Builder.getInt64(1));
Bill Wendling77b19132012-05-28 06:10:56 +0000755 Builder.CreateStore(Add, Counter);
756 Builder.CreateBr(Exit);
757
758 // Fill in the exit block.
759 Builder.SetInsertPoint(Exit);
760 Builder.CreateRetVoid();
761}
Bill Wendling253353c2012-09-13 00:09:55 +0000762
763void GCOVProfiler::
764insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
765 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendling78fff8e2012-09-17 17:57:05 +0000766 Function *FlushF = M->getFunction("__gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000767 if (!FlushF)
768 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendling78fff8e2012-09-17 17:57:05 +0000769 "__gcov_flush", M);
Bill Wendling253353c2012-09-13 00:09:55 +0000770 else
771 FlushF->setLinkage(GlobalValue::InternalLinkage);
772 FlushF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000773 FlushF->addFnAttr(Attribute::NoInline);
Bill Wendling08e13e42012-12-10 19:46:49 +0000774 if (NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000775 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000776
Bill Wendling253353c2012-09-13 00:09:55 +0000777 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
778
779 // Write out the current counters.
780 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
781 assert(WriteoutF && "Need to create the writeout function first!");
782
783 IRBuilder<> Builder(Entry);
784 Builder.CreateCall(WriteoutF);
785
Bill Wendling032dbee2012-09-13 14:32:30 +0000786 // Zero out the counters.
787 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
788 I = CountersBySP.begin(), E = CountersBySP.end();
789 I != E; ++I) {
790 GlobalVariable *GV = I->first;
791 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
Bill Wendlingec3fc2e2012-09-14 22:35:49 +0000792 Builder.CreateStore(Null, GV);
Bill Wendling032dbee2012-09-13 14:32:30 +0000793 }
Bill Wendling253353c2012-09-13 00:09:55 +0000794
795 Type *RetTy = FlushF->getReturnType();
796 if (RetTy == Type::getVoidTy(*Ctx))
797 Builder.CreateRetVoid();
798 else if (RetTy->isIntegerTy())
Bill Wendling78fff8e2012-09-17 17:57:05 +0000799 // Used if __gcov_flush was implicitly declared.
Bill Wendling253353c2012-09-13 00:09:55 +0000800 Builder.CreateRet(ConstantInt::get(RetTy, 0));
801 else
Bill Wendling78fff8e2012-09-17 17:57:05 +0000802 report_fatal_error("invalid return type for __gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000803}