blob: 921d48c3646de4e94cf9a2009c827aadeeca66bc [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"
Nick Lewyckya204ef32013-03-14 05:13:26 +000032#include "llvm/Support/CommandLine.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000033#include "llvm/Support/Debug.h"
34#include "llvm/Support/DebugLoc.h"
35#include "llvm/Support/InstIterator.h"
36#include "llvm/Support/PathV2.h"
37#include "llvm/Support/raw_ostream.h"
38#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000039#include <string>
40#include <utility>
41using namespace llvm;
42
Nick Lewyckya204ef32013-03-14 05:13:26 +000043static cl::opt<std::string>
44DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
45 cl::ValueRequired);
46
47GCOVOptions GCOVOptions::getDefault() {
48 GCOVOptions Options;
49 Options.EmitNotes = true;
50 Options.EmitData = true;
51 Options.UseCfgChecksum = false;
52 Options.NoRedZone = false;
53 Options.FunctionNamesInData = true;
54
55 if (DefaultGCOVVersion.size() != 4) {
56 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
57 DefaultGCOVVersion);
58 }
59 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
60 return Options;
61}
62
Nick Lewyckyb1928702011-04-16 01:20:23 +000063namespace {
64 class GCOVProfiler : public ModulePass {
Nick Lewyckyb1928702011-04-16 01:20:23 +000065 public:
66 static char ID;
Nick Lewyckya204ef32013-03-14 05:13:26 +000067 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
68 ReversedVersion[0] = Options.Version[3];
69 ReversedVersion[1] = Options.Version[2];
70 ReversedVersion[2] = Options.Version[1];
71 ReversedVersion[3] = Options.Version[0];
72 ReversedVersion[4] = '\0';
Nick Lewyckya61e52c2011-04-21 01:56:25 +000073 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
74 }
Nick Lewyckya204ef32013-03-14 05:13:26 +000075 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
76 assert((Options.EmitNotes || Options.EmitData) &&
77 "GCOVProfiler asked to do nothing?");
78 ReversedVersion[0] = Options.Version[3];
79 ReversedVersion[1] = Options.Version[2];
80 ReversedVersion[2] = Options.Version[1];
81 ReversedVersion[3] = Options.Version[0];
82 ReversedVersion[4] = '\0';
Nick Lewyckyb1928702011-04-16 01:20:23 +000083 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
84 }
85 virtual const char *getPassName() const {
86 return "GCOV Profiler";
87 }
Nick Lewyckya204ef32013-03-14 05:13:26 +000088
Nick Lewyckyb1928702011-04-16 01:20:23 +000089 private:
Nick Lewycky269687f2011-05-04 04:03:04 +000090 bool runOnModule(Module &M);
91
Nick Lewycky64a0a332013-03-13 22:55:42 +000092 // Create the .gcno files for the Module based on DebugInfo.
93 void emitProfileNotes();
Nick Lewyckyb1928702011-04-16 01:20:23 +000094
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000095 // Modify the program to track transitions along edges and call into the
96 // profiling runtime to emit .gcda files when run.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000097 bool emitProfileArcs();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000098
Nick Lewyckyb1928702011-04-16 01:20:23 +000099 // Get pointers to the functions in the runtime library.
100 Constant *getStartFileFunc();
Bill Wendling77b19132012-05-28 06:10:56 +0000101 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000102 Constant *getEmitFunctionFunc();
103 Constant *getEmitArcsFunc();
104 Constant *getEndFileFunc();
105
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000106 // Create or retrieve an i32 state value that is used to represent the
107 // pred block number for certain non-trivial edges.
108 GlobalVariable *getEdgeStateValue();
109
110 // Produce a table of pointers to counters, by predecessor and successor
111 // block number.
112 GlobalVariable *buildEdgeLookupTable(Function *F,
113 GlobalVariable *Counter,
Nick Lewycky64a0a332013-03-13 22:55:42 +0000114 const UniqueVector<BasicBlock *>&Preds,
115 const UniqueVector<BasicBlock*>&Succs);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000116
Nick Lewyckyb1928702011-04-16 01:20:23 +0000117 // Add the function to write out all our counters to the global destructor
118 // list.
Bill Wendling21b742f2012-08-29 18:45:41 +0000119 void insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Bill Wendling77b19132012-05-28 06:10:56 +0000120 void insertIndirectCounterIncrement();
Bill Wendling253353c2012-09-13 00:09:55 +0000121 void insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000122
Bill Wendling73996f42012-08-30 01:32:31 +0000123 std::string mangleName(DICompileUnit CU, const char *NewStem);
Nick Lewycky269687f2011-05-04 04:03:04 +0000124
Nick Lewyckya204ef32013-03-14 05:13:26 +0000125 GCOVOptions Options;
126
127 // Reversed, NUL-terminated copy of Options.Version.
128 char ReversedVersion[5];
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000129
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000130 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000131 LLVMContext *Ctx;
132 };
133}
134
135char GCOVProfiler::ID = 0;
136INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
137 "Insert instrumentation for GCOV profiling", false, false)
138
Nick Lewyckya204ef32013-03-14 05:13:26 +0000139ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
140 return new GCOVProfiler(Options);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000141}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000142
Nick Lewyckyb1928702011-04-16 01:20:23 +0000143namespace {
144 class GCOVRecord {
145 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000146 static const char *LinesTag;
147 static const char *FunctionTag;
148 static const char *BlockTag;
149 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000150
151 GCOVRecord() {}
152
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000153 void writeBytes(const char *Bytes, int Size) {
154 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000155 }
156
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000157 void write(uint32_t i) {
158 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000159 }
160
161 // Returns the length measured in 4-byte blocks that will be used to
162 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000163 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000164 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000165 // padding out to the next 4-byte word. The length is measured in 4-byte
166 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000167 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000168 }
169
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000170 void writeGCOVString(StringRef s) {
171 uint32_t Len = lengthOfGCOVString(s);
172 write(Len);
173 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000174
175 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000176 assert((unsigned)(4 - (s.size() % 4)) > 0);
177 assert((unsigned)(4 - (s.size() % 4)) <= 4);
178 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000179 }
180
181 raw_ostream *os;
182 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000183 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
184 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
185 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
186 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000187
188 class GCOVFunction;
189 class GCOVBlock;
190
191 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Patel16c19a12011-09-20 18:35:00 +0000192 // list of line numbers and a single filename, representing lines that belong
193 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000194 class GCOVLines : public GCOVRecord {
195 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000196 void addLine(uint32_t Line) {
197 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000198 }
199
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000200 uint32_t length() {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000201 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000202 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000203 }
204
Devang Patel16c19a12011-09-20 18:35:00 +0000205 void writeOut() {
206 write(0);
207 writeGCOVString(Filename);
208 for (int i = 0, e = Lines.size(); i != e; ++i)
209 write(Lines[i]);
210 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000211
Devang Patel16c19a12011-09-20 18:35:00 +0000212 GCOVLines(StringRef F, raw_ostream *os)
213 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000214 this->os = os;
215 }
216
Devang Patel680018f2011-09-20 18:48:56 +0000217 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000218 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000219 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000220 };
221
222 // Represent a basic block in GCOV. Each block has a unique number in the
223 // function, number of lines belonging to each block, and a set of edges to
224 // other blocks.
225 class GCOVBlock : public GCOVRecord {
226 public:
Devang Patel68155d32011-09-20 17:55:19 +0000227 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000228 GCOVLines *&Lines = LinesByFile[Filename];
229 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000230 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000231 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000232 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000233 }
234
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000235 void addEdge(GCOVBlock &Successor) {
236 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000237 }
238
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000239 void writeOut() {
240 uint32_t Len = 3;
241 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
242 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000243 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000244 }
245
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000246 writeBytes(LinesTag, 4);
247 write(Len);
248 write(Number);
249 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
Devang Patel16c19a12011-09-20 18:35:00 +0000250 E = LinesByFile.end(); I != E; ++I)
251 I->second->writeOut();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000252 write(0);
253 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000254 }
255
256 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000257 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000258 }
259
260 private:
261 friend class GCOVFunction;
262
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000263 GCOVBlock(uint32_t Number, raw_ostream *os)
264 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000265 this->os = os;
266 }
267
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000268 uint32_t Number;
269 StringMap<GCOVLines *> LinesByFile;
270 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000271 };
272
273 // A function has a unique identifier, a checksum (we leave as zero) and a
274 // set of blocks and a map of edges between blocks. This is the only GCOV
275 // object users can construct, the blocks and lines will be rooted here.
276 class GCOVFunction : public GCOVRecord {
277 public:
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000278 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
Nick Lewyckya204ef32013-03-14 05:13:26 +0000279 bool UseCfgChecksum) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000280 this->os = os;
281
282 Function *F = SP.getFunction();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000283 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000284 uint32_t i = 0;
285 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000286 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000287 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000288 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000289
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000290 writeBytes(FunctionTag, 4);
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000291 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000292 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Nick Lewyckya204ef32013-03-14 05:13:26 +0000293 if (UseCfgChecksum)
Nick Lewyckybba40db2011-11-27 23:22:20 +0000294 ++BlockLen;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000295 write(BlockLen);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000296 write(Ident);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000297 write(0); // lineno checksum
Nick Lewyckya204ef32013-03-14 05:13:26 +0000298 if (UseCfgChecksum)
Nick Lewyckybba40db2011-11-27 23:22:20 +0000299 write(0); // cfg checksum
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000300 writeGCOVString(SP.getName());
301 writeGCOVString(SP.getFilename());
302 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000303 }
304
305 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000306 DeleteContainerSeconds(Blocks);
307 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000308 }
309
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000310 GCOVBlock &getBlock(BasicBlock *BB) {
311 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000312 }
313
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000314 GCOVBlock &getReturnBlock() {
315 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000316 }
317
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000318 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000319 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000320 writeBytes(BlockTag, 4);
321 write(Blocks.size() + 1);
322 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
323 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000324 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000325 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000326
327 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000328 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
329 E = Blocks.end(); I != E; ++I) {
330 GCOVBlock &Block = *I->second;
331 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000332
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000333 writeBytes(EdgeTag, 4);
334 write(Block.OutEdges.size() * 2 + 1);
335 write(Block.Number);
336 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000337 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
338 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000339 write(Block.OutEdges[i]->Number);
340 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000341 }
342 }
343
344 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000345 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
346 E = Blocks.end(); I != E; ++I) {
347 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000348 }
349 }
350
351 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000352 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
353 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000354 };
355}
356
Bill Wendling73996f42012-08-30 01:32:31 +0000357std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
Nick Lewycky269687f2011-05-04 04:03:04 +0000358 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
359 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
360 MDNode *N = GCov->getOperand(i);
361 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000362 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000363 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000364 if (!GCovFile || !CompileUnit) continue;
365 if (CompileUnit == CU) {
Bill Wendling6e5190c2012-08-30 00:34:21 +0000366 SmallString<128> Filename = GCovFile->getString();
367 sys::path::replace_extension(Filename, NewStem);
368 return Filename.str();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000369 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000370 }
371 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000372
Bill Wendling6e5190c2012-08-30 00:34:21 +0000373 SmallString<128> Filename = CU.getFilename();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000374 sys::path::replace_extension(Filename, NewStem);
Bill Wendling6e5190c2012-08-30 00:34:21 +0000375 return sys::path::filename(Filename.str());
Nick Lewycky269687f2011-05-04 04:03:04 +0000376}
377
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000378bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000379 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000380 Ctx = &M.getContext();
381
Nick Lewyckya204ef32013-03-14 05:13:26 +0000382 if (Options.EmitNotes) emitProfileNotes();
383 if (Options.EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000384 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000385}
386
Nick Lewycky64a0a332013-03-13 22:55:42 +0000387void GCOVProfiler::emitProfileNotes() {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000388 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewyckybba40db2011-11-27 23:22:20 +0000389 if (!CU_Nodes) return;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000390
Nick Lewyckybba40db2011-11-27 23:22:20 +0000391 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
392 // Each compile unit gets its own .gcno file. This means that whether we run
393 // this pass over the original .o's as they're produced, or run it after
394 // LTO, we'll generate the same .gcno files.
395
396 DICompileUnit CU(CU_Nodes->getOperand(i));
397 std::string ErrorInfo;
398 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
399 raw_fd_ostream::F_Binary);
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000400 out.write("oncg", 4);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000401 out.write(ReversedVersion, 4);
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000402 out.write("MVLL", 4);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000403
404 DIArray SPs = CU.getSubprograms();
405 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
406 DISubprogram SP(SPs.getElement(i));
407 if (!SP.Verify()) continue;
408
409 Function *F = SP.getFunction();
410 if (!F) continue;
Nick Lewyckya204ef32013-03-14 05:13:26 +0000411 GCOVFunction Func(SP, &out, i, Options.UseCfgChecksum);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000412
413 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
414 GCOVBlock &Block = Func.getBlock(BB);
415 TerminatorInst *TI = BB->getTerminator();
416 if (int successors = TI->getNumSuccessors()) {
417 for (int i = 0; i != successors; ++i) {
418 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
419 }
420 } else if (isa<ReturnInst>(TI)) {
421 Block.addEdge(Func.getReturnBlock());
422 }
423
424 uint32_t Line = 0;
425 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
426 I != IE; ++I) {
427 const DebugLoc &Loc = I->getDebugLoc();
428 if (Loc.isUnknown()) continue;
429 if (Line == Loc.getLine()) continue;
430 Line = Loc.getLine();
431 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
432
433 GCOVLines &Lines = Block.getFile(SP.getFilename());
434 Lines.addLine(Loc.getLine());
435 }
436 }
437 Func.writeOut();
438 }
439 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
440 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000441 }
442}
443
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000444bool GCOVProfiler::emitProfileArcs() {
445 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
446 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000447
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000448 bool Result = false;
Bill Wendling77b19132012-05-28 06:10:56 +0000449 bool InsertIndCounterIncrCode = false;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000450 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
451 DICompileUnit CU(CU_Nodes->getOperand(i));
452 DIArray SPs = CU.getSubprograms();
453 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
454 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
455 DISubprogram SP(SPs.getElement(i));
456 if (!SP.Verify()) continue;
457 Function *F = SP.getFunction();
458 if (!F) continue;
459 if (!Result) Result = true;
460 unsigned Edges = 0;
461 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
462 TerminatorInst *TI = BB->getTerminator();
463 if (isa<ReturnInst>(TI))
464 ++Edges;
465 else
466 Edges += TI->getNumSuccessors();
467 }
468
469 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000470 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000471 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000472 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000473 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000474 Constant::getNullValue(CounterTy),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000475 "__llvm_gcov_ctr");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000476 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
477
478 UniqueVector<BasicBlock *> ComplexEdgePreds;
479 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
480
481 unsigned Edge = 0;
482 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
483 TerminatorInst *TI = BB->getTerminator();
484 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
485 if (Successors) {
486 IRBuilder<> Builder(TI);
487
488 if (Successors == 1) {
489 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
490 Edge);
491 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000492 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000493 Builder.CreateStore(Count, Counter);
494 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000495 Value *Sel = Builder.CreateSelect(BI->getCondition(),
496 Builder.getInt64(Edge),
497 Builder.getInt64(Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000498 SmallVector<Value *, 2> Idx;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000499 Idx.push_back(Builder.getInt64(0));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000500 Idx.push_back(Sel);
501 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
502 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000503 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000504 Builder.CreateStore(Count, Counter);
505 } else {
506 ComplexEdgePreds.insert(BB);
507 for (int i = 0; i != Successors; ++i)
508 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
509 }
510 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000511 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000512 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000513
514 if (!ComplexEdgePreds.empty()) {
515 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000516 buildEdgeLookupTable(F, Counters,
517 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000518 GlobalVariable *EdgeState = getEdgeStateValue();
519
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000520 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
521 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000522 Builder.CreateStore(Builder.getInt32(i), EdgeState);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000523 }
524 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
525 // call runtime to perform increment
Bill Wendling77b19132012-05-28 06:10:56 +0000526 BasicBlock::iterator InsertPt =
527 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000528 IRBuilder<> Builder(InsertPt);
529 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000530 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
531 i * ComplexEdgePreds.size());
Bill Wendlingc7a88402012-05-25 23:55:00 +0000532
533 // Build code to increment the counter.
Bill Wendling77b19132012-05-28 06:10:56 +0000534 InsertIndCounterIncrCode = true;
535 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
536 EdgeState, CounterPtrArray);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000537 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000538 }
539 }
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000540
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000541 insertCounterWriteout(CountersBySP);
Bill Wendling253353c2012-09-13 00:09:55 +0000542 insertFlush(CountersBySP);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000543 }
Bill Wendling77b19132012-05-28 06:10:56 +0000544
545 if (InsertIndCounterIncrCode)
546 insertIndirectCounterIncrement();
547
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000548 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000549}
550
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000551// All edges with successors that aren't branches are "complex", because it
552// requires complex logic to pick which counter to update.
553GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
554 Function *F,
555 GlobalVariable *Counters,
556 const UniqueVector<BasicBlock *> &Preds,
557 const UniqueVector<BasicBlock *> &Succs) {
558 // TODO: support invoke, threads. We rely on the fact that nothing can modify
559 // the whole-Module pred edge# between the time we set it and the time we next
560 // read it. Threads and invoke make this untrue.
561
562 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000563 size_t TableSize = Succs.size() * Preds.size();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000564 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000565 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000566
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000567 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000568 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000569 for (size_t i = 0; i != TableSize; ++i)
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000570 EdgeTable[i] = NullValue;
571
572 unsigned Edge = 0;
573 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
574 TerminatorInst *TI = BB->getTerminator();
575 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000576 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000577 for (int i = 0; i != Successors; ++i) {
578 BasicBlock *Succ = TI->getSuccessor(i);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000579 IRBuilder<> Builder(Succ);
580 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000581 Edge + i);
582 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
583 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
584 }
585 }
586 Edge += Successors;
587 }
588
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000589 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000590 GlobalVariable *EdgeTableGV =
591 new GlobalVariable(
592 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000593 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000594 "__llvm_gcda_edge_table");
595 EdgeTableGV->setUnnamedAddr(true);
596 return EdgeTableGV;
597}
598
Nick Lewyckyb1928702011-04-16 01:20:23 +0000599Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000600 Type *Args[] = {
601 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
602 Type::getInt8PtrTy(*Ctx), // const char version[4]
603 };
604 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000605 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
606}
607
Bill Wendling77b19132012-05-28 06:10:56 +0000608Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
609 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendlingc7a88402012-05-25 23:55:00 +0000610 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling77b19132012-05-28 06:10:56 +0000611 Type *Args[] = {
Micah Villmowb8bce922012-10-24 17:25:11 +0000612 Int32Ty->getPointerTo(), // uint32_t *predecessor
613 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling77b19132012-05-28 06:10:56 +0000614 };
615 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
616 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000617}
618
619Constant *GCOVProfiler::getEmitFunctionFunc() {
Nick Lewycky17d2f772013-03-09 01:33:06 +0000620 Type *Args[3] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000621 Type::getInt32Ty(*Ctx), // uint32_t ident
622 Type::getInt8PtrTy(*Ctx), // const char *function_name
Nick Lewycky17d2f772013-03-09 01:33:06 +0000623 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Nick Lewycky5409a182011-05-05 02:46:38 +0000624 };
Bill Wendlingc7a88402012-05-25 23:55:00 +0000625 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000626 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000627}
628
629Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000630 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000631 Type::getInt32Ty(*Ctx), // uint32_t num_counters
632 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
633 };
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000634 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000635 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000636}
637
638Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000639 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000640 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000641}
642
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000643GlobalVariable *GCOVProfiler::getEdgeStateValue() {
644 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
645 if (!GV) {
646 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
647 GlobalValue::InternalLinkage,
648 ConstantInt::get(Type::getInt32Ty(*Ctx),
649 0xffffffff),
650 "__llvm_gcov_global_state_pred");
651 GV->setUnnamedAddr(true);
652 }
653 return GV;
654}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000655
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000656void GCOVProfiler::insertCounterWriteout(
Bill Wendling21b742f2012-08-29 18:45:41 +0000657 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling253353c2012-09-13 00:09:55 +0000658 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
659 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
660 if (!WriteoutF)
661 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
662 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000663 WriteoutF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000664 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000665 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000666 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000667
668 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000669 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000670
671 Constant *StartFile = getStartFileFunc();
672 Constant *EmitFunction = getEmitFunctionFunc();
673 Constant *EmitArcs = getEmitArcsFunc();
674 Constant *EndFile = getEndFileFunc();
675
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000676 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
677 if (CU_Nodes) {
678 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Bill Wendling032dbee2012-09-13 14:32:30 +0000679 DICompileUnit CU(CU_Nodes->getOperand(i));
680 std::string FilenameGcda = mangleName(CU, "gcda");
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000681 Builder.CreateCall2(StartFile,
682 Builder.CreateGlobalStringPtr(FilenameGcda),
Nick Lewyckya204ef32013-03-14 05:13:26 +0000683 Builder.CreateGlobalStringPtr(ReversedVersion));
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000684 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
685 DISubprogram SP(CountersBySP[j].second);
Nick Lewycky17d2f772013-03-09 01:33:06 +0000686 Builder.CreateCall3(EmitFunction,
Nick Lewycky60d16a22013-03-09 10:13:26 +0000687 Builder.getInt32(j),
Nick Lewyckya204ef32013-03-14 05:13:26 +0000688 Options.FunctionNamesInData ?
689 Builder.CreateGlobalStringPtr(SP.getName()) :
690 Constant::getNullValue(Builder.getInt8PtrTy()),
691 Builder.getInt8(Options.UseCfgChecksum));
Nick Lewycky17d2f772013-03-09 01:33:06 +0000692
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000693 GlobalVariable *GV = CountersBySP[j].first;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000694 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000695 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000696 Builder.CreateCall2(EmitArcs,
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000697 Builder.getInt32(Arcs),
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000698 Builder.CreateConstGEP2_64(GV, 0, 0));
699 }
700 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000701 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000702 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000703 Builder.CreateRetVoid();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000704
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000705 // Create a small bit of code that registers the "__llvm_gcov_writeout"
706 // function to be executed at exit.
707 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
708 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
709 "__llvm_gcov_init", M);
710 F->setUnnamedAddr(true);
711 F->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling034b94b2012-12-19 07:18:57 +0000712 F->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000713 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000714 F->addFnAttr(Attribute::NoRedZone);
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000715
716 BB = BasicBlock::Create(*Ctx, "entry", F);
717 Builder.SetInsertPoint(BB);
718
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000719 FTy = FunctionType::get(Builder.getInt32Ty(),
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000720 PointerType::get(FTy, 0), false);
Bill Wendlingc1b6ea72012-06-30 20:21:19 +0000721 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000722 Builder.CreateCall(AtExitFn, WriteoutF);
723 Builder.CreateRetVoid();
724
725 appendToGlobalCtors(*M, F, 0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000726}
Bill Wendling77b19132012-05-28 06:10:56 +0000727
728void GCOVProfiler::insertIndirectCounterIncrement() {
729 Function *Fn =
730 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
731 Fn->setUnnamedAddr(true);
732 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling034b94b2012-12-19 07:18:57 +0000733 Fn->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000734 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000735 Fn->addFnAttr(Attribute::NoRedZone);
Bill Wendling77b19132012-05-28 06:10:56 +0000736
Bill Wendling77b19132012-05-28 06:10:56 +0000737 // Create basic blocks for function.
738 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
739 IRBuilder<> Builder(BB);
740
741 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
742 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
743 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
744
745 // uint32_t pred = *predecessor;
746 // if (pred == 0xffffffff) return;
747 Argument *Arg = Fn->arg_begin();
748 Arg->setName("predecessor");
749 Value *Pred = Builder.CreateLoad(Arg, "pred");
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000750 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
Bill Wendling77b19132012-05-28 06:10:56 +0000751 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
752
753 Builder.SetInsertPoint(PredNotNegOne);
754
755 // uint64_t *counter = counters[pred];
756 // if (!counter) return;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000757 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
Bill Wendling77b19132012-05-28 06:10:56 +0000758 Arg = llvm::next(Fn->arg_begin());
759 Arg->setName("counters");
760 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
761 Value *Counter = Builder.CreateLoad(GEP, "counter");
Nick Lewycky58591b12013-02-27 06:21:30 +0000762 Cond = Builder.CreateICmpEQ(Counter,
763 Constant::getNullValue(
764 Builder.getInt64Ty()->getPointerTo()));
Bill Wendling77b19132012-05-28 06:10:56 +0000765 Builder.CreateCondBr(Cond, Exit, CounterEnd);
766
767 // ++*counter;
768 Builder.SetInsertPoint(CounterEnd);
769 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000770 Builder.getInt64(1));
Bill Wendling77b19132012-05-28 06:10:56 +0000771 Builder.CreateStore(Add, Counter);
772 Builder.CreateBr(Exit);
773
774 // Fill in the exit block.
775 Builder.SetInsertPoint(Exit);
776 Builder.CreateRetVoid();
777}
Bill Wendling253353c2012-09-13 00:09:55 +0000778
779void GCOVProfiler::
780insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
781 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendling78fff8e2012-09-17 17:57:05 +0000782 Function *FlushF = M->getFunction("__gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000783 if (!FlushF)
784 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendling78fff8e2012-09-17 17:57:05 +0000785 "__gcov_flush", M);
Bill Wendling253353c2012-09-13 00:09:55 +0000786 else
787 FlushF->setLinkage(GlobalValue::InternalLinkage);
788 FlushF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000789 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000790 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000791 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000792
Bill Wendling253353c2012-09-13 00:09:55 +0000793 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
794
795 // Write out the current counters.
796 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
797 assert(WriteoutF && "Need to create the writeout function first!");
798
799 IRBuilder<> Builder(Entry);
800 Builder.CreateCall(WriteoutF);
801
Bill Wendling032dbee2012-09-13 14:32:30 +0000802 // Zero out the counters.
803 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
804 I = CountersBySP.begin(), E = CountersBySP.end();
805 I != E; ++I) {
806 GlobalVariable *GV = I->first;
807 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
Bill Wendlingec3fc2e2012-09-14 22:35:49 +0000808 Builder.CreateStore(Null, GV);
Bill Wendling032dbee2012-09-13 14:32:30 +0000809 }
Bill Wendling253353c2012-09-13 00:09:55 +0000810
811 Type *RetTy = FlushF->getReturnType();
812 if (RetTy == Type::getVoidTy(*Ctx))
813 Builder.CreateRetVoid();
814 else if (RetTy->isIntegerTy())
Bill Wendling78fff8e2012-09-17 17:57:05 +0000815 // Used if __gcov_flush was implicitly declared.
Bill Wendling253353c2012-09-13 00:09:55 +0000816 Builder.CreateRet(ConstantInt::get(RetTy, 0));
817 else
Bill Wendling78fff8e2012-09-17 17:57:05 +0000818 report_fatal_error("invalid return type for __gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000819}