blob: 63227f997233712bd84fc4f6e6f6ab5205051bc8 [file] [log] [blame]
Nick Lewycky966edd02011-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 Lewycky966edd02011-04-16 01:20:23 +000019#include "llvm/Transforms/Instrumentation.h"
Nick Lewycky966edd02011-04-16 01:20:23 +000020#include "llvm/ADT/DenseMap.h"
Yuchen Wubabe7492013-11-20 04:15:05 +000021#include "llvm/ADT/Hashing.h"
Nick Lewycky966edd02011-04-16 01:20:23 +000022#include "llvm/ADT/STLExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000023#include "llvm/ADT/Statistic.h"
Nick Lewycky966edd02011-04-16 01:20:23 +000024#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/UniqueVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Module.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Pass.h"
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000032#include "llvm/Support/CommandLine.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000033#include "llvm/Support/Debug.h"
34#include "llvm/Support/DebugLoc.h"
Bill Wendling5aa82392013-03-26 22:47:50 +000035#include "llvm/Support/FileSystem.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000036#include "llvm/Support/InstIterator.h"
Rafael Espindola3bc8e712013-06-11 22:21:28 +000037#include "llvm/Support/Path.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000038#include "llvm/Support/raw_ostream.h"
39#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewycky0fdd0192013-06-18 06:38:21 +000040#include <algorithm>
Nick Lewycky966edd02011-04-16 01:20:23 +000041#include <string>
42#include <utility>
43using namespace llvm;
44
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000045static cl::opt<std::string>
46DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
47 cl::ValueRequired);
48
49GCOVOptions GCOVOptions::getDefault() {
50 GCOVOptions Options;
51 Options.EmitNotes = true;
52 Options.EmitData = true;
53 Options.UseCfgChecksum = false;
54 Options.NoRedZone = false;
55 Options.FunctionNamesInData = true;
56
57 if (DefaultGCOVVersion.size() != 4) {
58 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
59 DefaultGCOVVersion);
60 }
61 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
62 return Options;
63}
64
Nick Lewycky966edd02011-04-16 01:20:23 +000065namespace {
Yuchen Wubabe7492013-11-20 04:15:05 +000066 class GCOVFunction;
67
Nick Lewycky966edd02011-04-16 01:20:23 +000068 class GCOVProfiler : public ModulePass {
Nick Lewycky966edd02011-04-16 01:20:23 +000069 public:
70 static char ID;
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000071 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
Yuchen Wubabe7492013-11-20 04:15:05 +000072 init();
Nick Lewycky8e0a38f2011-04-21 01:56:25 +000073 }
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000074 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
75 assert((Options.EmitNotes || Options.EmitData) &&
76 "GCOVProfiler asked to do nothing?");
Yuchen Wubabe7492013-11-20 04:15:05 +000077 init();
78 }
79 ~GCOVProfiler() {
80 DeleteContainerPointers(Funcs);
Nick Lewycky966edd02011-04-16 01:20:23 +000081 }
82 virtual const char *getPassName() const {
83 return "GCOV Profiler";
84 }
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000085
Nick Lewycky966edd02011-04-16 01:20:23 +000086 private:
Yuchen Wubabe7492013-11-20 04:15:05 +000087 void init() {
88 ReversedVersion[0] = Options.Version[3];
89 ReversedVersion[1] = Options.Version[2];
90 ReversedVersion[2] = Options.Version[1];
91 ReversedVersion[3] = Options.Version[0];
92 ReversedVersion[4] = '\0';
93 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
94 }
Nick Lewycky6d9f0612011-05-04 04:03:04 +000095 bool runOnModule(Module &M);
96
Nick Lewyckyad145502013-03-13 22:55:42 +000097 // Create the .gcno files for the Module based on DebugInfo.
98 void emitProfileNotes();
Nick Lewycky966edd02011-04-16 01:20:23 +000099
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000100 // Modify the program to track transitions along edges and call into the
101 // profiling runtime to emit .gcda files when run.
Devang Patel2b21d862011-08-17 22:49:38 +0000102 bool emitProfileArcs();
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000103
Nick Lewycky966edd02011-04-16 01:20:23 +0000104 // Get pointers to the functions in the runtime library.
105 Constant *getStartFileFunc();
Bill Wendling15605172012-05-28 06:10:56 +0000106 Constant *getIncrementIndirectCounterFunc();
Nick Lewycky966edd02011-04-16 01:20:23 +0000107 Constant *getEmitFunctionFunc();
108 Constant *getEmitArcsFunc();
Yuchen Wu062f24c2013-11-12 04:59:08 +0000109 Constant *getSummaryInfoFunc();
Bill Wendling04d57c72013-03-19 21:03:22 +0000110 Constant *getDeleteWriteoutFunctionListFunc();
Bill Wendlingc3cab812013-03-18 23:04:39 +0000111 Constant *getDeleteFlushFunctionListFunc();
Nick Lewycky966edd02011-04-16 01:20:23 +0000112 Constant *getEndFileFunc();
113
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000114 // Create or retrieve an i32 state value that is used to represent the
115 // pred block number for certain non-trivial edges.
116 GlobalVariable *getEdgeStateValue();
117
118 // Produce a table of pointers to counters, by predecessor and successor
119 // block number.
120 GlobalVariable *buildEdgeLookupTable(Function *F,
121 GlobalVariable *Counter,
Nick Lewyckyad145502013-03-13 22:55:42 +0000122 const UniqueVector<BasicBlock *>&Preds,
123 const UniqueVector<BasicBlock*>&Succs);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000124
Nick Lewycky966edd02011-04-16 01:20:23 +0000125 // Add the function to write out all our counters to the global destructor
126 // list.
Bill Wendlingc3cab812013-03-18 23:04:39 +0000127 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
128 MDNode*> >);
129 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Bill Wendling15605172012-05-28 06:10:56 +0000130 void insertIndirectCounterIncrement();
Nick Lewycky966edd02011-04-16 01:20:23 +0000131
Bill Wendling85722f42013-03-28 22:40:08 +0000132 std::string mangleName(DICompileUnit CU, const char *NewStem);
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000133
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000134 GCOVOptions Options;
135
136 // Reversed, NUL-terminated copy of Options.Version.
137 char ReversedVersion[5];
Yuchen Wubabe7492013-11-20 04:15:05 +0000138 // Checksum, produced by hash of EdgeDestinations
Yuchen Wu664dc762013-11-21 04:01:05 +0000139 SmallVector<uint32_t, 4> FileChecksums;
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000140
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000141 Module *M;
Nick Lewycky966edd02011-04-16 01:20:23 +0000142 LLVMContext *Ctx;
Yuchen Wubabe7492013-11-20 04:15:05 +0000143 SmallVector<GCOVFunction *, 16> Funcs;
Nick Lewycky966edd02011-04-16 01:20:23 +0000144 };
145}
146
147char GCOVProfiler::ID = 0;
148INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
149 "Insert instrumentation for GCOV profiling", false, false)
150
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000151ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
152 return new GCOVProfiler(Options);
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000153}
Nick Lewycky966edd02011-04-16 01:20:23 +0000154
Yuchen Wubabe7492013-11-20 04:15:05 +0000155static StringRef getFunctionName(DISubprogram SP) {
Nick Lewyckyd6718632013-03-19 01:37:55 +0000156 if (!SP.getLinkageName().empty())
157 return SP.getLinkageName();
158 return SP.getName();
159}
160
Nick Lewycky966edd02011-04-16 01:20:23 +0000161namespace {
162 class GCOVRecord {
163 protected:
Craig Topper1c4d6672013-07-17 03:43:10 +0000164 static const char *const LinesTag;
165 static const char *const FunctionTag;
166 static const char *const BlockTag;
167 static const char *const EdgeTag;
Nick Lewycky966edd02011-04-16 01:20:23 +0000168
169 GCOVRecord() {}
170
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000171 void writeBytes(const char *Bytes, int Size) {
172 os->write(Bytes, Size);
Nick Lewycky966edd02011-04-16 01:20:23 +0000173 }
174
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000175 void write(uint32_t i) {
176 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewycky966edd02011-04-16 01:20:23 +0000177 }
178
179 // Returns the length measured in 4-byte blocks that will be used to
180 // represent this string in a GCOV file
Craig Topper24048c92013-07-17 03:54:53 +0000181 static unsigned lengthOfGCOVString(StringRef s) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000182 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewyckyed749d82011-04-21 02:48:39 +0000183 // padding out to the next 4-byte word. The length is measured in 4-byte
184 // words including padding, not bytes of actual string.
Nick Lewyckya7028842011-05-05 23:52:18 +0000185 return (s.size() / 4) + 1;
Nick Lewycky966edd02011-04-16 01:20:23 +0000186 }
187
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000188 void writeGCOVString(StringRef s) {
189 uint32_t Len = lengthOfGCOVString(s);
190 write(Len);
191 writeBytes(s.data(), s.size());
Nick Lewycky966edd02011-04-16 01:20:23 +0000192
193 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky6aa79492011-04-28 21:35:49 +0000194 assert((unsigned)(4 - (s.size() % 4)) > 0);
195 assert((unsigned)(4 - (s.size() % 4)) <= 4);
196 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewycky966edd02011-04-16 01:20:23 +0000197 }
198
199 raw_ostream *os;
200 };
Craig Topper1c4d6672013-07-17 03:43:10 +0000201 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
202 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
203 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
204 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewycky966edd02011-04-16 01:20:23 +0000205
206 class GCOVFunction;
207 class GCOVBlock;
208
209 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Pateladd1f172011-09-20 18:35:00 +0000210 // list of line numbers and a single filename, representing lines that belong
211 // to the block.
Nick Lewycky966edd02011-04-16 01:20:23 +0000212 class GCOVLines : public GCOVRecord {
213 public:
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000214 void addLine(uint32_t Line) {
215 Lines.push_back(Line);
Nick Lewycky966edd02011-04-16 01:20:23 +0000216 }
217
Craig Topper24048c92013-07-17 03:54:53 +0000218 uint32_t length() const {
Nick Lewycky6404d972011-11-27 23:22:20 +0000219 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Pateladd1f172011-09-20 18:35:00 +0000220 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewycky966edd02011-04-16 01:20:23 +0000221 }
222
Devang Pateladd1f172011-09-20 18:35:00 +0000223 void writeOut() {
224 write(0);
225 writeGCOVString(Filename);
226 for (int i = 0, e = Lines.size(); i != e; ++i)
227 write(Lines[i]);
228 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000229
Devang Pateladd1f172011-09-20 18:35:00 +0000230 GCOVLines(StringRef F, raw_ostream *os)
231 : Filename(F) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000232 this->os = os;
233 }
234
Devang Patel7d06f5c2011-09-20 18:48:56 +0000235 private:
Devang Pateladd1f172011-09-20 18:35:00 +0000236 StringRef Filename;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000237 SmallVector<uint32_t, 32> Lines;
Nick Lewycky966edd02011-04-16 01:20:23 +0000238 };
239
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000240
241 // Sorting function for deterministic behaviour in GCOVBlock::writeOut.
242 struct StringKeySort {
243 bool operator()(StringMapEntry<GCOVLines *> *LHS,
244 StringMapEntry<GCOVLines *> *RHS) const {
245 return LHS->getKey() < RHS->getKey();
246 }
247 };
248
Nick Lewycky966edd02011-04-16 01:20:23 +0000249 // Represent a basic block in GCOV. Each block has a unique number in the
250 // function, number of lines belonging to each block, and a set of edges to
251 // other blocks.
252 class GCOVBlock : public GCOVRecord {
253 public:
Devang Patel9cb1fc02011-09-20 17:55:19 +0000254 GCOVLines &getFile(StringRef Filename) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000255 GCOVLines *&Lines = LinesByFile[Filename];
256 if (!Lines) {
Devang Pateladd1f172011-09-20 18:35:00 +0000257 Lines = new GCOVLines(Filename, os);
Nick Lewycky966edd02011-04-16 01:20:23 +0000258 }
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000259 return *Lines;
Nick Lewycky966edd02011-04-16 01:20:23 +0000260 }
261
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000262 void addEdge(GCOVBlock &Successor) {
263 OutEdges.push_back(&Successor);
Nick Lewycky966edd02011-04-16 01:20:23 +0000264 }
265
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000266 void writeOut() {
267 uint32_t Len = 3;
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000268 SmallVector<StringMapEntry<GCOVLines *> *, 32> SortedLinesByFile;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000269 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
270 E = LinesByFile.end(); I != E; ++I) {
Devang Pateladd1f172011-09-20 18:35:00 +0000271 Len += I->second->length();
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000272 SortedLinesByFile.push_back(&*I);
Nick Lewycky966edd02011-04-16 01:20:23 +0000273 }
274
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000275 writeBytes(LinesTag, 4);
276 write(Len);
277 write(Number);
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000278
279 StringKeySort Sorter;
280 std::sort(SortedLinesByFile.begin(), SortedLinesByFile.end(), Sorter);
Craig Topperaf0dea12013-07-04 01:31:24 +0000281 for (SmallVectorImpl<StringMapEntry<GCOVLines *> *>::iterator
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000282 I = SortedLinesByFile.begin(), E = SortedLinesByFile.end();
283 I != E; ++I)
284 (*I)->getValue()->writeOut();
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000285 write(0);
286 write(0);
Nick Lewycky966edd02011-04-16 01:20:23 +0000287 }
288
289 ~GCOVBlock() {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000290 DeleteContainerSeconds(LinesByFile);
Nick Lewycky966edd02011-04-16 01:20:23 +0000291 }
292
293 private:
294 friend class GCOVFunction;
295
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000296 GCOVBlock(uint32_t Number, raw_ostream *os)
297 : Number(Number) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000298 this->os = os;
299 }
300
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000301 uint32_t Number;
302 StringMap<GCOVLines *> LinesByFile;
303 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewycky966edd02011-04-16 01:20:23 +0000304 };
305
306 // A function has a unique identifier, a checksum (we leave as zero) and a
307 // set of blocks and a map of edges between blocks. This is the only GCOV
308 // object users can construct, the blocks and lines will be rooted here.
309 class GCOVFunction : public GCOVRecord {
310 public:
Nick Lewycky492afe82013-03-07 08:28:49 +0000311 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
Yuchen Wubabe7492013-11-20 04:15:05 +0000312 bool UseCfgChecksum) :
313 SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000314 this->os = os;
315
316 Function *F = SP.getFunction();
Nick Lewycky6404d972011-11-27 23:22:20 +0000317 DEBUG(dbgs() << "Function: " << F->getName() << "\n");
Nick Lewycky966edd02011-04-16 01:20:23 +0000318 uint32_t i = 0;
319 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000320 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewycky966edd02011-04-16 01:20:23 +0000321 }
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000322 ReturnBlock = new GCOVBlock(i++, os);
Nick Lewycky966edd02011-04-16 01:20:23 +0000323 }
324
325 ~GCOVFunction() {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000326 DeleteContainerSeconds(Blocks);
327 delete ReturnBlock;
Nick Lewycky966edd02011-04-16 01:20:23 +0000328 }
329
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000330 GCOVBlock &getBlock(BasicBlock *BB) {
331 return *Blocks[BB];
Nick Lewycky966edd02011-04-16 01:20:23 +0000332 }
333
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000334 GCOVBlock &getReturnBlock() {
335 return *ReturnBlock;
Nick Lewycky8411b552011-04-21 03:18:00 +0000336 }
337
Yuchen Wubabe7492013-11-20 04:15:05 +0000338 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 void setCfgChecksum(uint32_t Checksum) {
351 CfgChecksum = Checksum;
352 }
353
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000354 void writeOut() {
Yuchen Wubabe7492013-11-20 04:15:05 +0000355 writeBytes(FunctionTag, 4);
356 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
357 1 + lengthOfGCOVString(SP.getFilename()) + 1;
358 if (UseCfgChecksum)
359 ++BlockLen;
360 write(BlockLen);
361 write(Ident);
362 write(0); // lineno checksum
363 if (UseCfgChecksum)
364 write(CfgChecksum);
365 writeGCOVString(getFunctionName(SP));
366 writeGCOVString(SP.getFilename());
367 write(SP.getLineNumber());
368
Nick Lewycky966edd02011-04-16 01:20:23 +0000369 // Emit count of blocks.
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000370 writeBytes(BlockTag, 4);
371 write(Blocks.size() + 1);
372 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
373 write(0); // No flags on our blocks.
Nick Lewycky966edd02011-04-16 01:20:23 +0000374 }
Nick Lewycky6404d972011-11-27 23:22:20 +0000375 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewycky966edd02011-04-16 01:20:23 +0000376
377 // Emit edges between blocks.
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000378 if (Blocks.empty()) return;
379 Function *F = Blocks.begin()->first->getParent();
380 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
381 GCOVBlock &Block = *Blocks[I];
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000382 if (Block.OutEdges.empty()) continue;
Nick Lewycky966edd02011-04-16 01:20:23 +0000383
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000384 writeBytes(EdgeTag, 4);
385 write(Block.OutEdges.size() * 2 + 1);
386 write(Block.Number);
387 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewycky6404d972011-11-27 23:22:20 +0000388 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
389 << "\n");
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000390 write(Block.OutEdges[i]->Number);
391 write(0); // no flags
Nick Lewycky966edd02011-04-16 01:20:23 +0000392 }
393 }
394
395 // Emit lines for each block.
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000396 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
397 Blocks[I]->writeOut();
Nick Lewycky966edd02011-04-16 01:20:23 +0000398 }
399 }
400
401 private:
Yuchen Wubabe7492013-11-20 04:15:05 +0000402 DISubprogram SP;
403 uint32_t Ident;
404 bool UseCfgChecksum;
405 uint32_t CfgChecksum;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000406 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
407 GCOVBlock *ReturnBlock;
Nick Lewycky966edd02011-04-16 01:20:23 +0000408 };
409}
410
Bill Wendling85722f42013-03-28 22:40:08 +0000411std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000412 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
413 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
414 MDNode *N = GCov->getOperand(i);
415 if (N->getNumOperands() != 2) continue;
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000416 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000417 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000418 if (!GCovFile || !CompileUnit) continue;
419 if (CompileUnit == CU) {
Bill Wendling1f6f8c22012-08-30 00:34:21 +0000420 SmallString<128> Filename = GCovFile->getString();
421 sys::path::replace_extension(Filename, NewStem);
422 return Filename.str();
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000423 }
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000424 }
425 }
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000426
Bill Wendling1f6f8c22012-08-30 00:34:21 +0000427 SmallString<128> Filename = CU.getFilename();
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000428 sys::path::replace_extension(Filename, NewStem);
Bill Wendling5aa82392013-03-26 22:47:50 +0000429 StringRef FName = sys::path::filename(Filename);
Bill Wendling5aa82392013-03-26 22:47:50 +0000430 SmallString<128> CurPath;
431 if (sys::fs::current_path(CurPath)) return FName;
432 sys::path::append(CurPath, FName.str());
433 return CurPath.str();
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000434}
435
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000436bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000437 this->M = &M;
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000438 Ctx = &M.getContext();
439
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000440 if (Options.EmitNotes) emitProfileNotes();
441 if (Options.EmitData) return emitProfileArcs();
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000442 return false;
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000443}
444
Nick Lewyckyad145502013-03-13 22:55:42 +0000445void GCOVProfiler::emitProfileNotes() {
Devang Patel2b21d862011-08-17 22:49:38 +0000446 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewycky6404d972011-11-27 23:22:20 +0000447 if (!CU_Nodes) return;
Nick Lewycky966edd02011-04-16 01:20:23 +0000448
Nick Lewycky6404d972011-11-27 23:22:20 +0000449 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
450 // Each compile unit gets its own .gcno file. This means that whether we run
451 // this pass over the original .o's as they're produced, or run it after
452 // LTO, we'll generate the same .gcno files.
453
454 DICompileUnit CU(CU_Nodes->getOperand(i));
455 std::string ErrorInfo;
Bill Wendling85722f42013-03-28 22:40:08 +0000456 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
Rafael Espindola6d354812013-07-16 19:44:17 +0000457 sys::fs::F_Binary);
Yuchen Wubabe7492013-11-20 04:15:05 +0000458 std::string EdgeDestinations;
Nick Lewycky6404d972011-11-27 23:22:20 +0000459
460 DIArray SPs = CU.getSubprograms();
461 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
462 DISubprogram SP(SPs.getElement(i));
Manman Ren983a16c2013-06-28 05:43:10 +0000463 assert((!SP || SP.isSubprogram()) &&
464 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
465 if (!SP)
466 continue;
Nick Lewycky6404d972011-11-27 23:22:20 +0000467
468 Function *F = SP.getFunction();
469 if (!F) continue;
Yuchen Wubabe7492013-11-20 04:15:05 +0000470 GCOVFunction *Func =
471 new GCOVFunction(SP, &out, i, Options.UseCfgChecksum);
472 Funcs.push_back(Func);
Nick Lewycky6404d972011-11-27 23:22:20 +0000473
474 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Yuchen Wubabe7492013-11-20 04:15:05 +0000475 GCOVBlock &Block = Func->getBlock(BB);
Nick Lewycky6404d972011-11-27 23:22:20 +0000476 TerminatorInst *TI = BB->getTerminator();
477 if (int successors = TI->getNumSuccessors()) {
478 for (int i = 0; i != successors; ++i) {
Yuchen Wubabe7492013-11-20 04:15:05 +0000479 Block.addEdge(Func->getBlock(TI->getSuccessor(i)));
Nick Lewycky6404d972011-11-27 23:22:20 +0000480 }
481 } else if (isa<ReturnInst>(TI)) {
Yuchen Wubabe7492013-11-20 04:15:05 +0000482 Block.addEdge(Func->getReturnBlock());
Nick Lewycky6404d972011-11-27 23:22:20 +0000483 }
484
485 uint32_t Line = 0;
486 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
487 I != IE; ++I) {
488 const DebugLoc &Loc = I->getDebugLoc();
489 if (Loc.isUnknown()) continue;
490 if (Line == Loc.getLine()) continue;
491 Line = Loc.getLine();
492 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
493
494 GCOVLines &Lines = Block.getFile(SP.getFilename());
495 Lines.addLine(Loc.getLine());
496 }
497 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000498 EdgeDestinations += Func->getEdgeDestinations();
Nick Lewycky6404d972011-11-27 23:22:20 +0000499 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000500
Yuchen Wu664dc762013-11-21 04:01:05 +0000501 FileChecksums.push_back(hash_value(EdgeDestinations));
Yuchen Wubabe7492013-11-20 04:15:05 +0000502 out.write("oncg", 4);
503 out.write(ReversedVersion, 4);
Yuchen Wu664dc762013-11-21 04:01:05 +0000504 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
Yuchen Wubabe7492013-11-20 04:15:05 +0000505
506 for (SmallVectorImpl<GCOVFunction *>::iterator I = Funcs.begin(),
Yuchen Wu664dc762013-11-21 04:01:05 +0000507 E = Funcs.end(); I != E; ++I) {
508 GCOVFunction *Func = *I;
509 Func->setCfgChecksum(FileChecksums.back());
510 Func->writeOut();
511 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000512
Nick Lewycky6404d972011-11-27 23:22:20 +0000513 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
514 out.close();
Nick Lewycky966edd02011-04-16 01:20:23 +0000515 }
516}
517
Devang Patel2b21d862011-08-17 22:49:38 +0000518bool GCOVProfiler::emitProfileArcs() {
519 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
520 if (!CU_Nodes) return false;
Nick Lewycky966edd02011-04-16 01:20:23 +0000521
Devang Patel2b21d862011-08-17 22:49:38 +0000522 bool Result = false;
Bill Wendling15605172012-05-28 06:10:56 +0000523 bool InsertIndCounterIncrCode = false;
Devang Patel2b21d862011-08-17 22:49:38 +0000524 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
525 DICompileUnit CU(CU_Nodes->getOperand(i));
526 DIArray SPs = CU.getSubprograms();
527 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
528 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
529 DISubprogram SP(SPs.getElement(i));
Manman Ren983a16c2013-06-28 05:43:10 +0000530 assert((!SP || SP.isSubprogram()) &&
531 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
532 if (!SP)
533 continue;
Devang Patel2b21d862011-08-17 22:49:38 +0000534 Function *F = SP.getFunction();
535 if (!F) continue;
536 if (!Result) Result = true;
537 unsigned Edges = 0;
538 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
539 TerminatorInst *TI = BB->getTerminator();
540 if (isa<ReturnInst>(TI))
541 ++Edges;
542 else
543 Edges += TI->getNumSuccessors();
544 }
545
546 ArrayType *CounterTy =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000547 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patel2b21d862011-08-17 22:49:38 +0000548 GlobalVariable *Counters =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000549 new GlobalVariable(*M, CounterTy, false,
Nick Lewycky966edd02011-04-16 01:20:23 +0000550 GlobalValue::InternalLinkage,
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000551 Constant::getNullValue(CounterTy),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000552 "__llvm_gcov_ctr");
Devang Patel2b21d862011-08-17 22:49:38 +0000553 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
554
555 UniqueVector<BasicBlock *> ComplexEdgePreds;
556 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
557
558 unsigned Edge = 0;
559 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
560 TerminatorInst *TI = BB->getTerminator();
561 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
562 if (Successors) {
Devang Patel2b21d862011-08-17 22:49:38 +0000563 if (Successors == 1) {
Bill Wendling707f6012013-08-20 23:52:00 +0000564 IRBuilder<> Builder(BB->getFirstInsertionPt());
Devang Patel2b21d862011-08-17 22:49:38 +0000565 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
566 Edge);
567 Value *Count = Builder.CreateLoad(Counter);
Nick Lewycky8e94d802013-02-27 05:46:30 +0000568 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patel2b21d862011-08-17 22:49:38 +0000569 Builder.CreateStore(Count, Counter);
570 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Bill Wendling707f6012013-08-20 23:52:00 +0000571 IRBuilder<> Builder(BI);
Nick Lewycky8e94d802013-02-27 05:46:30 +0000572 Value *Sel = Builder.CreateSelect(BI->getCondition(),
573 Builder.getInt64(Edge),
574 Builder.getInt64(Edge + 1));
Devang Patel2b21d862011-08-17 22:49:38 +0000575 SmallVector<Value *, 2> Idx;
Nick Lewycky8e94d802013-02-27 05:46:30 +0000576 Idx.push_back(Builder.getInt64(0));
Devang Patel2b21d862011-08-17 22:49:38 +0000577 Idx.push_back(Sel);
578 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
579 Value *Count = Builder.CreateLoad(Counter);
Nick Lewycky8e94d802013-02-27 05:46:30 +0000580 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patel2b21d862011-08-17 22:49:38 +0000581 Builder.CreateStore(Count, Counter);
582 } else {
583 ComplexEdgePreds.insert(BB);
584 for (int i = 0; i != Successors; ++i)
585 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
586 }
Bill Wendling707f6012013-08-20 23:52:00 +0000587
Devang Patel2b21d862011-08-17 22:49:38 +0000588 Edge += Successors;
Nick Lewycky966edd02011-04-16 01:20:23 +0000589 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000590 }
Devang Patel2b21d862011-08-17 22:49:38 +0000591
592 if (!ComplexEdgePreds.empty()) {
593 GlobalVariable *EdgeTable =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000594 buildEdgeLookupTable(F, Counters,
595 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patel2b21d862011-08-17 22:49:38 +0000596 GlobalVariable *EdgeState = getEdgeStateValue();
597
Devang Patel2b21d862011-08-17 22:49:38 +0000598 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
Bill Wendling707f6012013-08-20 23:52:00 +0000599 IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
Nick Lewycky8e94d802013-02-27 05:46:30 +0000600 Builder.CreateStore(Builder.getInt32(i), EdgeState);
Devang Patel2b21d862011-08-17 22:49:38 +0000601 }
Bill Wendling707f6012013-08-20 23:52:00 +0000602
Devang Patel2b21d862011-08-17 22:49:38 +0000603 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
Bill Wendling707f6012013-08-20 23:52:00 +0000604 // Call runtime to perform increment.
605 IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
Devang Patel2b21d862011-08-17 22:49:38 +0000606 Value *CounterPtrArray =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000607 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
608 i * ComplexEdgePreds.size());
Bill Wendling8ed07492012-05-25 23:55:00 +0000609
610 // Build code to increment the counter.
Bill Wendling15605172012-05-28 06:10:56 +0000611 InsertIndCounterIncrCode = true;
612 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
613 EdgeState, CounterPtrArray);
Devang Patel2b21d862011-08-17 22:49:38 +0000614 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000615 }
616 }
Bill Wendlinge85f3492012-06-01 23:14:32 +0000617
Bill Wendlingc3cab812013-03-18 23:04:39 +0000618 Function *WriteoutF = insertCounterWriteout(CountersBySP);
619 Function *FlushF = insertFlush(CountersBySP);
620
621 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
Bill Wendling04d57c72013-03-19 21:03:22 +0000622 // be executed at exit and the "__llvm_gcov_flush" function to be executed
623 // when "__gcov_flush" is called.
Bill Wendlingc3cab812013-03-18 23:04:39 +0000624 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
625 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
626 "__llvm_gcov_init", M);
627 F->setUnnamedAddr(true);
628 F->setLinkage(GlobalValue::InternalLinkage);
629 F->addFnAttr(Attribute::NoInline);
630 if (Options.NoRedZone)
631 F->addFnAttr(Attribute::NoRedZone);
632
633 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
634 IRBuilder<> Builder(BB);
635
Bill Wendlingc3cab812013-03-18 23:04:39 +0000636 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingc77e9442013-03-20 21:13:59 +0000637 Type *Params[] = {
638 PointerType::get(FTy, 0),
639 PointerType::get(FTy, 0)
640 };
641 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
Bill Wendling04d57c72013-03-19 21:03:22 +0000642
Yuchen Wu3197b252013-10-23 20:35:00 +0000643 // Initialize the environment and register the local writeout and flush
Bill Wendlingc77e9442013-03-20 21:13:59 +0000644 // functions.
645 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
646 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
Bill Wendlingc3cab812013-03-18 23:04:39 +0000647 Builder.CreateRetVoid();
648
649 appendToGlobalCtors(*M, F, 0);
Nick Lewycky966edd02011-04-16 01:20:23 +0000650 }
Bill Wendling15605172012-05-28 06:10:56 +0000651
652 if (InsertIndCounterIncrCode)
653 insertIndirectCounterIncrement();
654
Devang Patel2b21d862011-08-17 22:49:38 +0000655 return Result;
Nick Lewycky966edd02011-04-16 01:20:23 +0000656}
657
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000658// All edges with successors that aren't branches are "complex", because it
659// requires complex logic to pick which counter to update.
660GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
661 Function *F,
662 GlobalVariable *Counters,
663 const UniqueVector<BasicBlock *> &Preds,
664 const UniqueVector<BasicBlock *> &Succs) {
665 // TODO: support invoke, threads. We rely on the fact that nothing can modify
666 // the whole-Module pred edge# between the time we set it and the time we next
667 // read it. Threads and invoke make this untrue.
668
669 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Benjamin Kramer96e1e392012-11-17 13:49:37 +0000670 size_t TableSize = Succs.size() * Preds.size();
Chris Lattner229907c2011-07-18 04:54:35 +0000671 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer96e1e392012-11-17 13:49:37 +0000672 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000673
Benjamin Kramer96e1e392012-11-17 13:49:37 +0000674 OwningArrayPtr<Constant *> EdgeTable(new Constant*[TableSize]);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000675 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer96e1e392012-11-17 13:49:37 +0000676 for (size_t i = 0; i != TableSize; ++i)
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000677 EdgeTable[i] = NullValue;
678
679 unsigned Edge = 0;
680 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
681 TerminatorInst *TI = BB->getTerminator();
682 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky6aa79492011-04-28 21:35:49 +0000683 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000684 for (int i = 0; i != Successors; ++i) {
685 BasicBlock *Succ = TI->getSuccessor(i);
Nick Lewycky8e94d802013-02-27 05:46:30 +0000686 IRBuilder<> Builder(Succ);
687 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000688 Edge + i);
689 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
690 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
691 }
692 }
693 Edge += Successors;
694 }
695
Benjamin Kramer96e1e392012-11-17 13:49:37 +0000696 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000697 GlobalVariable *EdgeTableGV =
698 new GlobalVariable(
699 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad83be3612011-06-22 09:24:39 +0000700 ConstantArray::get(EdgeTableTy, V),
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000701 "__llvm_gcda_edge_table");
702 EdgeTableGV->setUnnamedAddr(true);
703 return EdgeTableGV;
704}
705
Nick Lewycky966edd02011-04-16 01:20:23 +0000706Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewycky492afe82013-03-07 08:28:49 +0000707 Type *Args[] = {
708 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
709 Type::getInt8PtrTy(*Ctx), // const char version[4]
Yuchen Wubabe7492013-11-20 04:15:05 +0000710 Type::getInt32Ty(*Ctx), // uint32_t checksum
Nick Lewycky492afe82013-03-07 08:28:49 +0000711 };
712 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000713 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
714}
715
Bill Wendling15605172012-05-28 06:10:56 +0000716Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
717 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendling8ed07492012-05-25 23:55:00 +0000718 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling15605172012-05-28 06:10:56 +0000719 Type *Args[] = {
Micah Villmow51e72462012-10-24 17:25:11 +0000720 Int32Ty->getPointerTo(), // uint32_t *predecessor
721 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling15605172012-05-28 06:10:56 +0000722 };
723 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
724 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000725}
726
727Constant *GCOVProfiler::getEmitFunctionFunc() {
Yuchen Wubabe7492013-11-20 04:15:05 +0000728 Type *Args[] = {
Nick Lewycky4f9c3672011-05-05 02:46:38 +0000729 Type::getInt32Ty(*Ctx), // uint32_t ident
730 Type::getInt8PtrTy(*Ctx), // const char *function_name
Nick Lewycky88f1d0d2013-03-09 01:33:06 +0000731 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Yuchen Wubabe7492013-11-20 04:15:05 +0000732 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
Nick Lewycky4f9c3672011-05-05 02:46:38 +0000733 };
Bill Wendling8ed07492012-05-25 23:55:00 +0000734 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000735 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000736}
737
738Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foadb804a2b2011-07-12 14:06:48 +0000739 Type *Args[] = {
Nick Lewycky966edd02011-04-16 01:20:23 +0000740 Type::getInt32Ty(*Ctx), // uint32_t num_counters
741 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
742 };
Nick Lewycky492afe82013-03-07 08:28:49 +0000743 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000744 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000745}
746
Yuchen Wu062f24c2013-11-12 04:59:08 +0000747Constant *GCOVProfiler::getSummaryInfoFunc() {
748 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
749 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
750}
751
Bill Wendling04d57c72013-03-19 21:03:22 +0000752Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
753 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
754 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
755}
756
Bill Wendlingc3cab812013-03-18 23:04:39 +0000757Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
758 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
759 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
760}
761
Nick Lewycky966edd02011-04-16 01:20:23 +0000762Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattner229907c2011-07-18 04:54:35 +0000763 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000764 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000765}
766
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000767GlobalVariable *GCOVProfiler::getEdgeStateValue() {
768 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
769 if (!GV) {
770 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
771 GlobalValue::InternalLinkage,
772 ConstantInt::get(Type::getInt32Ty(*Ctx),
773 0xffffffff),
774 "__llvm_gcov_global_state_pred");
775 GV->setUnnamedAddr(true);
776 }
777 return GV;
778}
Nick Lewycky966edd02011-04-16 01:20:23 +0000779
Bill Wendlingc3cab812013-03-18 23:04:39 +0000780Function *GCOVProfiler::insertCounterWriteout(
Bill Wendlinge8aee6b2012-08-29 18:45:41 +0000781 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling2e6e8662012-09-13 00:09:55 +0000782 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
783 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
784 if (!WriteoutF)
785 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
786 "__llvm_gcov_writeout", M);
Nick Lewycky966edd02011-04-16 01:20:23 +0000787 WriteoutF->setUnnamedAddr(true);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000788 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000789 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000790 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling2e6e8662012-09-13 00:09:55 +0000791
792 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000793 IRBuilder<> Builder(BB);
Nick Lewycky966edd02011-04-16 01:20:23 +0000794
795 Constant *StartFile = getStartFileFunc();
796 Constant *EmitFunction = getEmitFunctionFunc();
797 Constant *EmitArcs = getEmitArcsFunc();
Yuchen Wu062f24c2013-11-12 04:59:08 +0000798 Constant *SummaryInfo = getSummaryInfoFunc();
Nick Lewycky966edd02011-04-16 01:20:23 +0000799 Constant *EndFile = getEndFileFunc();
800
Devang Patel2b21d862011-08-17 22:49:38 +0000801 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
802 if (CU_Nodes) {
803 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Bill Wendlingfb1f6682012-09-13 14:32:30 +0000804 DICompileUnit CU(CU_Nodes->getOperand(i));
Bill Wendling85722f42013-03-28 22:40:08 +0000805 std::string FilenameGcda = mangleName(CU, "gcda");
Yuchen Wubabe7492013-11-20 04:15:05 +0000806 Builder.CreateCall3(StartFile,
Nick Lewycky492afe82013-03-07 08:28:49 +0000807 Builder.CreateGlobalStringPtr(FilenameGcda),
Yuchen Wubabe7492013-11-20 04:15:05 +0000808 Builder.CreateGlobalStringPtr(ReversedVersion),
Yuchen Wu664dc762013-11-21 04:01:05 +0000809 Builder.getInt32(FileChecksums[i]));
Nick Lewycky03aed112013-03-09 02:06:37 +0000810 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
811 DISubprogram SP(CountersBySP[j].second);
Yuchen Wubabe7492013-11-20 04:15:05 +0000812 Builder.CreateCall4(
Nick Lewyckyd6718632013-03-19 01:37:55 +0000813 EmitFunction, Builder.getInt32(j),
814 Options.FunctionNamesInData ?
815 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
816 Constant::getNullValue(Builder.getInt8PtrTy()),
Yuchen Wubabe7492013-11-20 04:15:05 +0000817 Builder.getInt8(Options.UseCfgChecksum),
Yuchen Wu664dc762013-11-21 04:01:05 +0000818 Builder.getInt32(FileChecksums[i]));
Nick Lewycky88f1d0d2013-03-09 01:33:06 +0000819
Nick Lewycky03aed112013-03-09 02:06:37 +0000820 GlobalVariable *GV = CountersBySP[j].first;
Devang Patel2b21d862011-08-17 22:49:38 +0000821 unsigned Arcs =
Nick Lewycky966edd02011-04-16 01:20:23 +0000822 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patel2b21d862011-08-17 22:49:38 +0000823 Builder.CreateCall2(EmitArcs,
Nick Lewycky8e94d802013-02-27 05:46:30 +0000824 Builder.getInt32(Arcs),
Devang Patel2b21d862011-08-17 22:49:38 +0000825 Builder.CreateConstGEP2_64(GV, 0, 0));
826 }
Yuchen Wu062f24c2013-11-12 04:59:08 +0000827 Builder.CreateCall(SummaryInfo);
Devang Patel2b21d862011-08-17 22:49:38 +0000828 Builder.CreateCall(EndFile);
Nick Lewycky966edd02011-04-16 01:20:23 +0000829 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000830 }
Bill Wendlingc3cab812013-03-18 23:04:39 +0000831
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000832 Builder.CreateRetVoid();
Bill Wendlingc3cab812013-03-18 23:04:39 +0000833 return WriteoutF;
Nick Lewycky966edd02011-04-16 01:20:23 +0000834}
Bill Wendling15605172012-05-28 06:10:56 +0000835
836void GCOVProfiler::insertIndirectCounterIncrement() {
837 Function *Fn =
838 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
839 Fn->setUnnamedAddr(true);
840 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000841 Fn->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000842 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000843 Fn->addFnAttr(Attribute::NoRedZone);
Bill Wendling15605172012-05-28 06:10:56 +0000844
Bill Wendling15605172012-05-28 06:10:56 +0000845 // Create basic blocks for function.
846 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
847 IRBuilder<> Builder(BB);
848
849 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
850 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
851 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
852
853 // uint32_t pred = *predecessor;
854 // if (pred == 0xffffffff) return;
855 Argument *Arg = Fn->arg_begin();
856 Arg->setName("predecessor");
857 Value *Pred = Builder.CreateLoad(Arg, "pred");
Nick Lewycky8e94d802013-02-27 05:46:30 +0000858 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
Bill Wendling15605172012-05-28 06:10:56 +0000859 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
860
861 Builder.SetInsertPoint(PredNotNegOne);
862
863 // uint64_t *counter = counters[pred];
864 // if (!counter) return;
Nick Lewycky8e94d802013-02-27 05:46:30 +0000865 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
Bill Wendling15605172012-05-28 06:10:56 +0000866 Arg = llvm::next(Fn->arg_begin());
867 Arg->setName("counters");
868 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
869 Value *Counter = Builder.CreateLoad(GEP, "counter");
Nick Lewycky625f3952013-02-27 06:21:30 +0000870 Cond = Builder.CreateICmpEQ(Counter,
871 Constant::getNullValue(
872 Builder.getInt64Ty()->getPointerTo()));
Bill Wendling15605172012-05-28 06:10:56 +0000873 Builder.CreateCondBr(Cond, Exit, CounterEnd);
874
875 // ++*counter;
876 Builder.SetInsertPoint(CounterEnd);
877 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
Nick Lewycky8e94d802013-02-27 05:46:30 +0000878 Builder.getInt64(1));
Bill Wendling15605172012-05-28 06:10:56 +0000879 Builder.CreateStore(Add, Counter);
880 Builder.CreateBr(Exit);
881
882 // Fill in the exit block.
883 Builder.SetInsertPoint(Exit);
884 Builder.CreateRetVoid();
885}
Bill Wendling2e6e8662012-09-13 00:09:55 +0000886
Bill Wendlingc3cab812013-03-18 23:04:39 +0000887Function *GCOVProfiler::
Bill Wendling2e6e8662012-09-13 00:09:55 +0000888insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
889 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingc3cab812013-03-18 23:04:39 +0000890 Function *FlushF = M->getFunction("__llvm_gcov_flush");
Bill Wendling2e6e8662012-09-13 00:09:55 +0000891 if (!FlushF)
892 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendlingc3cab812013-03-18 23:04:39 +0000893 "__llvm_gcov_flush", M);
Bill Wendling2e6e8662012-09-13 00:09:55 +0000894 else
895 FlushF->setLinkage(GlobalValue::InternalLinkage);
896 FlushF->setUnnamedAddr(true);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000897 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000898 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000899 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling2e6e8662012-09-13 00:09:55 +0000900
Bill Wendling2e6e8662012-09-13 00:09:55 +0000901 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
902
903 // Write out the current counters.
904 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
905 assert(WriteoutF && "Need to create the writeout function first!");
906
907 IRBuilder<> Builder(Entry);
908 Builder.CreateCall(WriteoutF);
909
Bill Wendlingfb1f6682012-09-13 14:32:30 +0000910 // Zero out the counters.
911 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
912 I = CountersBySP.begin(), E = CountersBySP.end();
913 I != E; ++I) {
914 GlobalVariable *GV = I->first;
915 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
Bill Wendling8d26bc32012-09-14 22:35:49 +0000916 Builder.CreateStore(Null, GV);
Bill Wendlingfb1f6682012-09-13 14:32:30 +0000917 }
Bill Wendling2e6e8662012-09-13 00:09:55 +0000918
919 Type *RetTy = FlushF->getReturnType();
920 if (RetTy == Type::getVoidTy(*Ctx))
921 Builder.CreateRetVoid();
922 else if (RetTy->isIntegerTy())
Bill Wendlingc3cab812013-03-18 23:04:39 +0000923 // Used if __llvm_gcov_flush was implicitly declared.
Bill Wendling2e6e8662012-09-13 00:09:55 +0000924 Builder.CreateRet(ConstantInt::get(RetTy, 0));
925 else
Bill Wendlingc3cab812013-03-18 23:04:39 +0000926 report_fatal_error("invalid return type for __llvm_gcov_flush");
927
928 return FlushF;
Bill Wendling2e6e8662012-09-13 00:09:55 +0000929}