blob: 09dea48e3988629b08fa9db75b3cdb7c2df35ed7 [file] [log] [blame]
Nick Lewyckyb1928702011-04-16 01:20:23 +00001//===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass implements GCOV-style profiling. When this pass is run it emits
11// "gcno" files next to the existing source, and instruments the code that runs
12// to records the edges between blocks that run and emit a complementary "gcda"
13// file on exit.
14//
15//===----------------------------------------------------------------------===//
16
17#define DEBUG_TYPE "insert-gcov-profiling"
18
Nick Lewyckyb1928702011-04-16 01:20:23 +000019#include "llvm/Transforms/Instrumentation.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "ProfilingUtils.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000021#include "llvm/ADT/DenseMap.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000022#include "llvm/ADT/STLExtras.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000023#include "llvm/ADT/Statistic.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000024#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/UniqueVector.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/DebugInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000028#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Module.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000031#include "llvm/Pass.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/DebugLoc.h"
34#include "llvm/Support/InstIterator.h"
35#include "llvm/Support/PathV2.h"
36#include "llvm/Support/raw_ostream.h"
37#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewyckyb1928702011-04-16 01:20:23 +000038#include <string>
39#include <utility>
40using namespace llvm;
41
42namespace {
43 class GCOVProfiler : public ModulePass {
Nick Lewyckyb1928702011-04-16 01:20:23 +000044 public:
45 static char ID;
Nick Lewyckya61e52c2011-04-21 01:56:25 +000046 GCOVProfiler()
Nick Lewyckybba40db2011-11-27 23:22:20 +000047 : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(false),
Bill Wendling08e13e42012-12-10 19:46:49 +000048 UseExtraChecksum(false), NoRedZone(false) {
Nick Lewyckya61e52c2011-04-21 01:56:25 +000049 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
50 }
Rafael Espindolaf209dea2012-12-18 03:35:05 +000051 GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format,
52 bool useExtraChecksum, bool NoRedZone_)
Bill Wendlingf5c95b82011-05-17 23:05:13 +000053 : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
Rafael Espindolaf209dea2012-12-18 03:35:05 +000054 Use402Format(use402Format), UseExtraChecksum(useExtraChecksum),
55 NoRedZone(NoRedZone_) {
Nick Lewyckya61e52c2011-04-21 01:56:25 +000056 assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
Nick Lewyckyb1928702011-04-16 01:20:23 +000057 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
58 }
59 virtual const char *getPassName() const {
60 return "GCOV Profiler";
61 }
Nick Lewyckyb1928702011-04-16 01:20:23 +000062 private:
Nick Lewycky269687f2011-05-04 04:03:04 +000063 bool runOnModule(Module &M);
64
Nick Lewyckyb1928702011-04-16 01:20:23 +000065 // Create the GCNO files for the Module based on DebugInfo.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000066 void emitGCNO();
Nick Lewyckyb1928702011-04-16 01:20:23 +000067
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000068 // Modify the program to track transitions along edges and call into the
69 // profiling runtime to emit .gcda files when run.
Devang Patelf6d3a4c2011-08-17 22:49:38 +000070 bool emitProfileArcs();
Nick Lewycky0c4de8a2011-04-16 02:05:18 +000071
Nick Lewyckyb1928702011-04-16 01:20:23 +000072 // Get pointers to the functions in the runtime library.
73 Constant *getStartFileFunc();
Bill Wendling77b19132012-05-28 06:10:56 +000074 Constant *getIncrementIndirectCounterFunc();
Nick Lewyckyb1928702011-04-16 01:20:23 +000075 Constant *getEmitFunctionFunc();
76 Constant *getEmitArcsFunc();
77 Constant *getEndFileFunc();
78
Nick Lewycky1790c9c2011-04-26 03:54:16 +000079 // Create or retrieve an i32 state value that is used to represent the
80 // pred block number for certain non-trivial edges.
81 GlobalVariable *getEdgeStateValue();
82
83 // Produce a table of pointers to counters, by predecessor and successor
84 // block number.
85 GlobalVariable *buildEdgeLookupTable(Function *F,
86 GlobalVariable *Counter,
87 const UniqueVector<BasicBlock *> &Preds,
88 const UniqueVector<BasicBlock *> &Succs);
89
Nick Lewyckyb1928702011-04-16 01:20:23 +000090 // Add the function to write out all our counters to the global destructor
91 // list.
Bill Wendling21b742f2012-08-29 18:45:41 +000092 void insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Bill Wendling77b19132012-05-28 06:10:56 +000093 void insertIndirectCounterIncrement();
Bill Wendling253353c2012-09-13 00:09:55 +000094 void insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Nick Lewyckyb1928702011-04-16 01:20:23 +000095
Bill Wendling73996f42012-08-30 01:32:31 +000096 std::string mangleName(DICompileUnit CU, const char *NewStem);
Nick Lewycky269687f2011-05-04 04:03:04 +000097
Nick Lewyckya61e52c2011-04-21 01:56:25 +000098 bool EmitNotes;
99 bool EmitData;
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000100 bool Use402Format;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000101 bool UseExtraChecksum;
Bill Wendling08e13e42012-12-10 19:46:49 +0000102 bool NoRedZone;
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000103
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000104 Module *M;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000105 LLVMContext *Ctx;
106 };
107}
108
109char GCOVProfiler::ID = 0;
110INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
111 "Insert instrumentation for GCOV profiling", false, false)
112
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000113ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
Nick Lewycky7c067412011-12-06 00:29:13 +0000114 bool Use402Format,
Bill Wendling08e13e42012-12-10 19:46:49 +0000115 bool UseExtraChecksum,
116 bool NoRedZone) {
117 return new GCOVProfiler(EmitNotes, EmitData, Use402Format, UseExtraChecksum,
118 NoRedZone);
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000119}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000120
Nick Lewyckyb1928702011-04-16 01:20:23 +0000121namespace {
122 class GCOVRecord {
123 protected:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000124 static const char *LinesTag;
125 static const char *FunctionTag;
126 static const char *BlockTag;
127 static const char *EdgeTag;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000128
129 GCOVRecord() {}
130
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000131 void writeBytes(const char *Bytes, int Size) {
132 os->write(Bytes, Size);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000133 }
134
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000135 void write(uint32_t i) {
136 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000137 }
138
139 // Returns the length measured in 4-byte blocks that will be used to
140 // represent this string in a GCOV file
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000141 unsigned lengthOfGCOVString(StringRef s) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000142 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewycky17df2c32011-04-21 02:48:39 +0000143 // padding out to the next 4-byte word. The length is measured in 4-byte
144 // words including padding, not bytes of actual string.
Nick Lewyckyd363ff32011-05-05 23:52:18 +0000145 return (s.size() / 4) + 1;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000146 }
147
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000148 void writeGCOVString(StringRef s) {
149 uint32_t Len = lengthOfGCOVString(s);
150 write(Len);
151 writeBytes(s.data(), s.size());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000152
153 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000154 assert((unsigned)(4 - (s.size() % 4)) > 0);
155 assert((unsigned)(4 - (s.size() % 4)) <= 4);
156 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewyckyb1928702011-04-16 01:20:23 +0000157 }
158
159 raw_ostream *os;
160 };
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000161 const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
162 const char *GCOVRecord::FunctionTag = "\0\0\0\1";
163 const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
164 const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewyckyb1928702011-04-16 01:20:23 +0000165
166 class GCOVFunction;
167 class GCOVBlock;
168
169 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Patel16c19a12011-09-20 18:35:00 +0000170 // list of line numbers and a single filename, representing lines that belong
171 // to the block.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000172 class GCOVLines : public GCOVRecord {
173 public:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000174 void addLine(uint32_t Line) {
175 Lines.push_back(Line);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000176 }
177
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000178 uint32_t length() {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000179 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Patel16c19a12011-09-20 18:35:00 +0000180 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000181 }
182
Devang Patel16c19a12011-09-20 18:35:00 +0000183 void writeOut() {
184 write(0);
185 writeGCOVString(Filename);
186 for (int i = 0, e = Lines.size(); i != e; ++i)
187 write(Lines[i]);
188 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000189
Devang Patel16c19a12011-09-20 18:35:00 +0000190 GCOVLines(StringRef F, raw_ostream *os)
191 : Filename(F) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000192 this->os = os;
193 }
194
Devang Patel680018f2011-09-20 18:48:56 +0000195 private:
Devang Patel16c19a12011-09-20 18:35:00 +0000196 StringRef Filename;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000197 SmallVector<uint32_t, 32> Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000198 };
199
200 // Represent a basic block in GCOV. Each block has a unique number in the
201 // function, number of lines belonging to each block, and a set of edges to
202 // other blocks.
203 class GCOVBlock : public GCOVRecord {
204 public:
Devang Patel68155d32011-09-20 17:55:19 +0000205 GCOVLines &getFile(StringRef Filename) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000206 GCOVLines *&Lines = LinesByFile[Filename];
207 if (!Lines) {
Devang Patel16c19a12011-09-20 18:35:00 +0000208 Lines = new GCOVLines(Filename, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000209 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000210 return *Lines;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000211 }
212
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000213 void addEdge(GCOVBlock &Successor) {
214 OutEdges.push_back(&Successor);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000215 }
216
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000217 void writeOut() {
218 uint32_t Len = 3;
219 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
220 E = LinesByFile.end(); I != E; ++I) {
Devang Patel16c19a12011-09-20 18:35:00 +0000221 Len += I->second->length();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000222 }
223
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000224 writeBytes(LinesTag, 4);
225 write(Len);
226 write(Number);
227 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
Devang Patel16c19a12011-09-20 18:35:00 +0000228 E = LinesByFile.end(); I != E; ++I)
229 I->second->writeOut();
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000230 write(0);
231 write(0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000232 }
233
234 ~GCOVBlock() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000235 DeleteContainerSeconds(LinesByFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000236 }
237
238 private:
239 friend class GCOVFunction;
240
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000241 GCOVBlock(uint32_t Number, raw_ostream *os)
242 : Number(Number) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000243 this->os = os;
244 }
245
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000246 uint32_t Number;
247 StringMap<GCOVLines *> LinesByFile;
248 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000249 };
250
251 // A function has a unique identifier, a checksum (we leave as zero) and a
252 // set of blocks and a map of edges between blocks. This is the only GCOV
253 // object users can construct, the blocks and lines will be rooted here.
254 class GCOVFunction : public GCOVRecord {
255 public:
Nick Lewyckybba40db2011-11-27 23:22:20 +0000256 GCOVFunction(DISubprogram SP, raw_ostream *os,
257 bool Use402Format, bool UseExtraChecksum) {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000258 this->os = os;
259
260 Function *F = SP.getFunction();
Nick Lewyckybba40db2011-11-27 23:22:20 +0000261 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000262 uint32_t i = 0;
263 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000264 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000265 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000266 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000267
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000268 writeBytes(FunctionTag, 4);
Bill Wendlingf5c95b82011-05-17 23:05:13 +0000269 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000270 1 + lengthOfGCOVString(SP.getFilename()) + 1;
Nick Lewyckybba40db2011-11-27 23:22:20 +0000271 if (UseExtraChecksum)
272 ++BlockLen;
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000273 write(BlockLen);
274 uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
275 write(Ident);
Nick Lewyckybba40db2011-11-27 23:22:20 +0000276 write(0); // lineno checksum
277 if (UseExtraChecksum)
278 write(0); // cfg checksum
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000279 writeGCOVString(SP.getName());
280 writeGCOVString(SP.getFilename());
281 write(SP.getLineNumber());
Nick Lewyckyb1928702011-04-16 01:20:23 +0000282 }
283
284 ~GCOVFunction() {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000285 DeleteContainerSeconds(Blocks);
286 delete ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000287 }
288
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000289 GCOVBlock &getBlock(BasicBlock *BB) {
290 return *Blocks[BB];
Nick Lewyckyb1928702011-04-16 01:20:23 +0000291 }
292
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000293 GCOVBlock &getReturnBlock() {
294 return *ReturnBlock;
Nick Lewyckya4c4c0e2011-04-21 03:18:00 +0000295 }
296
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000297 void writeOut() {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000298 // Emit count of blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000299 writeBytes(BlockTag, 4);
300 write(Blocks.size() + 1);
301 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
302 write(0); // No flags on our blocks.
Nick Lewyckyb1928702011-04-16 01:20:23 +0000303 }
Nick Lewyckybba40db2011-11-27 23:22:20 +0000304 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewyckyb1928702011-04-16 01:20:23 +0000305
306 // Emit edges between blocks.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000307 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
308 E = Blocks.end(); I != E; ++I) {
309 GCOVBlock &Block = *I->second;
310 if (Block.OutEdges.empty()) continue;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000311
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000312 writeBytes(EdgeTag, 4);
313 write(Block.OutEdges.size() * 2 + 1);
314 write(Block.Number);
315 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewyckybba40db2011-11-27 23:22:20 +0000316 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
317 << "\n");
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000318 write(Block.OutEdges[i]->Number);
319 write(0); // no flags
Nick Lewyckyb1928702011-04-16 01:20:23 +0000320 }
321 }
322
323 // Emit lines for each block.
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000324 for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
325 E = Blocks.end(); I != E; ++I) {
326 I->second->writeOut();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000327 }
328 }
329
330 private:
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000331 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
332 GCOVBlock *ReturnBlock;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000333 };
334}
335
Bill Wendling73996f42012-08-30 01:32:31 +0000336std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
Nick Lewycky269687f2011-05-04 04:03:04 +0000337 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
338 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
339 MDNode *N = GCov->getOperand(i);
340 if (N->getNumOperands() != 2) continue;
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000341 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky269687f2011-05-04 04:03:04 +0000342 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000343 if (!GCovFile || !CompileUnit) continue;
344 if (CompileUnit == CU) {
Bill Wendling6e5190c2012-08-30 00:34:21 +0000345 SmallString<128> Filename = GCovFile->getString();
346 sys::path::replace_extension(Filename, NewStem);
347 return Filename.str();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000348 }
Nick Lewycky269687f2011-05-04 04:03:04 +0000349 }
350 }
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000351
Bill Wendling6e5190c2012-08-30 00:34:21 +0000352 SmallString<128> Filename = CU.getFilename();
Nick Lewyckyfcf74ed2011-05-05 00:03:30 +0000353 sys::path::replace_extension(Filename, NewStem);
Bill Wendling6e5190c2012-08-30 00:34:21 +0000354 return sys::path::filename(Filename.str());
Nick Lewycky269687f2011-05-04 04:03:04 +0000355}
356
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000357bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000358 this->M = &M;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000359 Ctx = &M.getContext();
360
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000361 if (EmitNotes) emitGCNO();
362 if (EmitData) return emitProfileArcs();
Nick Lewyckya61e52c2011-04-21 01:56:25 +0000363 return false;
Nick Lewycky0c4de8a2011-04-16 02:05:18 +0000364}
365
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000366void GCOVProfiler::emitGCNO() {
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000367 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewyckybba40db2011-11-27 23:22:20 +0000368 if (!CU_Nodes) return;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000369
Nick Lewyckybba40db2011-11-27 23:22:20 +0000370 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
371 // Each compile unit gets its own .gcno file. This means that whether we run
372 // this pass over the original .o's as they're produced, or run it after
373 // LTO, we'll generate the same .gcno files.
374
375 DICompileUnit CU(CU_Nodes->getOperand(i));
376 std::string ErrorInfo;
377 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
378 raw_fd_ostream::F_Binary);
379 if (!Use402Format)
380 out.write("oncg*404MVLL", 12);
381 else
382 out.write("oncg*204MVLL", 12);
383
384 DIArray SPs = CU.getSubprograms();
385 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
386 DISubprogram SP(SPs.getElement(i));
387 if (!SP.Verify()) continue;
388
389 Function *F = SP.getFunction();
390 if (!F) continue;
391 GCOVFunction Func(SP, &out, Use402Format, UseExtraChecksum);
392
393 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
394 GCOVBlock &Block = Func.getBlock(BB);
395 TerminatorInst *TI = BB->getTerminator();
396 if (int successors = TI->getNumSuccessors()) {
397 for (int i = 0; i != successors; ++i) {
398 Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
399 }
400 } else if (isa<ReturnInst>(TI)) {
401 Block.addEdge(Func.getReturnBlock());
402 }
403
404 uint32_t Line = 0;
405 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
406 I != IE; ++I) {
407 const DebugLoc &Loc = I->getDebugLoc();
408 if (Loc.isUnknown()) continue;
409 if (Line == Loc.getLine()) continue;
410 Line = Loc.getLine();
411 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
412
413 GCOVLines &Lines = Block.getFile(SP.getFilename());
414 Lines.addLine(Loc.getLine());
415 }
416 }
417 Func.writeOut();
418 }
419 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
420 out.close();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000421 }
422}
423
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000424bool GCOVProfiler::emitProfileArcs() {
425 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
426 if (!CU_Nodes) return false;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000427
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000428 bool Result = false;
Bill Wendling77b19132012-05-28 06:10:56 +0000429 bool InsertIndCounterIncrCode = false;
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000430 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
431 DICompileUnit CU(CU_Nodes->getOperand(i));
432 DIArray SPs = CU.getSubprograms();
433 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
434 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
435 DISubprogram SP(SPs.getElement(i));
436 if (!SP.Verify()) continue;
437 Function *F = SP.getFunction();
438 if (!F) continue;
439 if (!Result) Result = true;
440 unsigned Edges = 0;
441 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
442 TerminatorInst *TI = BB->getTerminator();
443 if (isa<ReturnInst>(TI))
444 ++Edges;
445 else
446 Edges += TI->getNumSuccessors();
447 }
448
449 ArrayType *CounterTy =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000450 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000451 GlobalVariable *Counters =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000452 new GlobalVariable(*M, CounterTy, false,
Nick Lewyckyb1928702011-04-16 01:20:23 +0000453 GlobalValue::InternalLinkage,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000454 Constant::getNullValue(CounterTy),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000455 "__llvm_gcov_ctr");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000456 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
457
458 UniqueVector<BasicBlock *> ComplexEdgePreds;
459 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
460
461 unsigned Edge = 0;
462 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
463 TerminatorInst *TI = BB->getTerminator();
464 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
465 if (Successors) {
466 IRBuilder<> Builder(TI);
467
468 if (Successors == 1) {
469 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
470 Edge);
471 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000472 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000473 Builder.CreateStore(Count, Counter);
474 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000475 Value *Sel = Builder.CreateSelect(BI->getCondition(),
476 Builder.getInt64(Edge),
477 Builder.getInt64(Edge + 1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000478 SmallVector<Value *, 2> Idx;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000479 Idx.push_back(Builder.getInt64(0));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000480 Idx.push_back(Sel);
481 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
482 Value *Count = Builder.CreateLoad(Counter);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000483 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000484 Builder.CreateStore(Count, Counter);
485 } else {
486 ComplexEdgePreds.insert(BB);
487 for (int i = 0; i != Successors; ++i)
488 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
489 }
490 Edge += Successors;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000491 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000492 }
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000493
494 if (!ComplexEdgePreds.empty()) {
495 GlobalVariable *EdgeTable =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000496 buildEdgeLookupTable(F, Counters,
497 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000498 GlobalVariable *EdgeState = getEdgeStateValue();
499
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000500 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
501 IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000502 Builder.CreateStore(Builder.getInt32(i), EdgeState);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000503 }
504 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
505 // call runtime to perform increment
Bill Wendling77b19132012-05-28 06:10:56 +0000506 BasicBlock::iterator InsertPt =
507 ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000508 IRBuilder<> Builder(InsertPt);
509 Value *CounterPtrArray =
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000510 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
511 i * ComplexEdgePreds.size());
Bill Wendlingc7a88402012-05-25 23:55:00 +0000512
513 // Build code to increment the counter.
Bill Wendling77b19132012-05-28 06:10:56 +0000514 InsertIndCounterIncrCode = true;
515 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
516 EdgeState, CounterPtrArray);
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000517 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000518 }
519 }
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000520
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000521 insertCounterWriteout(CountersBySP);
Bill Wendling253353c2012-09-13 00:09:55 +0000522 insertFlush(CountersBySP);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000523 }
Bill Wendling77b19132012-05-28 06:10:56 +0000524
525 if (InsertIndCounterIncrCode)
526 insertIndirectCounterIncrement();
527
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000528 return Result;
Nick Lewyckyb1928702011-04-16 01:20:23 +0000529}
530
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000531// All edges with successors that aren't branches are "complex", because it
532// requires complex logic to pick which counter to update.
533GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
534 Function *F,
535 GlobalVariable *Counters,
536 const UniqueVector<BasicBlock *> &Preds,
537 const UniqueVector<BasicBlock *> &Succs) {
538 // TODO: support invoke, threads. We rely on the fact that nothing can modify
539 // the whole-Module pred edge# between the time we set it and the time we next
540 // read it. Threads and invoke make this untrue.
541
542 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000543 size_t TableSize = Succs.size() * Preds.size();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000544 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000545 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000546
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000547 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000548 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000549 for (size_t i = 0; i != TableSize; ++i)
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000550 EdgeTable[i] = NullValue;
551
552 unsigned Edge = 0;
553 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
554 TerminatorInst *TI = BB->getTerminator();
555 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky7a2ba2f2011-04-28 21:35:49 +0000556 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000557 for (int i = 0; i != Successors; ++i) {
558 BasicBlock *Succ = TI->getSuccessor(i);
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000559 IRBuilder<> Builder(Succ);
560 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000561 Edge + i);
562 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
563 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
564 }
565 }
566 Edge += Successors;
567 }
568
Benjamin Kramer9e6ee162012-11-17 13:49:37 +0000569 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000570 GlobalVariable *EdgeTableGV =
571 new GlobalVariable(
572 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad26701082011-06-22 09:24:39 +0000573 ConstantArray::get(EdgeTableTy, V),
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000574 "__llvm_gcda_edge_table");
575 EdgeTableGV->setUnnamedAddr(true);
576 return EdgeTableGV;
577}
578
Nick Lewyckyb1928702011-04-16 01:20:23 +0000579Constant *GCOVProfiler::getStartFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000580 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Jay Foad5fdd6c82011-07-12 14:06:48 +0000581 Type::getInt8PtrTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000582 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
583}
584
Bill Wendling77b19132012-05-28 06:10:56 +0000585Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
586 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendlingc7a88402012-05-25 23:55:00 +0000587 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling77b19132012-05-28 06:10:56 +0000588 Type *Args[] = {
Micah Villmowb8bce922012-10-24 17:25:11 +0000589 Int32Ty->getPointerTo(), // uint32_t *predecessor
590 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling77b19132012-05-28 06:10:56 +0000591 };
592 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
593 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000594}
595
596Constant *GCOVProfiler::getEmitFunctionFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000597 Type *Args[2] = {
Nick Lewycky5409a182011-05-05 02:46:38 +0000598 Type::getInt32Ty(*Ctx), // uint32_t ident
599 Type::getInt8PtrTy(*Ctx), // const char *function_name
600 };
Bill Wendlingc7a88402012-05-25 23:55:00 +0000601 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000602 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000603}
604
605Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000606 Type *Args[] = {
Nick Lewyckyb1928702011-04-16 01:20:23 +0000607 Type::getInt32Ty(*Ctx), // uint32_t num_counters
608 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
609 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000610 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
Nick Lewyckyb1928702011-04-16 01:20:23 +0000611 Args, false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000612 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000613}
614
615Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000616 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000617 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000618}
619
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000620GlobalVariable *GCOVProfiler::getEdgeStateValue() {
621 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
622 if (!GV) {
623 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
624 GlobalValue::InternalLinkage,
625 ConstantInt::get(Type::getInt32Ty(*Ctx),
626 0xffffffff),
627 "__llvm_gcov_global_state_pred");
628 GV->setUnnamedAddr(true);
629 }
630 return GV;
631}
Nick Lewyckyb1928702011-04-16 01:20:23 +0000632
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000633void GCOVProfiler::insertCounterWriteout(
Bill Wendling21b742f2012-08-29 18:45:41 +0000634 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling253353c2012-09-13 00:09:55 +0000635 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
636 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
637 if (!WriteoutF)
638 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
639 "__llvm_gcov_writeout", M);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000640 WriteoutF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000641 WriteoutF->addFnAttr(Attribute::NoInline);
Bill Wendling08e13e42012-12-10 19:46:49 +0000642 if (NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000643 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000644
645 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000646 IRBuilder<> Builder(BB);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000647
648 Constant *StartFile = getStartFileFunc();
649 Constant *EmitFunction = getEmitFunctionFunc();
650 Constant *EmitArcs = getEmitArcsFunc();
651 Constant *EndFile = getEndFileFunc();
652
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000653 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
654 if (CU_Nodes) {
655 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Bill Wendling032dbee2012-09-13 14:32:30 +0000656 DICompileUnit CU(CU_Nodes->getOperand(i));
657 std::string FilenameGcda = mangleName(CU, "gcda");
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000658 Builder.CreateCall(StartFile,
659 Builder.CreateGlobalStringPtr(FilenameGcda));
Bill Wendling21b742f2012-08-29 18:45:41 +0000660 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
Nick Lewycky5409a182011-05-05 02:46:38 +0000661 I = CountersBySP.begin(), E = CountersBySP.end();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000662 I != E; ++I) {
663 DISubprogram SP(I->second);
664 intptr_t ident = reinterpret_cast<intptr_t>(I->second);
665 Builder.CreateCall2(EmitFunction,
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000666 Builder.getInt32(ident),
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000667 Builder.CreateGlobalStringPtr(SP.getName()));
668
669 GlobalVariable *GV = I->first;
670 unsigned Arcs =
Nick Lewyckyb1928702011-04-16 01:20:23 +0000671 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000672 Builder.CreateCall2(EmitArcs,
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000673 Builder.getInt32(Arcs),
Devang Patelf6d3a4c2011-08-17 22:49:38 +0000674 Builder.CreateConstGEP2_64(GV, 0, 0));
675 }
676 Builder.CreateCall(EndFile);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000677 }
Nick Lewyckyb1928702011-04-16 01:20:23 +0000678 }
Nick Lewycky1790c9c2011-04-26 03:54:16 +0000679 Builder.CreateRetVoid();
Nick Lewyckyb1928702011-04-16 01:20:23 +0000680
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000681 // Create a small bit of code that registers the "__llvm_gcov_writeout"
682 // function to be executed at exit.
683 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
684 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
685 "__llvm_gcov_init", M);
686 F->setUnnamedAddr(true);
687 F->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling034b94b2012-12-19 07:18:57 +0000688 F->addFnAttr(Attribute::NoInline);
Bill Wendling08e13e42012-12-10 19:46:49 +0000689 if (NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000690 F->addFnAttr(Attribute::NoRedZone);
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000691
692 BB = BasicBlock::Create(*Ctx, "entry", F);
693 Builder.SetInsertPoint(BB);
694
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000695 FTy = FunctionType::get(Builder.getInt32Ty(),
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000696 PointerType::get(FTy, 0), false);
Bill Wendlingc1b6ea72012-06-30 20:21:19 +0000697 Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
Bill Wendling4a8fefa2012-06-01 23:14:32 +0000698 Builder.CreateCall(AtExitFn, WriteoutF);
699 Builder.CreateRetVoid();
700
701 appendToGlobalCtors(*M, F, 0);
Nick Lewyckyb1928702011-04-16 01:20:23 +0000702}
Bill Wendling77b19132012-05-28 06:10:56 +0000703
704void GCOVProfiler::insertIndirectCounterIncrement() {
705 Function *Fn =
706 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
707 Fn->setUnnamedAddr(true);
708 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling034b94b2012-12-19 07:18:57 +0000709 Fn->addFnAttr(Attribute::NoInline);
Bill Wendling08e13e42012-12-10 19:46:49 +0000710 if (NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000711 Fn->addFnAttr(Attribute::NoRedZone);
Bill Wendling77b19132012-05-28 06:10:56 +0000712
Bill Wendling77b19132012-05-28 06:10:56 +0000713 // Create basic blocks for function.
714 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
715 IRBuilder<> Builder(BB);
716
717 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
718 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
719 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
720
721 // uint32_t pred = *predecessor;
722 // if (pred == 0xffffffff) return;
723 Argument *Arg = Fn->arg_begin();
724 Arg->setName("predecessor");
725 Value *Pred = Builder.CreateLoad(Arg, "pred");
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000726 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
Bill Wendling77b19132012-05-28 06:10:56 +0000727 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
728
729 Builder.SetInsertPoint(PredNotNegOne);
730
731 // uint64_t *counter = counters[pred];
732 // if (!counter) return;
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000733 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
Bill Wendling77b19132012-05-28 06:10:56 +0000734 Arg = llvm::next(Fn->arg_begin());
735 Arg->setName("counters");
736 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
737 Value *Counter = Builder.CreateLoad(GEP, "counter");
Nick Lewycky58591b12013-02-27 06:21:30 +0000738 Cond = Builder.CreateICmpEQ(Counter,
739 Constant::getNullValue(
740 Builder.getInt64Ty()->getPointerTo()));
Bill Wendling77b19132012-05-28 06:10:56 +0000741 Builder.CreateCondBr(Cond, Exit, CounterEnd);
742
743 // ++*counter;
744 Builder.SetInsertPoint(CounterEnd);
745 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
Nick Lewyckybd2d1242013-02-27 05:46:30 +0000746 Builder.getInt64(1));
Bill Wendling77b19132012-05-28 06:10:56 +0000747 Builder.CreateStore(Add, Counter);
748 Builder.CreateBr(Exit);
749
750 // Fill in the exit block.
751 Builder.SetInsertPoint(Exit);
752 Builder.CreateRetVoid();
753}
Bill Wendling253353c2012-09-13 00:09:55 +0000754
755void GCOVProfiler::
756insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
757 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendling78fff8e2012-09-17 17:57:05 +0000758 Function *FlushF = M->getFunction("__gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000759 if (!FlushF)
760 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendling78fff8e2012-09-17 17:57:05 +0000761 "__gcov_flush", M);
Bill Wendling253353c2012-09-13 00:09:55 +0000762 else
763 FlushF->setLinkage(GlobalValue::InternalLinkage);
764 FlushF->setUnnamedAddr(true);
Bill Wendling034b94b2012-12-19 07:18:57 +0000765 FlushF->addFnAttr(Attribute::NoInline);
Bill Wendling08e13e42012-12-10 19:46:49 +0000766 if (NoRedZone)
Bill Wendling034b94b2012-12-19 07:18:57 +0000767 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling253353c2012-09-13 00:09:55 +0000768
Bill Wendling253353c2012-09-13 00:09:55 +0000769 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
770
771 // Write out the current counters.
772 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
773 assert(WriteoutF && "Need to create the writeout function first!");
774
775 IRBuilder<> Builder(Entry);
776 Builder.CreateCall(WriteoutF);
777
Bill Wendling032dbee2012-09-13 14:32:30 +0000778 // Zero out the counters.
779 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
780 I = CountersBySP.begin(), E = CountersBySP.end();
781 I != E; ++I) {
782 GlobalVariable *GV = I->first;
783 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
Bill Wendlingec3fc2e2012-09-14 22:35:49 +0000784 Builder.CreateStore(Null, GV);
Bill Wendling032dbee2012-09-13 14:32:30 +0000785 }
Bill Wendling253353c2012-09-13 00:09:55 +0000786
787 Type *RetTy = FlushF->getReturnType();
788 if (RetTy == Type::getVoidTy(*Ctx))
789 Builder.CreateRetVoid();
790 else if (RetTy->isIntegerTy())
Bill Wendling78fff8e2012-09-17 17:57:05 +0000791 // Used if __gcov_flush was implicitly declared.
Bill Wendling253353c2012-09-13 00:09:55 +0000792 Builder.CreateRet(ConstantInt::get(RetTy, 0));
793 else
Bill Wendling78fff8e2012-09-17 17:57:05 +0000794 report_fatal_error("invalid return type for __gcov_flush");
Bill Wendling253353c2012-09-13 00:09:55 +0000795}