blob: 0ad44d55a059fe5e35dfc4958c369eb3c7e24e2b [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"
Bill Wendling39c41c32013-03-26 22:47:50 +000035#include "llvm/Support/FileSystem.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000036#include "llvm/Support/InstIterator.h"
37#include "llvm/Support/PathV2.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000040#include <string>
41#include <utility>
42using namespace llvm;
43
Nick Lewyckya204ef32013-03-14 05:13:26 +000044static cl::opt<std::string>
45DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
46 cl::ValueRequired);
47
48GCOVOptions GCOVOptions::getDefault() {
49 GCOVOptions Options;
50 Options.EmitNotes = true;
51 Options.EmitData = true;
52 Options.UseCfgChecksum = false;
53 Options.NoRedZone = false;
54 Options.FunctionNamesInData = true;
55
56 if (DefaultGCOVVersion.size() != 4) {
57 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
58 DefaultGCOVVersion);
59 }
60 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
61 return Options;
62}
63
Nick Lewyckyb1928702011-04-16 01:20:23 +000064namespace {
65 class GCOVProfiler : public ModulePass {
Nick Lewyckyb1928702011-04-16 01:20:23 +000066 public:
67 static char ID;
Nick Lewyckya204ef32013-03-14 05:13:26 +000068 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
69 ReversedVersion[0] = Options.Version[3];
70 ReversedVersion[1] = Options.Version[2];
71 ReversedVersion[2] = Options.Version[1];
72 ReversedVersion[3] = Options.Version[0];
73 ReversedVersion[4] = '\0';
Nick Lewyckya61e52c2011-04-21 01:56:25 +000074 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
75 }
Nick Lewyckya204ef32013-03-14 05:13:26 +000076 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
77 assert((Options.EmitNotes || Options.EmitData) &&
78 "GCOVProfiler asked to do nothing?");
79 ReversedVersion[0] = Options.Version[3];
80 ReversedVersion[1] = Options.Version[2];
81 ReversedVersion[2] = Options.Version[1];
82 ReversedVersion[3] = Options.Version[0];
83 ReversedVersion[4] = '\0';
Nick Lewyckyb1928702011-04-16 01:20:23 +000084 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
85 }
86 virtual const char *getPassName() const {
87 return "GCOV Profiler";
88 }
Nick Lewyckya204ef32013-03-14 05:13:26 +000089
Nick Lewyckyb1928702011-04-16 01:20:23 +000090 private:
Nick Lewycky269687f2011-05-04 04:03:04 +000091 bool runOnModule(Module &M);
92
Nick Lewycky64a0a332013-03-13 22:55:42 +000093 // Create the .gcno files for the Module based on DebugInfo.
94 void emitProfileNotes();
Nick Lewyckyb1928702011-04-16 01:20:23 +000095
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000096 // Modify the program to track transitions along edges and call into the
97 // profiling runtime to emit .gcda files when run.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000098 bool emitProfileArcs();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000099
Nick Lewyckyb1928702011-04-16 01:20:23 +0000100 // Get pointers to the functions in the runtime library.
101 Constant *getStartFileFunc();
Bill Wendling77b19132012-05-28 06:10:56 +0000102 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000103 Constant *getEmitFunctionFunc();
104 Constant *getEmitArcsFunc();
Bill Wendling18764712013-03-19 21:03:22 +0000105 Constant *getDeleteWriteoutFunctionListFunc();
Bill Wendlingd195eb62013-03-18 23:04:39 +0000106 Constant *getDeleteFlushFunctionListFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000107 Constant *getEndFileFunc();
108
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000109 // Create or retrieve an i32 state value that is used to represent the
110 // pred block number for certain non-trivial edges.
111 GlobalVariable *getEdgeStateValue();
112
113 // Produce a table of pointers to counters, by predecessor and successor
114 // block number.
115 GlobalVariable *buildEdgeLookupTable(Function *F,
116 GlobalVariable *Counter,
Nick Lewycky64a0a332013-03-13 22:55:42 +0000117 const UniqueVector<BasicBlock *>&Preds,
118 const UniqueVector<BasicBlock*>&Succs);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000119
Nick Lewyckyb1928702011-04-16 01:20:23 +0000120 // Add the function to write out all our counters to the global destructor
121 // list.
Bill Wendlingd195eb62013-03-18 23:04:39 +0000122 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
123 MDNode*> >);
124 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Bill Wendling77b19132012-05-28 06:10:56 +0000125 void insertIndirectCounterIncrement();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000126
Bill Wendling39c41c32013-03-26 22:47:50 +0000127 std::string mangleName(DICompileUnit CU, const char *NewStem,
128 bool FullPath);
Nick Lewycky269687f2011-05-04 04:03:04 +0000129
Nick Lewyckya204ef32013-03-14 05:13:26 +0000130 GCOVOptions Options;
131
132 // Reversed, NUL-terminated copy of Options.Version.
133 char ReversedVersion[5];
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000134
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000135 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000136 LLVMContext *Ctx;
137 };
138}
139
140char GCOVProfiler::ID = 0;
141INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
142 "Insert instrumentation for GCOV profiling", false, false)
143
Nick Lewyckya204ef32013-03-14 05:13:26 +0000144ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
145 return new GCOVProfiler(Options);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000146}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000147
Nick Lewycky5d22d022013-03-19 01:37:55 +0000148static std::string getFunctionName(DISubprogram SP) {
149 if (!SP.getLinkageName().empty())
150 return SP.getLinkageName();
151 return SP.getName();
152}
153
Nick Lewyckyb1928702011-04-16 01:20:23 +0000154namespace {
155 class GCOVRecord {
156 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000157 static const char *LinesTag;
158 static const char *FunctionTag;
159 static const char *BlockTag;
160 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000161
162 GCOVRecord() {}
163
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000164 void writeBytes(const char *Bytes, int Size) {
165 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000166 }
167
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000168 void write(uint32_t i) {
169 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000170 }
171
172 // Returns the length measured in 4-byte blocks that will be used to
173 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000174 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000175 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000176 // padding out to the next 4-byte word. The length is measured in 4-byte
177 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000178 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000179 }
180
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000181 void writeGCOVString(StringRef s) {
182 uint32_t Len = lengthOfGCOVString(s);
183 write(Len);
184 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000185
186 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000187 assert((unsigned)(4 - (s.size() % 4)) > 0);
188 assert((unsigned)(4 - (s.size() % 4)) <= 4);
189 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000190 }
191
192 raw_ostream *os;
193 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000194 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
195 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
196 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
197 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000198
199 class GCOVFunction;
200 class GCOVBlock;
201
202 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Patel16c19a12011-09-20 18:35:00 +0000203 // list of line numbers and a single filename, representing lines that belong
204 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000205 class GCOVLines : public GCOVRecord {
206 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000207 void addLine(uint32_t Line) {
208 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000209 }
210
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000211 uint32_t length() {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000212 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000213 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000214 }
215
Devang Patel16c19a12011-09-20 18:35:00 +0000216 void writeOut() {
217 write(0);
218 writeGCOVString(Filename);
219 for (int i = 0, e = Lines.size(); i != e; ++i)
220 write(Lines[i]);
221 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000222
Devang Patel16c19a12011-09-20 18:35:00 +0000223 GCOVLines(StringRef F, raw_ostream *os)
224 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000225 this->os = os;
226 }
227
Devang Patel680018f2011-09-20 18:48:56 +0000228 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000229 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000230 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000231 };
232
233 // Represent a basic block in GCOV. Each block has a unique number in the
234 // function, number of lines belonging to each block, and a set of edges to
235 // other blocks.
236 class GCOVBlock : public GCOVRecord {
237 public:
Devang Patel68155d32011-09-20 17:55:19 +0000238 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000239 GCOVLines *&Lines = LinesByFile[Filename];
240 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000241 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000242 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000243 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000244 }
245
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000246 void addEdge(GCOVBlock &Successor) {
247 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000248 }
249
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000250 void writeOut() {
251 uint32_t Len = 3;
252 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
253 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000254 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000255 }
256
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000257 writeBytes(LinesTag, 4);
258 write(Len);
259 write(Number);
260 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
Devang Patel16c19a12011-09-20 18:35:00 +0000261 E = LinesByFile.end(); I != E; ++I)
262 I->second->writeOut();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000263 write(0);
264 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000265 }
266
267 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000268 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000269 }
270
271 private:
272 friend class GCOVFunction;
273
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000274 GCOVBlock(uint32_t Number, raw_ostream *os)
275 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000276 this->os = os;
277 }
278
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000279 uint32_t Number;
280 StringMap<GCOVLines *> LinesByFile;
281 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000282 };
283
284 // A function has a unique identifier, a checksum (we leave as zero) and a
285 // set of blocks and a map of edges between blocks. This is the only GCOV
286 // object users can construct, the blocks and lines will be rooted here.
287 class GCOVFunction : public GCOVRecord {
288 public:
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000289 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
Nick Lewyckya204ef32013-03-14 05:13:26 +0000290 bool UseCfgChecksum) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000291 this->os = os;
292
293 Function *F = SP.getFunction();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000294 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000295 uint32_t i = 0;
296 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000297 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000298 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000299 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000300
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000301 writeBytes(FunctionTag, 4);
Nick Lewycky5d22d022013-03-19 01:37:55 +0000302 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000303 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Nick Lewyckya204ef32013-03-14 05:13:26 +0000304 if (UseCfgChecksum)
Nick Lewyckybba40db2011-11-27 23:22:20 +0000305 ++BlockLen;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000306 write(BlockLen);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000307 write(Ident);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000308 write(0); // lineno checksum
Nick Lewyckya204ef32013-03-14 05:13:26 +0000309 if (UseCfgChecksum)
Nick Lewyckybba40db2011-11-27 23:22:20 +0000310 write(0); // cfg checksum
Nick Lewycky5d22d022013-03-19 01:37:55 +0000311 writeGCOVString(getFunctionName(SP));
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000312 writeGCOVString(SP.getFilename());
313 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000314 }
315
316 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000317 DeleteContainerSeconds(Blocks);
318 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000319 }
320
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000321 GCOVBlock &getBlock(BasicBlock *BB) {
322 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000323 }
324
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000325 GCOVBlock &getReturnBlock() {
326 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000327 }
328
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000329 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000330 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000331 writeBytes(BlockTag, 4);
332 write(Blocks.size() + 1);
333 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
334 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000335 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000336 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000337
338 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000339 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
340 E = Blocks.end(); I != E; ++I) {
341 GCOVBlock &Block = *I->second;
342 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000343
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000344 writeBytes(EdgeTag, 4);
345 write(Block.OutEdges.size() * 2 + 1);
346 write(Block.Number);
347 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000348 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
349 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000350 write(Block.OutEdges[i]->Number);
351 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000352 }
353 }
354
355 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000356 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
357 E = Blocks.end(); I != E; ++I) {
358 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000359 }
360 }
361
362 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000363 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
364 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000365 };
366}
367
Bill Wendling39c41c32013-03-26 22:47:50 +0000368std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem,
369 bool FullPath) {
Nick Lewycky269687f2011-05-04 04:03:04 +0000370 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
371 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
372 MDNode *N = GCov->getOperand(i);
373 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000374 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000375 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000376 if (!GCovFile || !CompileUnit) continue;
377 if (CompileUnit == CU) {
Bill Wendling6e5190c2012-08-30 00:34:21 +0000378 SmallString<128> Filename = GCovFile->getString();
379 sys::path::replace_extension(Filename, NewStem);
380 return Filename.str();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000381 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000382 }
383 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000384
Bill Wendling6e5190c2012-08-30 00:34:21 +0000385 SmallString<128> Filename = CU.getFilename();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000386 sys::path::replace_extension(Filename, NewStem);
Bill Wendling39c41c32013-03-26 22:47:50 +0000387 StringRef FName = sys::path::filename(Filename);
388 if (!FullPath)
389 return FName;
390 SmallString<128> CurPath;
391 if (sys::fs::current_path(CurPath)) return FName;
392 sys::path::append(CurPath, FName.str());
393 return CurPath.str();
Nick Lewycky269687f2011-05-04 04:03:04 +0000394}
395
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000396bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000397 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000398 Ctx = &M.getContext();
399
Nick Lewyckya204ef32013-03-14 05:13:26 +0000400 if (Options.EmitNotes) emitProfileNotes();
401 if (Options.EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000402 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000403}
404
Nick Lewycky64a0a332013-03-13 22:55:42 +0000405void GCOVProfiler::emitProfileNotes() {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000406 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewyckybba40db2011-11-27 23:22:20 +0000407 if (!CU_Nodes) return;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000408
Nick Lewyckybba40db2011-11-27 23:22:20 +0000409 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
410 // Each compile unit gets its own .gcno file. This means that whether we run
411 // this pass over the original .o's as they're produced, or run it after
412 // LTO, we'll generate the same .gcno files.
413
414 DICompileUnit CU(CU_Nodes->getOperand(i));
415 std::string ErrorInfo;
Bill Wendling39c41c32013-03-26 22:47:50 +0000416 raw_fd_ostream out(mangleName(CU, "gcno", false).c_str(), ErrorInfo,
Nick Lewyckybba40db2011-11-27 23:22:20 +0000417 raw_fd_ostream::F_Binary);
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000418 out.write("oncg", 4);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000419 out.write(ReversedVersion, 4);
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000420 out.write("MVLL", 4);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000421
422 DIArray SPs = CU.getSubprograms();
423 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
424 DISubprogram SP(SPs.getElement(i));
425 if (!SP.Verify()) continue;
426
427 Function *F = SP.getFunction();
428 if (!F) continue;
Nick Lewyckya204ef32013-03-14 05:13:26 +0000429 GCOVFunction Func(SP, &out, i, Options.UseCfgChecksum);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000430
431 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
432 GCOVBlock &Block = Func.getBlock(BB);
433 TerminatorInst *TI = BB->getTerminator();
434 if (int successors = TI->getNumSuccessors()) {
435 for (int i = 0; i != successors; ++i) {
436 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
437 }
438 } else if (isa<ReturnInst>(TI)) {
439 Block.addEdge(Func.getReturnBlock());
440 }
441
442 uint32_t Line = 0;
443 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
444 I != IE; ++I) {
445 const DebugLoc &Loc = I->getDebugLoc();
446 if (Loc.isUnknown()) continue;
447 if (Line == Loc.getLine()) continue;
448 Line = Loc.getLine();
449 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
450
451 GCOVLines &Lines = Block.getFile(SP.getFilename());
452 Lines.addLine(Loc.getLine());
453 }
454 }
455 Func.writeOut();
456 }
457 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
458 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000459 }
460}
461
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000462bool GCOVProfiler::emitProfileArcs() {
463 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
464 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000465
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000466 bool Result = false;
Bill Wendling77b19132012-05-28 06:10:56 +0000467 bool InsertIndCounterIncrCode = false;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000468 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
469 DICompileUnit CU(CU_Nodes->getOperand(i));
470 DIArray SPs = CU.getSubprograms();
471 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
472 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
473 DISubprogram SP(SPs.getElement(i));
474 if (!SP.Verify()) continue;
475 Function *F = SP.getFunction();
476 if (!F) continue;
477 if (!Result) Result = true;
478 unsigned Edges = 0;
479 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
480 TerminatorInst *TI = BB->getTerminator();
481 if (isa<ReturnInst>(TI))
482 ++Edges;
483 else
484 Edges += TI->getNumSuccessors();
485 }
486
487 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000488 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000489 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000490 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000491 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000492 Constant::getNullValue(CounterTy),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000493 "__llvm_gcov_ctr");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000494 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
495
496 UniqueVector<BasicBlock *> ComplexEdgePreds;
497 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
498
499 unsigned Edge = 0;
500 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
501 TerminatorInst *TI = BB->getTerminator();
502 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
503 if (Successors) {
504 IRBuilder<> Builder(TI);
505
506 if (Successors == 1) {
507 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
508 Edge);
509 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000510 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000511 Builder.CreateStore(Count, Counter);
512 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000513 Value *Sel = Builder.CreateSelect(BI->getCondition(),
514 Builder.getInt64(Edge),
515 Builder.getInt64(Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000516 SmallVector<Value *, 2> Idx;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000517 Idx.push_back(Builder.getInt64(0));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000518 Idx.push_back(Sel);
519 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
520 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000521 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000522 Builder.CreateStore(Count, Counter);
523 } else {
524 ComplexEdgePreds.insert(BB);
525 for (int i = 0; i != Successors; ++i)
526 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
527 }
528 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000529 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000530 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000531
532 if (!ComplexEdgePreds.empty()) {
533 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000534 buildEdgeLookupTable(F, Counters,
535 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000536 GlobalVariable *EdgeState = getEdgeStateValue();
537
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000538 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
539 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000540 Builder.CreateStore(Builder.getInt32(i), EdgeState);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000541 }
542 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
543 // call runtime to perform increment
Bill Wendling77b19132012-05-28 06:10:56 +0000544 BasicBlock::iterator InsertPt =
545 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000546 IRBuilder<> Builder(InsertPt);
547 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000548 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
549 i * ComplexEdgePreds.size());
Bill Wendlingc7a88402012-05-25 23:55:00 +0000550
551 // Build code to increment the counter.
Bill Wendling77b19132012-05-28 06:10:56 +0000552 InsertIndCounterIncrCode = true;
553 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
554 EdgeState, CounterPtrArray);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000555 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000556 }
557 }
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000558
Bill Wendlingd195eb62013-03-18 23:04:39 +0000559 Function *WriteoutF = insertCounterWriteout(CountersBySP);
560 Function *FlushF = insertFlush(CountersBySP);
561
562 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
Bill Wendling18764712013-03-19 21:03:22 +0000563 // be executed at exit and the "__llvm_gcov_flush" function to be executed
564 // when "__gcov_flush" is called.
Bill Wendlingd195eb62013-03-18 23:04:39 +0000565 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
566 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
567 "__llvm_gcov_init", M);
568 F->setUnnamedAddr(true);
569 F->setLinkage(GlobalValue::InternalLinkage);
570 F->addFnAttr(Attribute::NoInline);
571 if (Options.NoRedZone)
572 F->addFnAttr(Attribute::NoRedZone);
573
574 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
575 IRBuilder<> Builder(BB);
576
Bill Wendlingd195eb62013-03-18 23:04:39 +0000577 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendling8640c6a2013-03-20 21:13:59 +0000578 Type *Params[] = {
579 PointerType::get(FTy, 0),
580 PointerType::get(FTy, 0)
581 };
582 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
Bill Wendling18764712013-03-19 21:03:22 +0000583
Bill Wendling8640c6a2013-03-20 21:13:59 +0000584 // Inialize the environment and register the local writeout and flush
585 // functions.
586 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
587 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
Bill Wendlingd195eb62013-03-18 23:04:39 +0000588 Builder.CreateRetVoid();
589
590 appendToGlobalCtors(*M, F, 0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000591 }
Bill Wendling77b19132012-05-28 06:10:56 +0000592
593 if (InsertIndCounterIncrCode)
594 insertIndirectCounterIncrement();
595
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000596 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000597}
598
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000599// All edges with successors that aren't branches are "complex", because it
600// requires complex logic to pick which counter to update.
601GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
602 Function *F,
603 GlobalVariable *Counters,
604 const UniqueVector<BasicBlock *> &Preds,
605 const UniqueVector<BasicBlock *> &Succs) {
606 // TODO: support invoke, threads. We rely on the fact that nothing can modify
607 // the whole-Module pred edge# between the time we set it and the time we next
608 // read it. Threads and invoke make this untrue.
609
610 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000611 size_t TableSize = Succs.size() * Preds.size();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000612 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000613 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000614
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000615 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000616 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000617 for (size_t i = 0; i != TableSize; ++i)
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000618 EdgeTable[i] = NullValue;
619
620 unsigned Edge = 0;
621 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
622 TerminatorInst *TI = BB->getTerminator();
623 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000624 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000625 for (int i = 0; i != Successors; ++i) {
626 BasicBlock *Succ = TI->getSuccessor(i);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000627 IRBuilder<> Builder(Succ);
628 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000629 Edge + i);
630 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
631 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
632 }
633 }
634 Edge += Successors;
635 }
636
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000637 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000638 GlobalVariable *EdgeTableGV =
639 new GlobalVariable(
640 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000641 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000642 "__llvm_gcda_edge_table");
643 EdgeTableGV->setUnnamedAddr(true);
644 return EdgeTableGV;
645}
646
Nick Lewyckyb1928702011-04-16 01:20:23 +0000647Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000648 Type *Args[] = {
649 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
650 Type::getInt8PtrTy(*Ctx), // const char version[4]
651 };
652 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000653 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
654}
655
Bill Wendling77b19132012-05-28 06:10:56 +0000656Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
657 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendlingc7a88402012-05-25 23:55:00 +0000658 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling77b19132012-05-28 06:10:56 +0000659 Type *Args[] = {
Micah Villmowb8bce922012-10-24 17:25:11 +0000660 Int32Ty->getPointerTo(), // uint32_t *predecessor
661 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling77b19132012-05-28 06:10:56 +0000662 };
663 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
664 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000665}
666
667Constant *GCOVProfiler::getEmitFunctionFunc() {
Nick Lewycky17d2f772013-03-09 01:33:06 +0000668 Type *Args[3] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000669 Type::getInt32Ty(*Ctx), // uint32_t ident
670 Type::getInt8PtrTy(*Ctx), // const char *function_name
Nick Lewycky17d2f772013-03-09 01:33:06 +0000671 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Nick Lewycky5409a182011-05-05 02:46:38 +0000672 };
Bill Wendlingc7a88402012-05-25 23:55:00 +0000673 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000674 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000675}
676
677Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000678 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000679 Type::getInt32Ty(*Ctx), // uint32_t num_counters
680 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
681 };
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000682 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000683 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000684}
685
Bill Wendling18764712013-03-19 21:03:22 +0000686Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
687 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
688 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
689}
690
Bill Wendlingd195eb62013-03-18 23:04:39 +0000691Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
692 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
693 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
694}
695
Nick Lewyckyb1928702011-04-16 01:20:23 +0000696Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000697 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000698 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000699}
700
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000701GlobalVariable *GCOVProfiler::getEdgeStateValue() {
702 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
703 if (!GV) {
704 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
705 GlobalValue::InternalLinkage,
706 ConstantInt::get(Type::getInt32Ty(*Ctx),
707 0xffffffff),
708 "__llvm_gcov_global_state_pred");
709 GV->setUnnamedAddr(true);
710 }
711 return GV;
712}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000713
Bill Wendlingd195eb62013-03-18 23:04:39 +0000714Function *GCOVProfiler::insertCounterWriteout(
Bill Wendling21b742f2012-08-29 18:45:41 +0000715 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling253353c2012-09-13 00:09:55 +0000716 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
717 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
718 if (!WriteoutF)
719 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
720 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000721 WriteoutF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000722 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000723 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000724 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000725
726 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000727 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000728
729 Constant *StartFile = getStartFileFunc();
730 Constant *EmitFunction = getEmitFunctionFunc();
731 Constant *EmitArcs = getEmitArcsFunc();
732 Constant *EndFile = getEndFileFunc();
733
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000734 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
735 if (CU_Nodes) {
736 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Bill Wendling032dbee2012-09-13 14:32:30 +0000737 DICompileUnit CU(CU_Nodes->getOperand(i));
Bill Wendling39c41c32013-03-26 22:47:50 +0000738 std::string FilenameGcda = mangleName(CU, "gcda", true);
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000739 Builder.CreateCall2(StartFile,
740 Builder.CreateGlobalStringPtr(FilenameGcda),
Nick Lewyckya204ef32013-03-14 05:13:26 +0000741 Builder.CreateGlobalStringPtr(ReversedVersion));
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000742 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
743 DISubprogram SP(CountersBySP[j].second);
Nick Lewycky5d22d022013-03-19 01:37:55 +0000744 Builder.CreateCall3(
745 EmitFunction, Builder.getInt32(j),
746 Options.FunctionNamesInData ?
747 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
748 Constant::getNullValue(Builder.getInt8PtrTy()),
749 Builder.getInt8(Options.UseCfgChecksum));
Nick Lewycky17d2f772013-03-09 01:33:06 +0000750
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000751 GlobalVariable *GV = CountersBySP[j].first;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000752 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000753 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000754 Builder.CreateCall2(EmitArcs,
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000755 Builder.getInt32(Arcs),
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000756 Builder.CreateConstGEP2_64(GV, 0, 0));
757 }
758 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000759 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000760 }
Bill Wendlingd195eb62013-03-18 23:04:39 +0000761
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000762 Builder.CreateRetVoid();
Bill Wendlingd195eb62013-03-18 23:04:39 +0000763 return WriteoutF;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000764}
Bill Wendling77b19132012-05-28 06:10:56 +0000765
766void GCOVProfiler::insertIndirectCounterIncrement() {
767 Function *Fn =
768 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
769 Fn->setUnnamedAddr(true);
770 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling034b94b2012-12-19 07:18:57 +0000771 Fn->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000772 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000773 Fn->addFnAttr(Attribute::NoRedZone);
Bill Wendling77b19132012-05-28 06:10:56 +0000774
Bill Wendling77b19132012-05-28 06:10:56 +0000775 // Create basic blocks for function.
776 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
777 IRBuilder<> Builder(BB);
778
779 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
780 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
781 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
782
783 // uint32_t pred = *predecessor;
784 // if (pred == 0xffffffff) return;
785 Argument *Arg = Fn->arg_begin();
786 Arg->setName("predecessor");
787 Value *Pred = Builder.CreateLoad(Arg, "pred");
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000788 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
Bill Wendling77b19132012-05-28 06:10:56 +0000789 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
790
791 Builder.SetInsertPoint(PredNotNegOne);
792
793 // uint64_t *counter = counters[pred];
794 // if (!counter) return;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000795 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
Bill Wendling77b19132012-05-28 06:10:56 +0000796 Arg = llvm::next(Fn->arg_begin());
797 Arg->setName("counters");
798 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
799 Value *Counter = Builder.CreateLoad(GEP, "counter");
Nick Lewycky58591b12013-02-27 06:21:30 +0000800 Cond = Builder.CreateICmpEQ(Counter,
801 Constant::getNullValue(
802 Builder.getInt64Ty()->getPointerTo()));
Bill Wendling77b19132012-05-28 06:10:56 +0000803 Builder.CreateCondBr(Cond, Exit, CounterEnd);
804
805 // ++*counter;
806 Builder.SetInsertPoint(CounterEnd);
807 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000808 Builder.getInt64(1));
Bill Wendling77b19132012-05-28 06:10:56 +0000809 Builder.CreateStore(Add, Counter);
810 Builder.CreateBr(Exit);
811
812 // Fill in the exit block.
813 Builder.SetInsertPoint(Exit);
814 Builder.CreateRetVoid();
815}
Bill Wendling253353c2012-09-13 00:09:55 +0000816
Bill Wendlingd195eb62013-03-18 23:04:39 +0000817Function *GCOVProfiler::
Bill Wendling253353c2012-09-13 00:09:55 +0000818insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
819 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingd195eb62013-03-18 23:04:39 +0000820 Function *FlushF = M->getFunction("__llvm_gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000821 if (!FlushF)
822 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendlingd195eb62013-03-18 23:04:39 +0000823 "__llvm_gcov_flush", M);
Bill Wendling253353c2012-09-13 00:09:55 +0000824 else
825 FlushF->setLinkage(GlobalValue::InternalLinkage);
826 FlushF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000827 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000828 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000829 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000830
Bill Wendling253353c2012-09-13 00:09:55 +0000831 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
832
833 // Write out the current counters.
834 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
835 assert(WriteoutF && "Need to create the writeout function first!");
836
837 IRBuilder<> Builder(Entry);
838 Builder.CreateCall(WriteoutF);
839
Bill Wendling032dbee2012-09-13 14:32:30 +0000840 // Zero out the counters.
841 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
842 I = CountersBySP.begin(), E = CountersBySP.end();
843 I != E; ++I) {
844 GlobalVariable *GV = I->first;
845 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
Bill Wendlingec3fc2e2012-09-14 22:35:49 +0000846 Builder.CreateStore(Null, GV);
Bill Wendling032dbee2012-09-13 14:32:30 +0000847 }
Bill Wendling253353c2012-09-13 00:09:55 +0000848
849 Type *RetTy = FlushF->getReturnType();
850 if (RetTy == Type::getVoidTy(*Ctx))
851 Builder.CreateRetVoid();
852 else if (RetTy->isIntegerTy())
Bill Wendlingd195eb62013-03-18 23:04:39 +0000853 // Used if __llvm_gcov_flush was implicitly declared.
Bill Wendling253353c2012-09-13 00:09:55 +0000854 Builder.CreateRet(ConstantInt::get(RetTy, 0));
855 else
Bill Wendlingd195eb62013-03-18 23:04:39 +0000856 report_fatal_error("invalid return type for __llvm_gcov_flush");
857
858 return FlushF;
Bill Wendling253353c2012-09-13 00:09:55 +0000859}