blob: 8330a9bc335183bda7f139097f0f4cf6f06d7624 [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
Nick Lewyckyb1928702011-04-16 01:20:23 +000017#include "llvm/Transforms/Instrumentation.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000018#include "llvm/ADT/DenseMap.h"
Stephen Hines36b56882014-04-23 16:57:46 -070019#include "llvm/ADT/Hashing.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000020#include "llvm/ADT/STLExtras.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000021#include "llvm/ADT/Statistic.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000022#include "llvm/ADT/StringExtras.h"
23#include "llvm/ADT/StringMap.h"
24#include "llvm/ADT/UniqueVector.h"
Stephen Hines36b56882014-04-23 16:57:46 -070025#include "llvm/IR/DebugInfo.h"
26#include "llvm/IR/DebugLoc.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000027#include "llvm/IR/IRBuilder.h"
Stephen Hines36b56882014-04-23 16:57:46 -070028#include "llvm/IR/InstIterator.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000029#include "llvm/IR/Instructions.h"
Stephen Hines36b56882014-04-23 16:57:46 -070030#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000031#include "llvm/IR/Module.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000032#include "llvm/Pass.h"
Nick Lewyckya204ef32013-03-14 05:13:26 +000033#include "llvm/Support/CommandLine.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000034#include "llvm/Support/Debug.h"
Bill Wendling39c41c32013-03-26 22:47:50 +000035#include "llvm/Support/FileSystem.h"
Rafael Espindolaa11c3e22013-06-11 22:21:28 +000036#include "llvm/Support/Path.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000037#include "llvm/Support/raw_ostream.h"
38#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewyckyc4e6b542013-06-18 06:38:21 +000039#include <algorithm>
Stephen Hinesdce4a402014-05-29 02:49:00 -070040#include <memory>
Nick Lewyckyb1928702011-04-16 01:20:23 +000041#include <string>
42#include <utility>
43using namespace llvm;
44
Stephen Hinesdce4a402014-05-29 02:49:00 -070045#define DEBUG_TYPE "insert-gcov-profiling"
46
Nick Lewyckya204ef32013-03-14 05:13:26 +000047static cl::opt<std::string>
48DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
49 cl::ValueRequired);
50
51GCOVOptions GCOVOptions::getDefault() {
52 GCOVOptions Options;
53 Options.EmitNotes = true;
54 Options.EmitData = true;
55 Options.UseCfgChecksum = false;
56 Options.NoRedZone = false;
57 Options.FunctionNamesInData = true;
58
59 if (DefaultGCOVVersion.size() != 4) {
60 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
61 DefaultGCOVVersion);
62 }
63 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
64 return Options;
65}
66
Nick Lewyckyb1928702011-04-16 01:20:23 +000067namespace {
Stephen Hines36b56882014-04-23 16:57:46 -070068 class GCOVFunction;
69
Nick Lewyckyb1928702011-04-16 01:20:23 +000070 class GCOVProfiler : public ModulePass {
Nick Lewyckyb1928702011-04-16 01:20:23 +000071 public:
72 static char ID;
Nick Lewyckya204ef32013-03-14 05:13:26 +000073 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
Stephen Hines36b56882014-04-23 16:57:46 -070074 init();
Nick Lewyckya61e52c2011-04-21 01:56:25 +000075 }
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?");
Stephen Hines36b56882014-04-23 16:57:46 -070079 init();
80 }
Stephen Hines36b56882014-04-23 16:57:46 -070081 const char *getPassName() const override {
82 return "GCOV Profiler";
83 }
84
85 private:
86 void init() {
Nick Lewyckya204ef32013-03-14 05:13:26 +000087 ReversedVersion[0] = Options.Version[3];
88 ReversedVersion[1] = Options.Version[2];
89 ReversedVersion[2] = Options.Version[1];
90 ReversedVersion[3] = Options.Version[0];
91 ReversedVersion[4] = '\0';
Nick Lewyckyb1928702011-04-16 01:20:23 +000092 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
93 }
Stephen Hines36b56882014-04-23 16:57:46 -070094 bool runOnModule(Module &M) override;
Nick Lewycky269687f2011-05-04 04:03:04 +000095
Nick Lewycky64a0a332013-03-13 22:55:42 +000096 // Create the .gcno files for the Module based on DebugInfo.
97 void emitProfileNotes();
Nick Lewyckyb1928702011-04-16 01:20:23 +000098
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000099 // Modify the program to track transitions along edges and call into the
100 // profiling runtime to emit .gcda files when run.
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000101 bool emitProfileArcs();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000102
Nick Lewyckyb1928702011-04-16 01:20:23 +0000103 // Get pointers to the functions in the runtime library.
104 Constant *getStartFileFunc();
Bill Wendling77b19132012-05-28 06:10:56 +0000105 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000106 Constant *getEmitFunctionFunc();
107 Constant *getEmitArcsFunc();
Yuchen Wuf42264e2013-11-12 04:59:08 +0000108 Constant *getSummaryInfoFunc();
Bill Wendling18764712013-03-19 21:03:22 +0000109 Constant *getDeleteWriteoutFunctionListFunc();
Bill Wendlingd195eb62013-03-18 23:04:39 +0000110 Constant *getDeleteFlushFunctionListFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000111 Constant *getEndFileFunc();
112
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000113 // Create or retrieve an i32 state value that is used to represent the
114 // pred block number for certain non-trivial edges.
115 GlobalVariable *getEdgeStateValue();
116
117 // Produce a table of pointers to counters, by predecessor and successor
118 // block number.
119 GlobalVariable *buildEdgeLookupTable(Function *F,
120 GlobalVariable *Counter,
Nick Lewycky64a0a332013-03-13 22:55:42 +0000121 const UniqueVector<BasicBlock *>&Preds,
122 const UniqueVector<BasicBlock*>&Succs);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000123
Nick Lewyckyb1928702011-04-16 01:20:23 +0000124 // Add the function to write out all our counters to the global destructor
125 // list.
Bill Wendlingd195eb62013-03-18 23:04:39 +0000126 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
127 MDNode*> >);
128 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Bill Wendling77b19132012-05-28 06:10:56 +0000129 void insertIndirectCounterIncrement();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000130
Bill Wendlingf2a28062013-03-28 22:40:08 +0000131 std::string mangleName(DICompileUnit CU, const char *NewStem);
Nick Lewycky269687f2011-05-04 04:03:04 +0000132
Nick Lewyckya204ef32013-03-14 05:13:26 +0000133 GCOVOptions Options;
134
135 // Reversed, NUL-terminated copy of Options.Version.
Stephen Hines36b56882014-04-23 16:57:46 -0700136 char ReversedVersion[5];
137 // Checksum, produced by hash of EdgeDestinations
138 SmallVector<uint32_t, 4> FileChecksums;
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000139
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000140 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000141 LLVMContext *Ctx;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700142 SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000143 };
144}
145
146char GCOVProfiler::ID = 0;
147INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
148 "Insert instrumentation for GCOV profiling", false, false)
149
Nick Lewyckya204ef32013-03-14 05:13:26 +0000150ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
151 return new GCOVProfiler(Options);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000152}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000153
Stephen Hines36b56882014-04-23 16:57:46 -0700154static StringRef getFunctionName(DISubprogram SP) {
Nick Lewycky5d22d022013-03-19 01:37:55 +0000155 if (!SP.getLinkageName().empty())
156 return SP.getLinkageName();
157 return SP.getName();
158}
159
Nick Lewyckyb1928702011-04-16 01:20:23 +0000160namespace {
161 class GCOVRecord {
162 protected:
Craig Topperd6d6a972013-07-17 03:43:10 +0000163 static const char *const LinesTag;
164 static const char *const FunctionTag;
165 static const char *const BlockTag;
166 static const char *const EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000167
168 GCOVRecord() {}
169
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000170 void writeBytes(const char *Bytes, int Size) {
171 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000172 }
173
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000174 void write(uint32_t i) {
175 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000176 }
177
178 // Returns the length measured in 4-byte blocks that will be used to
179 // represent this string in a GCOV file
Craig Topper619850c2013-07-17 03:54:53 +0000180 static unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000181 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000182 // padding out to the next 4-byte word. The length is measured in 4-byte
183 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000184 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000185 }
186
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000187 void writeGCOVString(StringRef s) {
188 uint32_t Len = lengthOfGCOVString(s);
189 write(Len);
190 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000191
192 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000193 assert((unsigned)(4 - (s.size() % 4)) > 0);
194 assert((unsigned)(4 - (s.size() % 4)) <= 4);
195 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000196 }
197
198 raw_ostream *os;
199 };
Craig Topperd6d6a972013-07-17 03:43:10 +0000200 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
201 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
202 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
203 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000204
205 class GCOVFunction;
206 class GCOVBlock;
207
208 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Patel16c19a12011-09-20 18:35:00 +0000209 // list of line numbers and a single filename, representing lines that belong
210 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000211 class GCOVLines : public GCOVRecord {
212 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000213 void addLine(uint32_t Line) {
214 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000215 }
216
Craig Topper619850c2013-07-17 03:54:53 +0000217 uint32_t length() const {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000218 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000219 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000220 }
221
Devang Patel16c19a12011-09-20 18:35:00 +0000222 void writeOut() {
223 write(0);
224 writeGCOVString(Filename);
225 for (int i = 0, e = Lines.size(); i != e; ++i)
226 write(Lines[i]);
227 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000228
Stephen Hines36b56882014-04-23 16:57:46 -0700229 GCOVLines(StringRef F, raw_ostream *os)
Devang Patel16c19a12011-09-20 18:35:00 +0000230 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000231 this->os = os;
232 }
233
Devang Patel680018f2011-09-20 18:48:56 +0000234 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000235 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000236 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000237 };
238
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000239
Nick Lewyckyb1928702011-04-16 01:20:23 +0000240 // Represent a basic block in GCOV. Each block has a unique number in the
241 // function, number of lines belonging to each block, and a set of edges to
242 // other blocks.
243 class GCOVBlock : public GCOVRecord {
244 public:
Devang Patel68155d32011-09-20 17:55:19 +0000245 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000246 GCOVLines *&Lines = LinesByFile[Filename];
247 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000248 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000249 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000250 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000251 }
252
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000253 void addEdge(GCOVBlock &Successor) {
254 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000255 }
256
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000257 void writeOut() {
258 uint32_t Len = 3;
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000259 SmallVector<StringMapEntry<GCOVLines *> *, 32> SortedLinesByFile;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000260 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
261 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000262 Len += I->second->length();
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000263 SortedLinesByFile.push_back(&*I);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000264 }
265
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000266 writeBytes(LinesTag, 4);
267 write(Len);
268 write(Number);
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000269
Stephen Hines36b56882014-04-23 16:57:46 -0700270 std::sort(SortedLinesByFile.begin(), SortedLinesByFile.end(),
271 [](StringMapEntry<GCOVLines *> *LHS,
272 StringMapEntry<GCOVLines *> *RHS) {
273 return LHS->getKey() < RHS->getKey();
274 });
Craig Topper6227d5c2013-07-04 01:31:24 +0000275 for (SmallVectorImpl<StringMapEntry<GCOVLines *> *>::iterator
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000276 I = SortedLinesByFile.begin(), E = SortedLinesByFile.end();
Stephen Hines36b56882014-04-23 16:57:46 -0700277 I != E; ++I)
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000278 (*I)->getValue()->writeOut();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000279 write(0);
280 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000281 }
282
283 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000284 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000285 }
286
287 private:
288 friend class GCOVFunction;
289
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000290 GCOVBlock(uint32_t Number, raw_ostream *os)
291 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000292 this->os = os;
293 }
294
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000295 uint32_t Number;
296 StringMap<GCOVLines *> LinesByFile;
297 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000298 };
299
300 // A function has a unique identifier, a checksum (we leave as zero) and a
301 // set of blocks and a map of edges between blocks. This is the only GCOV
302 // object users can construct, the blocks and lines will be rooted here.
303 class GCOVFunction : public GCOVRecord {
304 public:
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000305 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
Stephen Hines36b56882014-04-23 16:57:46 -0700306 bool UseCfgChecksum) :
307 SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000308 this->os = os;
309
310 Function *F = SP.getFunction();
Stephen Hines36b56882014-04-23 16:57:46 -0700311 DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000312 uint32_t i = 0;
313 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000314 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000315 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000316 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000317
Stephen Hines36b56882014-04-23 16:57:46 -0700318 std::string FunctionNameAndLine;
319 raw_string_ostream FNLOS(FunctionNameAndLine);
320 FNLOS << getFunctionName(SP) << SP.getLineNumber();
321 FNLOS.flush();
322 FuncChecksum = hash_value(FunctionNameAndLine);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000323 }
324
325 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000326 DeleteContainerSeconds(Blocks);
327 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000328 }
329
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000330 GCOVBlock &getBlock(BasicBlock *BB) {
331 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000332 }
333
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000334 GCOVBlock &getReturnBlock() {
335 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000336 }
337
Stephen Hines36b56882014-04-23 16:57:46 -0700338 std::string getEdgeDestinations() {
339 std::string EdgeDestinations;
340 raw_string_ostream EDOS(EdgeDestinations);
341 Function *F = Blocks.begin()->first->getParent();
342 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
343 GCOVBlock &Block = *Blocks[I];
344 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
345 EDOS << Block.OutEdges[i]->Number;
346 }
347 return EdgeDestinations;
348 }
349
350 uint32_t getFuncChecksum() {
351 return FuncChecksum;
352 }
353
354 void setCfgChecksum(uint32_t Checksum) {
355 CfgChecksum = Checksum;
356 }
357
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000358 void writeOut() {
Stephen Hines36b56882014-04-23 16:57:46 -0700359 writeBytes(FunctionTag, 4);
360 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
361 1 + lengthOfGCOVString(SP.getFilename()) + 1;
362 if (UseCfgChecksum)
363 ++BlockLen;
364 write(BlockLen);
365 write(Ident);
366 write(FuncChecksum);
367 if (UseCfgChecksum)
368 write(CfgChecksum);
369 writeGCOVString(getFunctionName(SP));
370 writeGCOVString(SP.getFilename());
371 write(SP.getLineNumber());
372
Nick Lewyckyb1928702011-04-16 01:20:23 +0000373 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000374 writeBytes(BlockTag, 4);
375 write(Blocks.size() + 1);
376 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
377 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000378 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000379 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000380
381 // Emit edges between blocks.
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000382 if (Blocks.empty()) return;
383 Function *F = Blocks.begin()->first->getParent();
384 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
385 GCOVBlock &Block = *Blocks[I];
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000386 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000387
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000388 writeBytes(EdgeTag, 4);
389 write(Block.OutEdges.size() * 2 + 1);
390 write(Block.Number);
391 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000392 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
393 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000394 write(Block.OutEdges[i]->Number);
395 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000396 }
397 }
398
399 // Emit lines for each block.
Nick Lewyckyc4e6b542013-06-18 06:38:21 +0000400 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
401 Blocks[I]->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000402 }
403 }
404
405 private:
Stephen Hines36b56882014-04-23 16:57:46 -0700406 DISubprogram SP;
407 uint32_t Ident;
408 uint32_t FuncChecksum;
409 bool UseCfgChecksum;
410 uint32_t CfgChecksum;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000411 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
412 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000413 };
414}
415
Bill Wendlingf2a28062013-03-28 22:40:08 +0000416std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
Nick Lewycky269687f2011-05-04 04:03:04 +0000417 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
418 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
419 MDNode *N = GCov->getOperand(i);
420 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000421 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000422 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000423 if (!GCovFile || !CompileUnit) continue;
424 if (CompileUnit == CU) {
Bill Wendling6e5190c2012-08-30 00:34:21 +0000425 SmallString<128> Filename = GCovFile->getString();
426 sys::path::replace_extension(Filename, NewStem);
427 return Filename.str();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000428 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000429 }
430 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000431
Bill Wendling6e5190c2012-08-30 00:34:21 +0000432 SmallString<128> Filename = CU.getFilename();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000433 sys::path::replace_extension(Filename, NewStem);
Bill Wendling39c41c32013-03-26 22:47:50 +0000434 StringRef FName = sys::path::filename(Filename);
Bill Wendling39c41c32013-03-26 22:47:50 +0000435 SmallString<128> CurPath;
436 if (sys::fs::current_path(CurPath)) return FName;
437 sys::path::append(CurPath, FName.str());
438 return CurPath.str();
Nick Lewycky269687f2011-05-04 04:03:04 +0000439}
440
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000441bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000442 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000443 Ctx = &M.getContext();
444
Nick Lewyckya204ef32013-03-14 05:13:26 +0000445 if (Options.EmitNotes) emitProfileNotes();
446 if (Options.EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000447 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000448}
449
Stephen Hinesdce4a402014-05-29 02:49:00 -0700450static bool functionHasLines(Function *F) {
451 // Check whether this function actually has any source lines. Not only
452 // do these waste space, they also can crash gcov.
453 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
454 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
455 I != IE; ++I) {
456 const DebugLoc &Loc = I->getDebugLoc();
457 if (Loc.isUnknown()) continue;
458 if (Loc.getLine() != 0)
459 return true;
460 }
461 }
462 return false;
463}
464
Nick Lewycky64a0a332013-03-13 22:55:42 +0000465void GCOVProfiler::emitProfileNotes() {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000466 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewyckybba40db2011-11-27 23:22:20 +0000467 if (!CU_Nodes) return;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000468
Nick Lewyckybba40db2011-11-27 23:22:20 +0000469 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
470 // Each compile unit gets its own .gcno file. This means that whether we run
471 // this pass over the original .o's as they're produced, or run it after
472 // LTO, we'll generate the same .gcno files.
473
474 DICompileUnit CU(CU_Nodes->getOperand(i));
475 std::string ErrorInfo;
Bill Wendlingf2a28062013-03-28 22:40:08 +0000476 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
Stephen Hines36b56882014-04-23 16:57:46 -0700477 sys::fs::F_None);
478 std::string EdgeDestinations;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000479
480 DIArray SPs = CU.getSubprograms();
481 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
482 DISubprogram SP(SPs.getElement(i));
Manman Rencbafae62013-06-28 05:43:10 +0000483 assert((!SP || SP.isSubprogram()) &&
484 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
485 if (!SP)
486 continue;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000487
488 Function *F = SP.getFunction();
489 if (!F) continue;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700490 if (!functionHasLines(F)) continue;
Stephen Hines36b56882014-04-23 16:57:46 -0700491
492 // gcov expects every function to start with an entry block that has a
493 // single successor, so split the entry block to make sure of that.
494 BasicBlock &EntryBlock = F->getEntryBlock();
495 BasicBlock::iterator It = EntryBlock.begin();
496 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
497 ++It;
498 EntryBlock.splitBasicBlock(It);
499
Stephen Hinesdce4a402014-05-29 02:49:00 -0700500 Funcs.push_back(
501 make_unique<GCOVFunction>(SP, &out, i, Options.UseCfgChecksum));
502 GCOVFunction &Func = *Funcs.back();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000503
504 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700505 GCOVBlock &Block = Func.getBlock(BB);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000506 TerminatorInst *TI = BB->getTerminator();
507 if (int successors = TI->getNumSuccessors()) {
508 for (int i = 0; i != successors; ++i) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700509 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
Nick Lewyckybba40db2011-11-27 23:22:20 +0000510 }
511 } else if (isa<ReturnInst>(TI)) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700512 Block.addEdge(Func.getReturnBlock());
Nick Lewyckybba40db2011-11-27 23:22:20 +0000513 }
514
515 uint32_t Line = 0;
516 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
517 I != IE; ++I) {
518 const DebugLoc &Loc = I->getDebugLoc();
519 if (Loc.isUnknown()) continue;
520 if (Line == Loc.getLine()) continue;
521 Line = Loc.getLine();
522 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
523
524 GCOVLines &Lines = Block.getFile(SP.getFilename());
525 Lines.addLine(Loc.getLine());
526 }
527 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700528 EdgeDestinations += Func.getEdgeDestinations();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000529 }
Stephen Hines36b56882014-04-23 16:57:46 -0700530
531 FileChecksums.push_back(hash_value(EdgeDestinations));
532 out.write("oncg", 4);
533 out.write(ReversedVersion, 4);
534 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
535
Stephen Hinesdce4a402014-05-29 02:49:00 -0700536 for (auto &Func : Funcs) {
Stephen Hines36b56882014-04-23 16:57:46 -0700537 Func->setCfgChecksum(FileChecksums.back());
538 Func->writeOut();
539 }
540
Nick Lewyckybba40db2011-11-27 23:22:20 +0000541 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
542 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000543 }
544}
545
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000546bool GCOVProfiler::emitProfileArcs() {
547 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
548 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000549
Stephen Hines36b56882014-04-23 16:57:46 -0700550 bool Result = false;
Bill Wendling77b19132012-05-28 06:10:56 +0000551 bool InsertIndCounterIncrCode = false;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000552 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
553 DICompileUnit CU(CU_Nodes->getOperand(i));
554 DIArray SPs = CU.getSubprograms();
555 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
556 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
557 DISubprogram SP(SPs.getElement(i));
Manman Rencbafae62013-06-28 05:43:10 +0000558 assert((!SP || SP.isSubprogram()) &&
559 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
560 if (!SP)
561 continue;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000562 Function *F = SP.getFunction();
563 if (!F) continue;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700564 if (!functionHasLines(F)) continue;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000565 if (!Result) Result = true;
566 unsigned Edges = 0;
567 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
568 TerminatorInst *TI = BB->getTerminator();
569 if (isa<ReturnInst>(TI))
570 ++Edges;
571 else
572 Edges += TI->getNumSuccessors();
573 }
Stephen Hines36b56882014-04-23 16:57:46 -0700574
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000575 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000576 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000577 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000578 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000579 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000580 Constant::getNullValue(CounterTy),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000581 "__llvm_gcov_ctr");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000582 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
Stephen Hines36b56882014-04-23 16:57:46 -0700583
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000584 UniqueVector<BasicBlock *> ComplexEdgePreds;
585 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
Stephen Hines36b56882014-04-23 16:57:46 -0700586
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000587 unsigned Edge = 0;
588 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
589 TerminatorInst *TI = BB->getTerminator();
590 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
591 if (Successors) {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000592 if (Successors == 1) {
Bill Wendlingf675b3c2013-08-20 23:52:00 +0000593 IRBuilder<> Builder(BB->getFirstInsertionPt());
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000594 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
595 Edge);
596 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000597 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000598 Builder.CreateStore(Count, Counter);
599 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Bill Wendlingf675b3c2013-08-20 23:52:00 +0000600 IRBuilder<> Builder(BI);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000601 Value *Sel = Builder.CreateSelect(BI->getCondition(),
602 Builder.getInt64(Edge),
603 Builder.getInt64(Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000604 SmallVector<Value *, 2> Idx;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000605 Idx.push_back(Builder.getInt64(0));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000606 Idx.push_back(Sel);
607 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
608 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000609 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000610 Builder.CreateStore(Count, Counter);
611 } else {
612 ComplexEdgePreds.insert(BB);
613 for (int i = 0; i != Successors; ++i)
614 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
615 }
Bill Wendlingf675b3c2013-08-20 23:52:00 +0000616
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000617 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000618 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000619 }
Stephen Hines36b56882014-04-23 16:57:46 -0700620
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000621 if (!ComplexEdgePreds.empty()) {
622 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000623 buildEdgeLookupTable(F, Counters,
624 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000625 GlobalVariable *EdgeState = getEdgeStateValue();
Stephen Hines36b56882014-04-23 16:57:46 -0700626
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000627 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
Bill Wendlingf675b3c2013-08-20 23:52:00 +0000628 IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000629 Builder.CreateStore(Builder.getInt32(i), EdgeState);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000630 }
Bill Wendlingf675b3c2013-08-20 23:52:00 +0000631
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000632 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
Bill Wendlingf675b3c2013-08-20 23:52:00 +0000633 // Call runtime to perform increment.
634 IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000635 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000636 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
637 i * ComplexEdgePreds.size());
Bill Wendlingc7a88402012-05-25 23:55:00 +0000638
639 // Build code to increment the counter.
Bill Wendling77b19132012-05-28 06:10:56 +0000640 InsertIndCounterIncrCode = true;
641 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
642 EdgeState, CounterPtrArray);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000643 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000644 }
645 }
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000646
Bill Wendlingd195eb62013-03-18 23:04:39 +0000647 Function *WriteoutF = insertCounterWriteout(CountersBySP);
648 Function *FlushF = insertFlush(CountersBySP);
649
650 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
Bill Wendling18764712013-03-19 21:03:22 +0000651 // be executed at exit and the "__llvm_gcov_flush" function to be executed
652 // when "__gcov_flush" is called.
Bill Wendlingd195eb62013-03-18 23:04:39 +0000653 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
654 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
655 "__llvm_gcov_init", M);
656 F->setUnnamedAddr(true);
657 F->setLinkage(GlobalValue::InternalLinkage);
658 F->addFnAttr(Attribute::NoInline);
659 if (Options.NoRedZone)
660 F->addFnAttr(Attribute::NoRedZone);
661
662 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
663 IRBuilder<> Builder(BB);
664
Bill Wendlingd195eb62013-03-18 23:04:39 +0000665 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendling8640c6a2013-03-20 21:13:59 +0000666 Type *Params[] = {
667 PointerType::get(FTy, 0),
668 PointerType::get(FTy, 0)
669 };
670 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
Bill Wendling18764712013-03-19 21:03:22 +0000671
Yuchen Wud7da5902013-10-23 20:35:00 +0000672 // Initialize the environment and register the local writeout and flush
Bill Wendling8640c6a2013-03-20 21:13:59 +0000673 // functions.
674 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
675 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
Bill Wendlingd195eb62013-03-18 23:04:39 +0000676 Builder.CreateRetVoid();
677
678 appendToGlobalCtors(*M, F, 0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000679 }
Bill Wendling77b19132012-05-28 06:10:56 +0000680
681 if (InsertIndCounterIncrCode)
682 insertIndirectCounterIncrement();
683
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000684 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000685}
686
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000687// All edges with successors that aren't branches are "complex", because it
688// requires complex logic to pick which counter to update.
689GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
690 Function *F,
691 GlobalVariable *Counters,
692 const UniqueVector<BasicBlock *> &Preds,
693 const UniqueVector<BasicBlock *> &Succs) {
694 // TODO: support invoke, threads. We rely on the fact that nothing can modify
695 // the whole-Module pred edge# between the time we set it and the time we next
696 // read it. Threads and invoke make this untrue.
697
698 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000699 size_t TableSize = Succs.size() * Preds.size();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000700 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000701 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000702
Stephen Hines36b56882014-04-23 16:57:46 -0700703 std::unique_ptr<Constant * []> EdgeTable(new Constant *[TableSize]);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000704 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000705 for (size_t i = 0; i != TableSize; ++i)
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000706 EdgeTable[i] = NullValue;
707
708 unsigned Edge = 0;
709 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
710 TerminatorInst *TI = BB->getTerminator();
711 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000712 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000713 for (int i = 0; i != Successors; ++i) {
714 BasicBlock *Succ = TI->getSuccessor(i);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000715 IRBuilder<> Builder(Succ);
716 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000717 Edge + i);
718 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
719 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
720 }
721 }
722 Edge += Successors;
723 }
724
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000725 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000726 GlobalVariable *EdgeTableGV =
727 new GlobalVariable(
728 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000729 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000730 "__llvm_gcda_edge_table");
731 EdgeTableGV->setUnnamedAddr(true);
732 return EdgeTableGV;
733}
734
Nick Lewyckyb1928702011-04-16 01:20:23 +0000735Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000736 Type *Args[] = {
737 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
738 Type::getInt8PtrTy(*Ctx), // const char version[4]
Stephen Hines36b56882014-04-23 16:57:46 -0700739 Type::getInt32Ty(*Ctx), // uint32_t checksum
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000740 };
741 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000742 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
743}
744
Bill Wendling77b19132012-05-28 06:10:56 +0000745Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
746 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendlingc7a88402012-05-25 23:55:00 +0000747 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling77b19132012-05-28 06:10:56 +0000748 Type *Args[] = {
Micah Villmowb8bce922012-10-24 17:25:11 +0000749 Int32Ty->getPointerTo(), // uint32_t *predecessor
750 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling77b19132012-05-28 06:10:56 +0000751 };
752 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
753 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000754}
755
756Constant *GCOVProfiler::getEmitFunctionFunc() {
Stephen Hines36b56882014-04-23 16:57:46 -0700757 Type *Args[] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000758 Type::getInt32Ty(*Ctx), // uint32_t ident
759 Type::getInt8PtrTy(*Ctx), // const char *function_name
Stephen Hines36b56882014-04-23 16:57:46 -0700760 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
Nick Lewycky17d2f772013-03-09 01:33:06 +0000761 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Stephen Hines36b56882014-04-23 16:57:46 -0700762 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
Nick Lewycky5409a182011-05-05 02:46:38 +0000763 };
Bill Wendlingc7a88402012-05-25 23:55:00 +0000764 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000765 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000766}
767
768Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000769 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000770 Type::getInt32Ty(*Ctx), // uint32_t num_counters
771 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
772 };
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000773 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000774 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000775}
776
Yuchen Wuf42264e2013-11-12 04:59:08 +0000777Constant *GCOVProfiler::getSummaryInfoFunc() {
778 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
779 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
780}
781
Bill Wendling18764712013-03-19 21:03:22 +0000782Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
783 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
784 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
785}
786
Bill Wendlingd195eb62013-03-18 23:04:39 +0000787Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
788 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
789 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
790}
791
Nick Lewyckyb1928702011-04-16 01:20:23 +0000792Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000793 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000794 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000795}
796
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000797GlobalVariable *GCOVProfiler::getEdgeStateValue() {
798 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
799 if (!GV) {
800 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
801 GlobalValue::InternalLinkage,
802 ConstantInt::get(Type::getInt32Ty(*Ctx),
803 0xffffffff),
804 "__llvm_gcov_global_state_pred");
805 GV->setUnnamedAddr(true);
806 }
807 return GV;
808}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000809
Bill Wendlingd195eb62013-03-18 23:04:39 +0000810Function *GCOVProfiler::insertCounterWriteout(
Bill Wendling21b742f2012-08-29 18:45:41 +0000811 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling253353c2012-09-13 00:09:55 +0000812 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
813 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
814 if (!WriteoutF)
815 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
816 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000817 WriteoutF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000818 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000819 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000820 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000821
822 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000823 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000824
825 Constant *StartFile = getStartFileFunc();
826 Constant *EmitFunction = getEmitFunctionFunc();
827 Constant *EmitArcs = getEmitArcsFunc();
Yuchen Wuf42264e2013-11-12 04:59:08 +0000828 Constant *SummaryInfo = getSummaryInfoFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000829 Constant *EndFile = getEndFileFunc();
830
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000831 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
832 if (CU_Nodes) {
833 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Bill Wendling032dbee2012-09-13 14:32:30 +0000834 DICompileUnit CU(CU_Nodes->getOperand(i));
Bill Wendlingf2a28062013-03-28 22:40:08 +0000835 std::string FilenameGcda = mangleName(CU, "gcda");
Stephen Hines36b56882014-04-23 16:57:46 -0700836 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
837 Builder.CreateCall3(StartFile,
Nick Lewyckyd9686a92013-03-07 08:28:49 +0000838 Builder.CreateGlobalStringPtr(FilenameGcda),
Stephen Hines36b56882014-04-23 16:57:46 -0700839 Builder.CreateGlobalStringPtr(ReversedVersion),
840 Builder.getInt32(CfgChecksum));
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000841 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
842 DISubprogram SP(CountersBySP[j].second);
Stephen Hines36b56882014-04-23 16:57:46 -0700843 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
844 Builder.CreateCall5(
Nick Lewycky5d22d022013-03-19 01:37:55 +0000845 EmitFunction, Builder.getInt32(j),
846 Options.FunctionNamesInData ?
847 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
848 Constant::getNullValue(Builder.getInt8PtrTy()),
Stephen Hines36b56882014-04-23 16:57:46 -0700849 Builder.getInt32(FuncChecksum),
850 Builder.getInt8(Options.UseCfgChecksum),
851 Builder.getInt32(CfgChecksum));
Nick Lewycky17d2f772013-03-09 01:33:06 +0000852
Nick Lewycky8fa6dc42013-03-09 02:06:37 +0000853 GlobalVariable *GV = CountersBySP[j].first;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000854 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000855 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000856 Builder.CreateCall2(EmitArcs,
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000857 Builder.getInt32(Arcs),
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000858 Builder.CreateConstGEP2_64(GV, 0, 0));
859 }
Yuchen Wuf42264e2013-11-12 04:59:08 +0000860 Builder.CreateCall(SummaryInfo);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000861 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000862 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000863 }
Bill Wendlingd195eb62013-03-18 23:04:39 +0000864
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000865 Builder.CreateRetVoid();
Bill Wendlingd195eb62013-03-18 23:04:39 +0000866 return WriteoutF;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000867}
Bill Wendling77b19132012-05-28 06:10:56 +0000868
869void GCOVProfiler::insertIndirectCounterIncrement() {
870 Function *Fn =
871 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
872 Fn->setUnnamedAddr(true);
873 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling034b94b2012-12-19 07:18:57 +0000874 Fn->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000875 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000876 Fn->addFnAttr(Attribute::NoRedZone);
Bill Wendling77b19132012-05-28 06:10:56 +0000877
Bill Wendling77b19132012-05-28 06:10:56 +0000878 // Create basic blocks for function.
879 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
880 IRBuilder<> Builder(BB);
881
882 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
883 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
884 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
885
886 // uint32_t pred = *predecessor;
887 // if (pred == 0xffffffff) return;
888 Argument *Arg = Fn->arg_begin();
889 Arg->setName("predecessor");
890 Value *Pred = Builder.CreateLoad(Arg, "pred");
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000891 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
Bill Wendling77b19132012-05-28 06:10:56 +0000892 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
893
894 Builder.SetInsertPoint(PredNotNegOne);
895
896 // uint64_t *counter = counters[pred];
897 // if (!counter) return;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000898 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
Stephen Hines36b56882014-04-23 16:57:46 -0700899 Arg = std::next(Fn->arg_begin());
Bill Wendling77b19132012-05-28 06:10:56 +0000900 Arg->setName("counters");
901 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
902 Value *Counter = Builder.CreateLoad(GEP, "counter");
Nick Lewycky58591b12013-02-27 06:21:30 +0000903 Cond = Builder.CreateICmpEQ(Counter,
904 Constant::getNullValue(
905 Builder.getInt64Ty()->getPointerTo()));
Bill Wendling77b19132012-05-28 06:10:56 +0000906 Builder.CreateCondBr(Cond, Exit, CounterEnd);
907
908 // ++*counter;
909 Builder.SetInsertPoint(CounterEnd);
910 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000911 Builder.getInt64(1));
Bill Wendling77b19132012-05-28 06:10:56 +0000912 Builder.CreateStore(Add, Counter);
913 Builder.CreateBr(Exit);
914
915 // Fill in the exit block.
916 Builder.SetInsertPoint(Exit);
917 Builder.CreateRetVoid();
918}
Bill Wendling253353c2012-09-13 00:09:55 +0000919
Bill Wendlingd195eb62013-03-18 23:04:39 +0000920Function *GCOVProfiler::
Bill Wendling253353c2012-09-13 00:09:55 +0000921insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
922 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingd195eb62013-03-18 23:04:39 +0000923 Function *FlushF = M->getFunction("__llvm_gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000924 if (!FlushF)
925 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendlingd195eb62013-03-18 23:04:39 +0000926 "__llvm_gcov_flush", M);
Bill Wendling253353c2012-09-13 00:09:55 +0000927 else
928 FlushF->setLinkage(GlobalValue::InternalLinkage);
929 FlushF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000930 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckya204ef32013-03-14 05:13:26 +0000931 if (Options.NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000932 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000933
Bill Wendling253353c2012-09-13 00:09:55 +0000934 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
935
936 // Write out the current counters.
937 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
938 assert(WriteoutF && "Need to create the writeout function first!");
939
940 IRBuilder<> Builder(Entry);
941 Builder.CreateCall(WriteoutF);
942
Bill Wendling032dbee2012-09-13 14:32:30 +0000943 // Zero out the counters.
944 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
945 I = CountersBySP.begin(), E = CountersBySP.end();
946 I != E; ++I) {
947 GlobalVariable *GV = I->first;
948 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
Bill Wendlingec3fc2e2012-09-14 22:35:49 +0000949 Builder.CreateStore(Null, GV);
Bill Wendling032dbee2012-09-13 14:32:30 +0000950 }
Bill Wendling253353c2012-09-13 00:09:55 +0000951
952 Type *RetTy = FlushF->getReturnType();
953 if (RetTy == Type::getVoidTy(*Ctx))
954 Builder.CreateRetVoid();
955 else if (RetTy->isIntegerTy())
Bill Wendlingd195eb62013-03-18 23:04:39 +0000956 // Used if __llvm_gcov_flush was implicitly declared.
Bill Wendling253353c2012-09-13 00:09:55 +0000957 Builder.CreateRet(ConstantInt::get(RetTy, 0));
958 else
Bill Wendlingd195eb62013-03-18 23:04:39 +0000959 report_fatal_error("invalid return type for __llvm_gcov_flush");
960
961 return FlushF;
Bill Wendling253353c2012-09-13 00:09:55 +0000962}