blob: 2edd151869e086f3e5e4812491e18736f49e1e12 [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 Wendlingf2a28062013-03-28 22:40:08 +0000127 std::string mangleName(DICompileUnit CU, const char *NewStem);
Nick Lewycky269687f2011-05-04 04:03:04 +0000128
Nick Lewyckya204ef32013-03-14 05:13:26 +0000129 GCOVOptions Options;
130
131 // Reversed, NUL-terminated copy of Options.Version.
132 char ReversedVersion[5];
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000133
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000134 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000135 LLVMContext *Ctx;
136 };
137}
138
139char GCOVProfiler::ID = 0;
140INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
141 "Insert instrumentation for GCOV profiling", false, false)
142
Nick Lewyckya204ef32013-03-14 05:13:26 +0000143ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
144 return new GCOVProfiler(Options);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000145}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000146
Nick Lewycky5d22d022013-03-19 01:37:55 +0000147static std::string getFunctionName(DISubprogram SP) {
148 if (!SP.getLinkageName().empty())
149 return SP.getLinkageName();
150 return SP.getName();
151}
152
Nick Lewyckyb1928702011-04-16 01:20:23 +0000153namespace {
154 class GCOVRecord {
155 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000156 static const char *LinesTag;
157 static const char *FunctionTag;
158 static const char *BlockTag;
159 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000160
161 GCOVRecord() {}
162
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000163 void writeBytes(const char *Bytes, int Size) {
164 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000165 }
166
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000167 void write(uint32_t i) {
168 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000169 }
170
171 // Returns the length measured in 4-byte blocks that will be used to
172 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000173 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000174 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000175 // padding out to the next 4-byte word. The length is measured in 4-byte
176 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000177 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000178 }
179
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000180 void writeGCOVString(StringRef s) {
181 uint32_t Len = lengthOfGCOVString(s);
182 write(Len);
183 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000184
185 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000186 assert((unsigned)(4 - (s.size() % 4)) > 0);
187 assert((unsigned)(4 - (s.size() % 4)) <= 4);
188 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000189 }
190
191 raw_ostream *os;
192 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000193 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
194 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
195 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
196 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000197
198 class GCOVFunction;
199 class GCOVBlock;
200
201 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Patel16c19a12011-09-20 18:35:00 +0000202 // list of line numbers and a single filename, representing lines that belong
203 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000204 class GCOVLines : public GCOVRecord {
205 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000206 void addLine(uint32_t Line) {
207 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000208 }
209
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000210 uint32_t length() {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000211 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000212 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000213 }
214
Devang Patel16c19a12011-09-20 18:35:00 +0000215 void writeOut() {
216 write(0);
217 writeGCOVString(Filename);
218 for (int i = 0, e = Lines.size(); i != e; ++i)
219 write(Lines[i]);
220 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000221
Devang Patel16c19a12011-09-20 18:35:00 +0000222 GCOVLines(StringRef F, raw_ostream *os)
223 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000224 this->os = os;
225 }
226
Devang Patel680018f2011-09-20 18:48:56 +0000227 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000228 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000229 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000230 };
231
232 // Represent a basic block in GCOV. Each block has a unique number in the
233 // function, number of lines belonging to each block, and a set of edges to
234 // other blocks.
235 class GCOVBlock : public GCOVRecord {
236 public:
Devang Patel68155d32011-09-20 17:55:19 +0000237 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000238 GCOVLines *&Lines = LinesByFile[Filename];
239 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000240 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000241 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000242 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000243 }
244
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000245 void addEdge(GCOVBlock &Successor) {
246 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000247 }
248
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000249 void writeOut() {
250 uint32_t Len = 3;
251 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
252 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000253 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000254 }
255
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000256 writeBytes(LinesTag, 4);
257 write(Len);
258 write(Number);
259 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
Devang Patel16c19a12011-09-20 18:35:00 +0000260 E = LinesByFile.end(); I != E; ++I)
261 I->second->writeOut();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000262 write(0);
263 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000264 }
265
266 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000267 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000268 }
269
270 private:
271 friend class GCOVFunction;
272
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000273 GCOVBlock(uint32_t Number, raw_ostream *os)
274 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000275 this->os = os;
276 }
277
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000278 uint32_t Number;
279 StringMap<GCOVLines *> LinesByFile;
280 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000281 };
282
283 // A function has a unique identifier, a checksum (we leave as zero) and a
284 // set of blocks and a map of edges between blocks. This is the only GCOV
285 // object users can construct, the blocks and lines will be rooted here.
286 class GCOVFunction : public GCOVRecord {
287 public:
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000288 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
Nick Lewyckya204ef32013-03-14 05:13:26 +0000289 bool UseCfgChecksum) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000290 this->os = os;
291
292 Function *F = SP.getFunction();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000293 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000294 uint32_t i = 0;
295 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000296 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000297 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000298 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000299
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000300 writeBytes(FunctionTag, 4);
Nick Lewycky5d22d022013-03-19 01:37:55 +0000301 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000302 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Nick Lewyckya204ef32013-03-14 05:13:26 +0000303 if (UseCfgChecksum)
Nick Lewyckybba40db2011-11-27 23:22:20 +0000304 ++BlockLen;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000305 write(BlockLen);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000306 write(Ident);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000307 write(0); // lineno checksum
Nick Lewyckya204ef32013-03-14 05:13:26 +0000308 if (UseCfgChecksum)
Nick Lewyckybba40db2011-11-27 23:22:20 +0000309 write(0); // cfg checksum
Nick Lewycky5d22d022013-03-19 01:37:55 +0000310 writeGCOVString(getFunctionName(SP));
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000311 writeGCOVString(SP.getFilename());
312 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000313 }
314
315 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000316 DeleteContainerSeconds(Blocks);
317 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000318 }
319
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000320 GCOVBlock &getBlock(BasicBlock *BB) {
321 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000322 }
323
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000324 GCOVBlock &getReturnBlock() {
325 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000326 }
327
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000328 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000329 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000330 writeBytes(BlockTag, 4);
331 write(Blocks.size() + 1);
332 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
333 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000334 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000335 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000336
337 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000338 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
339 E = Blocks.end(); I != E; ++I) {
340 GCOVBlock &Block = *I->second;
341 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000342
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000343 writeBytes(EdgeTag, 4);
344 write(Block.OutEdges.size() * 2 + 1);
345 write(Block.Number);
346 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000347 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
348 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000349 write(Block.OutEdges[i]->Number);
350 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000351 }
352 }
353
354 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000355 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
356 E = Blocks.end(); I != E; ++I) {
357 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000358 }
359 }
360
361 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000362 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
363 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000364 };
365}
366
Bill Wendlingf2a28062013-03-28 22:40:08 +0000367std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
Nick Lewycky269687f2011-05-04 04:03:04 +0000368 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
369 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
370 MDNode *N = GCov->getOperand(i);
371 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000372 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000373 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000374 if (!GCovFile || !CompileUnit) continue;
375 if (CompileUnit == CU) {
Bill Wendling6e5190c2012-08-30 00:34:21 +0000376 SmallString<128> Filename = GCovFile->getString();
377 sys::path::replace_extension(Filename, NewStem);
378 return Filename.str();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000379 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000380 }
381 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000382
Bill Wendling6e5190c2012-08-30 00:34:21 +0000383 SmallString<128> Filename = CU.getFilename();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000384 sys::path::replace_extension(Filename, NewStem);
Bill Wendling39c41c32013-03-26 22:47:50 +0000385 StringRef FName = sys::path::filename(Filename);
Bill Wendling39c41c32013-03-26 22:47:50 +0000386 SmallString<128> CurPath;
387 if (sys::fs::current_path(CurPath)) return FName;
388 sys::path::append(CurPath, FName.str());
389 return CurPath.str();
Nick Lewycky269687f2011-05-04 04:03:04 +0000390}
391
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000392bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000393 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000394 Ctx = &M.getContext();
395
Nick Lewyckya204ef32013-03-14 05:13:26 +0000396 if (Options.EmitNotes) emitProfileNotes();
397 if (Options.EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000398 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000399}
400
Nick Lewycky64a0a332013-03-13 22:55:42 +0000401void GCOVProfiler::emitProfileNotes() {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000402 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewyckybba40db2011-11-27 23:22:20 +0000403 if (!CU_Nodes) return;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000404
Nick Lewyckybba40db2011-11-27 23:22:20 +0000405 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
406 // Each compile unit gets its own .gcno file. This means that whether we run
407 // this pass over the original .o's as they're produced, or run it after
408 // LTO, we'll generate the same .gcno files.
409
410 DICompileUnit CU(CU_Nodes->getOperand(i));
411 std::string ErrorInfo;
Bill Wendlingf2a28062013-03-28 22:40:08 +0000412 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
Nick Lewyckybba40db2011-11-27 23:22:20 +0000413 raw_fd_ostream::F_Binary);
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000414 out.write("oncg", 4);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000415 out.write(ReversedVersion, 4);
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000416 out.write("MVLL", 4);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000417
418 DIArray SPs = CU.getSubprograms();
419 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
420 DISubprogram SP(SPs.getElement(i));
421 if (!SP.Verify()) continue;
422
423 Function *F = SP.getFunction();
424 if (!F) continue;
Nick Lewyckya204ef32013-03-14 05:13:26 +0000425 GCOVFunction Func(SP, &out, i, Options.UseCfgChecksum);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000426
427 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
428 GCOVBlock &Block = Func.getBlock(BB);
429 TerminatorInst *TI = BB->getTerminator();
430 if (int successors = TI->getNumSuccessors()) {
431 for (int i = 0; i != successors; ++i) {
432 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
433 }
434 } else if (isa<ReturnInst>(TI)) {
435 Block.addEdge(Func.getReturnBlock());
436 }
437
438 uint32_t Line = 0;
439 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
440 I != IE; ++I) {
441 const DebugLoc &Loc = I->getDebugLoc();
442 if (Loc.isUnknown()) continue;
443 if (Line == Loc.getLine()) continue;
444 Line = Loc.getLine();
445 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
446
447 GCOVLines &Lines = Block.getFile(SP.getFilename());
448 Lines.addLine(Loc.getLine());
449 }
450 }
451 Func.writeOut();
452 }
453 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
454 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000455 }
456}
457
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000458bool GCOVProfiler::emitProfileArcs() {
459 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
460 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000461
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000462 bool Result = false;
Bill Wendling77b19132012-05-28 06:10:56 +0000463 bool InsertIndCounterIncrCode = false;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000464 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
465 DICompileUnit CU(CU_Nodes->getOperand(i));
466 DIArray SPs = CU.getSubprograms();
467 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
468 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
469 DISubprogram SP(SPs.getElement(i));
470 if (!SP.Verify()) continue;
471 Function *F = SP.getFunction();
472 if (!F) continue;
473 if (!Result) Result = true;
474 unsigned Edges = 0;
475 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
476 TerminatorInst *TI = BB->getTerminator();
477 if (isa<ReturnInst>(TI))
478 ++Edges;
479 else
480 Edges += TI->getNumSuccessors();
481 }
482
483 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000484 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000485 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000486 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000487 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000488 Constant::getNullValue(CounterTy),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000489 "__llvm_gcov_ctr");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000490 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
491
492 UniqueVector<BasicBlock *> ComplexEdgePreds;
493 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
494
495 unsigned Edge = 0;
496 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
497 TerminatorInst *TI = BB->getTerminator();
498 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
499 if (Successors) {
500 IRBuilder<> Builder(TI);
501
502 if (Successors == 1) {
503 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
504 Edge);
505 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000506 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000507 Builder.CreateStore(Count, Counter);
508 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000509 Value *Sel = Builder.CreateSelect(BI->getCondition(),
510 Builder.getInt64(Edge),
511 Builder.getInt64(Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000512 SmallVector<Value *, 2> Idx;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000513 Idx.push_back(Builder.getInt64(0));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000514 Idx.push_back(Sel);
515 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
516 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000517 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000518 Builder.CreateStore(Count, Counter);
519 } else {
520 ComplexEdgePreds.insert(BB);
521 for (int i = 0; i != Successors; ++i)
522 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
523 }
524 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000525 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000526 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000527
528 if (!ComplexEdgePreds.empty()) {
529 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000530 buildEdgeLookupTable(F, Counters,
531 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000532 GlobalVariable *EdgeState = getEdgeStateValue();
533
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000534 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
535 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000536 Builder.CreateStore(Builder.getInt32(i), EdgeState);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000537 }
538 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
539 // call runtime to perform increment
Bill Wendling77b19132012-05-28 06:10:56 +0000540 BasicBlock::iterator InsertPt =
541 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000542 IRBuilder<> Builder(InsertPt);
543 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000544 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
545 i * ComplexEdgePreds.size());
Bill Wendlingc7a88402012-05-25 23:55:00 +0000546
547 // Build code to increment the counter.
Bill Wendling77b19132012-05-28 06:10:56 +0000548 InsertIndCounterIncrCode = true;
549 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
550 EdgeState, CounterPtrArray);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000551 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000552 }
553 }
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000554
Bill Wendlingd195eb62013-03-18 23:04:39 +0000555 Function *WriteoutF = insertCounterWriteout(CountersBySP);
556 Function *FlushF = insertFlush(CountersBySP);
557
558 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
Bill Wendling18764712013-03-19 21:03:22 +0000559 // be executed at exit and the "__llvm_gcov_flush" function to be executed
560 // when "__gcov_flush" is called.
Bill Wendlingd195eb62013-03-18 23:04:39 +0000561 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
562 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
563 "__llvm_gcov_init", M);
564 F->setUnnamedAddr(true);
565 F->setLinkage(GlobalValue::InternalLinkage);
566 F->addFnAttr(Attribute::NoInline);
567 if (Options.NoRedZone)
568 F->addFnAttr(Attribute::NoRedZone);
569
570 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
571 IRBuilder<> Builder(BB);
572
Bill Wendlingd195eb62013-03-18 23:04:39 +0000573 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendling8640c6a2013-03-20 21:13:59 +0000574 Type *Params[] = {
575 PointerType::get(FTy, 0),
576 PointerType::get(FTy, 0)
577 };
578 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
Bill Wendling18764712013-03-19 21:03:22 +0000579
Bill Wendling8640c6a2013-03-20 21:13:59 +0000580 // Inialize the environment and register the local writeout and flush
581 // functions.
582 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
583 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
Bill Wendlingd195eb62013-03-18 23:04:39 +0000584 Builder.CreateRetVoid();
585
586 appendToGlobalCtors(*M, F, 0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000587 }
Bill Wendling77b19132012-05-28 06:10:56 +0000588
589 if (InsertIndCounterIncrCode)
590 insertIndirectCounterIncrement();
591
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000592 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000593}
594
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000595// All edges with successors that aren't branches are "complex", because it
596// requires complex logic to pick which counter to update.
597GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
598 Function *F,
599 GlobalVariable *Counters,
600 const UniqueVector<BasicBlock *> &Preds,
601 const UniqueVector<BasicBlock *> &Succs) {
602 // TODO: support invoke, threads. We rely on the fact that nothing can modify
603 // the whole-Module pred edge# between the time we set it and the time we next
604 // read it. Threads and invoke make this untrue.
605
606 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000607 size_t TableSize = Succs.size() * Preds.size();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000608 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000609 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000610
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000611 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000612 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000613 for (size_t i = 0; i != TableSize; ++i)
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000614 EdgeTable[i] = NullValue;
615
616 unsigned Edge = 0;
617 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
618 TerminatorInst *TI = BB->getTerminator();
619 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000620 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000621 for (int i = 0; i != Successors; ++i) {
622 BasicBlock *Succ = TI->getSuccessor(i);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000623 IRBuilder<> Builder(Succ);
624 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000625 Edge + i);
626 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
627 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
628 }
629 }
630 Edge += Successors;
631 }
632
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000633 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000634 GlobalVariable *EdgeTableGV =
635 new GlobalVariable(
636 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000637 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000638 "__llvm_gcda_edge_table");
639 EdgeTableGV->setUnnamedAddr(true);
640 return EdgeTableGV;
641}
642
Nick Lewyckyb1928702011-04-16 01:20:23 +0000643Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000644 Type *Args[] = {
645 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
646 Type::getInt8PtrTy(*Ctx), // const char version[4]
647 };
648 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000649 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
650}
651
Bill Wendling77b19132012-05-28 06:10:56 +0000652Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
653 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendlingc7a88402012-05-25 23:55:00 +0000654 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling77b19132012-05-28 06:10:56 +0000655 Type *Args[] = {
Micah Villmowb8bce922012-10-24 17:25:11 +0000656 Int32Ty->getPointerTo(), // uint32_t *predecessor
657 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling77b19132012-05-28 06:10:56 +0000658 };
659 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
660 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000661}
662
663Constant *GCOVProfiler::getEmitFunctionFunc() {
Nick Lewycky17d2f772013-03-09 01:33:06 +0000664 Type *Args[3] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000665 Type::getInt32Ty(*Ctx), // uint32_t ident
666 Type::getInt8PtrTy(*Ctx), // const char *function_name
Nick Lewycky17d2f772013-03-09 01:33:06 +0000667 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Nick Lewycky5409a182011-05-05 02:46:38 +0000668 };
Bill Wendlingc7a88402012-05-25 23:55:00 +0000669 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000670 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000671}
672
673Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000674 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000675 Type::getInt32Ty(*Ctx), // uint32_t num_counters
676 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
677 };
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000678 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000679 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000680}
681
Bill Wendling18764712013-03-19 21:03:22 +0000682Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
683 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
684 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
685}
686
Bill Wendlingd195eb62013-03-18 23:04:39 +0000687Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
688 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
689 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
690}
691
Nick Lewyckyb1928702011-04-16 01:20:23 +0000692Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000693 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000694 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000695}
696
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000697GlobalVariable *GCOVProfiler::getEdgeStateValue() {
698 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
699 if (!GV) {
700 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
701 GlobalValue::InternalLinkage,
702 ConstantInt::get(Type::getInt32Ty(*Ctx),
703 0xffffffff),
704 "__llvm_gcov_global_state_pred");
705 GV->setUnnamedAddr(true);
706 }
707 return GV;
708}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000709
Bill Wendlingd195eb62013-03-18 23:04:39 +0000710Function *GCOVProfiler::insertCounterWriteout(
Bill Wendling21b742f2012-08-29 18:45:41 +0000711 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling253353c2012-09-13 00:09:55 +0000712 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
713 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
714 if (!WriteoutF)
715 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
716 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000717 WriteoutF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000718 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000719 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000720 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000721
722 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000723 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000724
725 Constant *StartFile = getStartFileFunc();
726 Constant *EmitFunction = getEmitFunctionFunc();
727 Constant *EmitArcs = getEmitArcsFunc();
728 Constant *EndFile = getEndFileFunc();
729
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000730 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
731 if (CU_Nodes) {
732 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Bill Wendling032dbee2012-09-13 14:32:30 +0000733 DICompileUnit CU(CU_Nodes->getOperand(i));
Bill Wendlingf2a28062013-03-28 22:40:08 +0000734 std::string FilenameGcda = mangleName(CU, "gcda");
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000735 Builder.CreateCall2(StartFile,
736 Builder.CreateGlobalStringPtr(FilenameGcda),
Nick Lewyckya204ef32013-03-14 05:13:26 +0000737 Builder.CreateGlobalStringPtr(ReversedVersion));
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000738 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
739 DISubprogram SP(CountersBySP[j].second);
Nick Lewycky5d22d022013-03-19 01:37:55 +0000740 Builder.CreateCall3(
741 EmitFunction, Builder.getInt32(j),
742 Options.FunctionNamesInData ?
743 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
744 Constant::getNullValue(Builder.getInt8PtrTy()),
745 Builder.getInt8(Options.UseCfgChecksum));
Nick Lewycky17d2f772013-03-09 01:33:06 +0000746
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000747 GlobalVariable *GV = CountersBySP[j].first;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000748 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000749 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000750 Builder.CreateCall2(EmitArcs,
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000751 Builder.getInt32(Arcs),
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000752 Builder.CreateConstGEP2_64(GV, 0, 0));
753 }
754 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000755 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000756 }
Bill Wendlingd195eb62013-03-18 23:04:39 +0000757
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000758 Builder.CreateRetVoid();
Bill Wendlingd195eb62013-03-18 23:04:39 +0000759 return WriteoutF;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000760}
Bill Wendling77b19132012-05-28 06:10:56 +0000761
762void GCOVProfiler::insertIndirectCounterIncrement() {
763 Function *Fn =
764 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
765 Fn->setUnnamedAddr(true);
766 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling034b94b2012-12-19 07:18:57 +0000767 Fn->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000768 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000769 Fn->addFnAttr(Attribute::NoRedZone);
Bill Wendling77b19132012-05-28 06:10:56 +0000770
Bill Wendling77b19132012-05-28 06:10:56 +0000771 // Create basic blocks for function.
772 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
773 IRBuilder<> Builder(BB);
774
775 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
776 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
777 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
778
779 // uint32_t pred = *predecessor;
780 // if (pred == 0xffffffff) return;
781 Argument *Arg = Fn->arg_begin();
782 Arg->setName("predecessor");
783 Value *Pred = Builder.CreateLoad(Arg, "pred");
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000784 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
Bill Wendling77b19132012-05-28 06:10:56 +0000785 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
786
787 Builder.SetInsertPoint(PredNotNegOne);
788
789 // uint64_t *counter = counters[pred];
790 // if (!counter) return;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000791 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
Bill Wendling77b19132012-05-28 06:10:56 +0000792 Arg = llvm::next(Fn->arg_begin());
793 Arg->setName("counters");
794 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
795 Value *Counter = Builder.CreateLoad(GEP, "counter");
Nick Lewycky58591b12013-02-27 06:21:30 +0000796 Cond = Builder.CreateICmpEQ(Counter,
797 Constant::getNullValue(
798 Builder.getInt64Ty()->getPointerTo()));
Bill Wendling77b19132012-05-28 06:10:56 +0000799 Builder.CreateCondBr(Cond, Exit, CounterEnd);
800
801 // ++*counter;
802 Builder.SetInsertPoint(CounterEnd);
803 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000804 Builder.getInt64(1));
Bill Wendling77b19132012-05-28 06:10:56 +0000805 Builder.CreateStore(Add, Counter);
806 Builder.CreateBr(Exit);
807
808 // Fill in the exit block.
809 Builder.SetInsertPoint(Exit);
810 Builder.CreateRetVoid();
811}
Bill Wendling253353c2012-09-13 00:09:55 +0000812
Bill Wendlingd195eb62013-03-18 23:04:39 +0000813Function *GCOVProfiler::
Bill Wendling253353c2012-09-13 00:09:55 +0000814insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
815 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingd195eb62013-03-18 23:04:39 +0000816 Function *FlushF = M->getFunction("__llvm_gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000817 if (!FlushF)
818 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendlingd195eb62013-03-18 23:04:39 +0000819 "__llvm_gcov_flush", M);
Bill Wendling253353c2012-09-13 00:09:55 +0000820 else
821 FlushF->setLinkage(GlobalValue::InternalLinkage);
822 FlushF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000823 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000824 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000825 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000826
Bill Wendling253353c2012-09-13 00:09:55 +0000827 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
828
829 // Write out the current counters.
830 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
831 assert(WriteoutF && "Need to create the writeout function first!");
832
833 IRBuilder<> Builder(Entry);
834 Builder.CreateCall(WriteoutF);
835
Bill Wendling032dbee2012-09-13 14:32:30 +0000836 // Zero out the counters.
837 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
838 I = CountersBySP.begin(), E = CountersBySP.end();
839 I != E; ++I) {
840 GlobalVariable *GV = I->first;
841 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
Bill Wendlingec3fc2e2012-09-14 22:35:49 +0000842 Builder.CreateStore(Null, GV);
Bill Wendling032dbee2012-09-13 14:32:30 +0000843 }
Bill Wendling253353c2012-09-13 00:09:55 +0000844
845 Type *RetTy = FlushF->getReturnType();
846 if (RetTy == Type::getVoidTy(*Ctx))
847 Builder.CreateRetVoid();
848 else if (RetTy->isIntegerTy())
Bill Wendlingd195eb62013-03-18 23:04:39 +0000849 // Used if __llvm_gcov_flush was implicitly declared.
Bill Wendling253353c2012-09-13 00:09:55 +0000850 Builder.CreateRet(ConstantInt::get(RetTy, 0));
851 else
Bill Wendlingd195eb62013-03-18 23:04:39 +0000852 report_fatal_error("invalid return type for __llvm_gcov_flush");
853
854 return FlushF;
Bill Wendling253353c2012-09-13 00:09:55 +0000855}