blob: be6b40684c2015462d3196d6234bbcf0024c0559 [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 Carruth9a4c9e52014-03-06 00:46:21 +000027#include "llvm/IR/DebugInfo.h"
Chandler Carruth92051402014-03-05 10:30:38 +000028#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/IRBuilder.h"
Chandler Carruth83948572014-03-04 10:30:26 +000030#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Instructions.h"
Bob Wilson055a0b42014-01-31 05:24:01 +000032#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Module.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Pass.h"
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000035#include "llvm/Support/CommandLine.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000036#include "llvm/Support/Debug.h"
Bill Wendling5aa82392013-03-26 22:47:50 +000037#include "llvm/Support/FileSystem.h"
Rafael Espindola3bc8e712013-06-11 22:21:28 +000038#include "llvm/Support/Path.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000039#include "llvm/Support/raw_ostream.h"
40#include "llvm/Transforms/Utils/ModuleUtils.h"
Nick Lewycky0fdd0192013-06-18 06:38:21 +000041#include <algorithm>
Nick Lewycky966edd02011-04-16 01:20:23 +000042#include <string>
43#include <utility>
44using namespace llvm;
45
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000046static cl::opt<std::string>
47DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
48 cl::ValueRequired);
49
50GCOVOptions GCOVOptions::getDefault() {
51 GCOVOptions Options;
52 Options.EmitNotes = true;
53 Options.EmitData = true;
54 Options.UseCfgChecksum = false;
55 Options.NoRedZone = false;
56 Options.FunctionNamesInData = true;
57
58 if (DefaultGCOVVersion.size() != 4) {
59 llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
60 DefaultGCOVVersion);
61 }
62 memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
63 return Options;
64}
65
Nick Lewycky966edd02011-04-16 01:20:23 +000066namespace {
Yuchen Wubabe7492013-11-20 04:15:05 +000067 class GCOVFunction;
68
Nick Lewycky966edd02011-04-16 01:20:23 +000069 class GCOVProfiler : public ModulePass {
Nick Lewycky966edd02011-04-16 01:20:23 +000070 public:
71 static char ID;
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000072 GCOVProfiler() : ModulePass(ID), Options(GCOVOptions::getDefault()) {
Yuchen Wubabe7492013-11-20 04:15:05 +000073 init();
Nick Lewycky8e0a38f2011-04-21 01:56:25 +000074 }
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000075 GCOVProfiler(const GCOVOptions &Options) : ModulePass(ID), Options(Options){
76 assert((Options.EmitNotes || Options.EmitData) &&
77 "GCOVProfiler asked to do nothing?");
Yuchen Wubabe7492013-11-20 04:15:05 +000078 init();
79 }
80 ~GCOVProfiler() {
81 DeleteContainerPointers(Funcs);
Nick Lewycky966edd02011-04-16 01:20:23 +000082 }
Craig Topper3e4c6972014-03-05 09:10:37 +000083 const char *getPassName() const override {
Nick Lewycky966edd02011-04-16 01:20:23 +000084 return "GCOV Profiler";
85 }
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +000086
Nick Lewycky966edd02011-04-16 01:20:23 +000087 private:
Yuchen Wubabe7492013-11-20 04:15:05 +000088 void init() {
89 ReversedVersion[0] = Options.Version[3];
90 ReversedVersion[1] = Options.Version[2];
91 ReversedVersion[2] = Options.Version[1];
92 ReversedVersion[3] = Options.Version[0];
93 ReversedVersion[4] = '\0';
94 initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
95 }
Craig Topper3e4c6972014-03-05 09:10:37 +000096 bool runOnModule(Module &M) override;
Nick Lewycky6d9f0612011-05-04 04:03:04 +000097
Nick Lewyckyad145502013-03-13 22:55:42 +000098 // Create the .gcno files for the Module based on DebugInfo.
99 void emitProfileNotes();
Nick Lewycky966edd02011-04-16 01:20:23 +0000100
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000101 // Modify the program to track transitions along edges and call into the
102 // profiling runtime to emit .gcda files when run.
Devang Patel2b21d862011-08-17 22:49:38 +0000103 bool emitProfileArcs();
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000104
Nick Lewycky966edd02011-04-16 01:20:23 +0000105 // Get pointers to the functions in the runtime library.
106 Constant *getStartFileFunc();
Bill Wendling15605172012-05-28 06:10:56 +0000107 Constant *getIncrementIndirectCounterFunc();
Nick Lewycky966edd02011-04-16 01:20:23 +0000108 Constant *getEmitFunctionFunc();
109 Constant *getEmitArcsFunc();
Yuchen Wu062f24c2013-11-12 04:59:08 +0000110 Constant *getSummaryInfoFunc();
Bill Wendling04d57c72013-03-19 21:03:22 +0000111 Constant *getDeleteWriteoutFunctionListFunc();
Bill Wendlingc3cab812013-03-18 23:04:39 +0000112 Constant *getDeleteFlushFunctionListFunc();
Nick Lewycky966edd02011-04-16 01:20:23 +0000113 Constant *getEndFileFunc();
114
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000115 // Create or retrieve an i32 state value that is used to represent the
116 // pred block number for certain non-trivial edges.
117 GlobalVariable *getEdgeStateValue();
118
119 // Produce a table of pointers to counters, by predecessor and successor
120 // block number.
121 GlobalVariable *buildEdgeLookupTable(Function *F,
122 GlobalVariable *Counter,
Nick Lewyckyad145502013-03-13 22:55:42 +0000123 const UniqueVector<BasicBlock *>&Preds,
124 const UniqueVector<BasicBlock*>&Succs);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000125
Nick Lewycky966edd02011-04-16 01:20:23 +0000126 // Add the function to write out all our counters to the global destructor
127 // list.
Bill Wendlingc3cab812013-03-18 23:04:39 +0000128 Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
129 MDNode*> >);
130 Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
Bill Wendling15605172012-05-28 06:10:56 +0000131 void insertIndirectCounterIncrement();
Nick Lewycky966edd02011-04-16 01:20:23 +0000132
Bill Wendling85722f42013-03-28 22:40:08 +0000133 std::string mangleName(DICompileUnit CU, const char *NewStem);
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000134
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000135 GCOVOptions Options;
136
137 // Reversed, NUL-terminated copy of Options.Version.
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000138 char ReversedVersion[5];
Yuchen Wubabe7492013-11-20 04:15:05 +0000139 // Checksum, produced by hash of EdgeDestinations
Yuchen Wu664dc762013-11-21 04:01:05 +0000140 SmallVector<uint32_t, 4> FileChecksums;
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000141
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000142 Module *M;
Nick Lewycky966edd02011-04-16 01:20:23 +0000143 LLVMContext *Ctx;
Yuchen Wubabe7492013-11-20 04:15:05 +0000144 SmallVector<GCOVFunction *, 16> Funcs;
Nick Lewycky966edd02011-04-16 01:20:23 +0000145 };
146}
147
148char GCOVProfiler::ID = 0;
149INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
150 "Insert instrumentation for GCOV profiling", false, false)
151
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000152ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
153 return new GCOVProfiler(Options);
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000154}
Nick Lewycky966edd02011-04-16 01:20:23 +0000155
Yuchen Wubabe7492013-11-20 04:15:05 +0000156static StringRef getFunctionName(DISubprogram SP) {
Nick Lewyckyd6718632013-03-19 01:37:55 +0000157 if (!SP.getLinkageName().empty())
158 return SP.getLinkageName();
159 return SP.getName();
160}
161
Nick Lewycky966edd02011-04-16 01:20:23 +0000162namespace {
163 class GCOVRecord {
164 protected:
Craig Topper1c4d6672013-07-17 03:43:10 +0000165 static const char *const LinesTag;
166 static const char *const FunctionTag;
167 static const char *const BlockTag;
168 static const char *const EdgeTag;
Nick Lewycky966edd02011-04-16 01:20:23 +0000169
170 GCOVRecord() {}
171
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000172 void writeBytes(const char *Bytes, int Size) {
173 os->write(Bytes, Size);
Nick Lewycky966edd02011-04-16 01:20:23 +0000174 }
175
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000176 void write(uint32_t i) {
177 writeBytes(reinterpret_cast<char*>(&i), 4);
Nick Lewycky966edd02011-04-16 01:20:23 +0000178 }
179
180 // Returns the length measured in 4-byte blocks that will be used to
181 // represent this string in a GCOV file
Craig Topper24048c92013-07-17 03:54:53 +0000182 static unsigned lengthOfGCOVString(StringRef s) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000183 // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
Nick Lewyckyed749d82011-04-21 02:48:39 +0000184 // padding out to the next 4-byte word. The length is measured in 4-byte
185 // words including padding, not bytes of actual string.
Nick Lewyckya7028842011-05-05 23:52:18 +0000186 return (s.size() / 4) + 1;
Nick Lewycky966edd02011-04-16 01:20:23 +0000187 }
188
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000189 void writeGCOVString(StringRef s) {
190 uint32_t Len = lengthOfGCOVString(s);
191 write(Len);
192 writeBytes(s.data(), s.size());
Nick Lewycky966edd02011-04-16 01:20:23 +0000193
194 // Write 1 to 4 bytes of NUL padding.
Nick Lewycky6aa79492011-04-28 21:35:49 +0000195 assert((unsigned)(4 - (s.size() % 4)) > 0);
196 assert((unsigned)(4 - (s.size() % 4)) <= 4);
197 writeBytes("\0\0\0\0", 4 - (s.size() % 4));
Nick Lewycky966edd02011-04-16 01:20:23 +0000198 }
199
200 raw_ostream *os;
201 };
Craig Topper1c4d6672013-07-17 03:43:10 +0000202 const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
203 const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
204 const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
205 const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
Nick Lewycky966edd02011-04-16 01:20:23 +0000206
207 class GCOVFunction;
208 class GCOVBlock;
209
210 // Constructed only by requesting it from a GCOVBlock, this object stores a
Devang Pateladd1f172011-09-20 18:35:00 +0000211 // list of line numbers and a single filename, representing lines that belong
212 // to the block.
Nick Lewycky966edd02011-04-16 01:20:23 +0000213 class GCOVLines : public GCOVRecord {
214 public:
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000215 void addLine(uint32_t Line) {
216 Lines.push_back(Line);
Nick Lewycky966edd02011-04-16 01:20:23 +0000217 }
218
Craig Topper24048c92013-07-17 03:54:53 +0000219 uint32_t length() const {
Nick Lewycky6404d972011-11-27 23:22:20 +0000220 // Here 2 = 1 for string length + 1 for '0' id#.
Devang Pateladd1f172011-09-20 18:35:00 +0000221 return lengthOfGCOVString(Filename) + 2 + Lines.size();
Nick Lewycky966edd02011-04-16 01:20:23 +0000222 }
223
Devang Pateladd1f172011-09-20 18:35:00 +0000224 void writeOut() {
225 write(0);
226 writeGCOVString(Filename);
227 for (int i = 0, e = Lines.size(); i != e; ++i)
228 write(Lines[i]);
229 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000230
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000231 GCOVLines(StringRef F, raw_ostream *os)
Devang Pateladd1f172011-09-20 18:35:00 +0000232 : Filename(F) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000233 this->os = os;
234 }
235
Devang Patel7d06f5c2011-09-20 18:48:56 +0000236 private:
Devang Pateladd1f172011-09-20 18:35:00 +0000237 StringRef Filename;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000238 SmallVector<uint32_t, 32> Lines;
Nick Lewycky966edd02011-04-16 01:20:23 +0000239 };
240
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000241
Nick Lewycky966edd02011-04-16 01:20:23 +0000242 // Represent a basic block in GCOV. Each block has a unique number in the
243 // function, number of lines belonging to each block, and a set of edges to
244 // other blocks.
245 class GCOVBlock : public GCOVRecord {
246 public:
Devang Patel9cb1fc02011-09-20 17:55:19 +0000247 GCOVLines &getFile(StringRef Filename) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000248 GCOVLines *&Lines = LinesByFile[Filename];
249 if (!Lines) {
Devang Pateladd1f172011-09-20 18:35:00 +0000250 Lines = new GCOVLines(Filename, os);
Nick Lewycky966edd02011-04-16 01:20:23 +0000251 }
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000252 return *Lines;
Nick Lewycky966edd02011-04-16 01:20:23 +0000253 }
254
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000255 void addEdge(GCOVBlock &Successor) {
256 OutEdges.push_back(&Successor);
Nick Lewycky966edd02011-04-16 01:20:23 +0000257 }
258
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000259 void writeOut() {
260 uint32_t Len = 3;
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000261 SmallVector<StringMapEntry<GCOVLines *> *, 32> SortedLinesByFile;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000262 for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
263 E = LinesByFile.end(); I != E; ++I) {
Devang Pateladd1f172011-09-20 18:35:00 +0000264 Len += I->second->length();
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000265 SortedLinesByFile.push_back(&*I);
Nick Lewycky966edd02011-04-16 01:20:23 +0000266 }
267
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000268 writeBytes(LinesTag, 4);
269 write(Len);
270 write(Number);
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000271
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000272 std::sort(SortedLinesByFile.begin(), SortedLinesByFile.end(),
273 [](StringMapEntry<GCOVLines *> *LHS,
274 StringMapEntry<GCOVLines *> *RHS) {
275 return LHS->getKey() < RHS->getKey();
276 });
Craig Topperaf0dea12013-07-04 01:31:24 +0000277 for (SmallVectorImpl<StringMapEntry<GCOVLines *> *>::iterator
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000278 I = SortedLinesByFile.begin(), E = SortedLinesByFile.end();
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000279 I != E; ++I)
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000280 (*I)->getValue()->writeOut();
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000281 write(0);
282 write(0);
Nick Lewycky966edd02011-04-16 01:20:23 +0000283 }
284
285 ~GCOVBlock() {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000286 DeleteContainerSeconds(LinesByFile);
Nick Lewycky966edd02011-04-16 01:20:23 +0000287 }
288
289 private:
290 friend class GCOVFunction;
291
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000292 GCOVBlock(uint32_t Number, raw_ostream *os)
293 : Number(Number) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000294 this->os = os;
295 }
296
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000297 uint32_t Number;
298 StringMap<GCOVLines *> LinesByFile;
299 SmallVector<GCOVBlock *, 4> OutEdges;
Nick Lewycky966edd02011-04-16 01:20:23 +0000300 };
301
302 // A function has a unique identifier, a checksum (we leave as zero) and a
303 // set of blocks and a map of edges between blocks. This is the only GCOV
304 // object users can construct, the blocks and lines will be rooted here.
305 class GCOVFunction : public GCOVRecord {
306 public:
Nick Lewycky492afe82013-03-07 08:28:49 +0000307 GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
Yuchen Wubabe7492013-11-20 04:15:05 +0000308 bool UseCfgChecksum) :
309 SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0) {
Nick Lewycky966edd02011-04-16 01:20:23 +0000310 this->os = os;
311
312 Function *F = SP.getFunction();
Daniel Jasper87a24d52013-12-04 08:57:17 +0000313 DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
Nick Lewycky966edd02011-04-16 01:20:23 +0000314 uint32_t i = 0;
315 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000316 Blocks[BB] = new GCOVBlock(i++, os);
Nick Lewycky966edd02011-04-16 01:20:23 +0000317 }
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000318 ReturnBlock = new GCOVBlock(i++, os);
Daniel Jasper87a24d52013-12-04 08:57:17 +0000319
320 std::string FunctionNameAndLine;
321 raw_string_ostream FNLOS(FunctionNameAndLine);
322 FNLOS << getFunctionName(SP) << SP.getLineNumber();
323 FNLOS.flush();
324 FuncChecksum = hash_value(FunctionNameAndLine);
Nick Lewycky966edd02011-04-16 01:20:23 +0000325 }
326
327 ~GCOVFunction() {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000328 DeleteContainerSeconds(Blocks);
329 delete ReturnBlock;
Nick Lewycky966edd02011-04-16 01:20:23 +0000330 }
331
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000332 GCOVBlock &getBlock(BasicBlock *BB) {
333 return *Blocks[BB];
Nick Lewycky966edd02011-04-16 01:20:23 +0000334 }
335
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000336 GCOVBlock &getReturnBlock() {
337 return *ReturnBlock;
Nick Lewycky8411b552011-04-21 03:18:00 +0000338 }
339
Yuchen Wubabe7492013-11-20 04:15:05 +0000340 std::string getEdgeDestinations() {
341 std::string EdgeDestinations;
342 raw_string_ostream EDOS(EdgeDestinations);
343 Function *F = Blocks.begin()->first->getParent();
344 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
345 GCOVBlock &Block = *Blocks[I];
346 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
347 EDOS << Block.OutEdges[i]->Number;
348 }
349 return EdgeDestinations;
350 }
351
Daniel Jasper87a24d52013-12-04 08:57:17 +0000352 uint32_t getFuncChecksum() {
353 return FuncChecksum;
354 }
355
Yuchen Wubabe7492013-11-20 04:15:05 +0000356 void setCfgChecksum(uint32_t Checksum) {
357 CfgChecksum = Checksum;
358 }
359
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000360 void writeOut() {
Yuchen Wubabe7492013-11-20 04:15:05 +0000361 writeBytes(FunctionTag, 4);
362 uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
363 1 + lengthOfGCOVString(SP.getFilename()) + 1;
364 if (UseCfgChecksum)
365 ++BlockLen;
366 write(BlockLen);
367 write(Ident);
Daniel Jasper87a24d52013-12-04 08:57:17 +0000368 write(FuncChecksum);
Yuchen Wubabe7492013-11-20 04:15:05 +0000369 if (UseCfgChecksum)
370 write(CfgChecksum);
371 writeGCOVString(getFunctionName(SP));
372 writeGCOVString(SP.getFilename());
373 write(SP.getLineNumber());
374
Nick Lewycky966edd02011-04-16 01:20:23 +0000375 // Emit count of blocks.
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000376 writeBytes(BlockTag, 4);
377 write(Blocks.size() + 1);
378 for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
379 write(0); // No flags on our blocks.
Nick Lewycky966edd02011-04-16 01:20:23 +0000380 }
Nick Lewycky6404d972011-11-27 23:22:20 +0000381 DEBUG(dbgs() << Blocks.size() << " blocks.\n");
Nick Lewycky966edd02011-04-16 01:20:23 +0000382
383 // Emit edges between blocks.
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000384 if (Blocks.empty()) return;
385 Function *F = Blocks.begin()->first->getParent();
386 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
387 GCOVBlock &Block = *Blocks[I];
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000388 if (Block.OutEdges.empty()) continue;
Nick Lewycky966edd02011-04-16 01:20:23 +0000389
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000390 writeBytes(EdgeTag, 4);
391 write(Block.OutEdges.size() * 2 + 1);
392 write(Block.Number);
393 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
Nick Lewycky6404d972011-11-27 23:22:20 +0000394 DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
395 << "\n");
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000396 write(Block.OutEdges[i]->Number);
397 write(0); // no flags
Nick Lewycky966edd02011-04-16 01:20:23 +0000398 }
399 }
400
401 // Emit lines for each block.
Nick Lewycky0fdd0192013-06-18 06:38:21 +0000402 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
403 Blocks[I]->writeOut();
Nick Lewycky966edd02011-04-16 01:20:23 +0000404 }
405 }
406
407 private:
Yuchen Wubabe7492013-11-20 04:15:05 +0000408 DISubprogram SP;
409 uint32_t Ident;
Daniel Jasper87a24d52013-12-04 08:57:17 +0000410 uint32_t FuncChecksum;
Yuchen Wubabe7492013-11-20 04:15:05 +0000411 bool UseCfgChecksum;
412 uint32_t CfgChecksum;
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000413 DenseMap<BasicBlock *, GCOVBlock *> Blocks;
414 GCOVBlock *ReturnBlock;
Nick Lewycky966edd02011-04-16 01:20:23 +0000415 };
416}
417
Bill Wendling85722f42013-03-28 22:40:08 +0000418std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000419 if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
420 for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
421 MDNode *N = GCov->getOperand(i);
422 if (N->getNumOperands() != 2) continue;
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000423 MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000424 MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000425 if (!GCovFile || !CompileUnit) continue;
426 if (CompileUnit == CU) {
Bill Wendling1f6f8c22012-08-30 00:34:21 +0000427 SmallString<128> Filename = GCovFile->getString();
428 sys::path::replace_extension(Filename, NewStem);
429 return Filename.str();
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000430 }
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000431 }
432 }
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000433
Bill Wendling1f6f8c22012-08-30 00:34:21 +0000434 SmallString<128> Filename = CU.getFilename();
Nick Lewyckya3d5d162011-05-05 00:03:30 +0000435 sys::path::replace_extension(Filename, NewStem);
Bill Wendling5aa82392013-03-26 22:47:50 +0000436 StringRef FName = sys::path::filename(Filename);
Bill Wendling5aa82392013-03-26 22:47:50 +0000437 SmallString<128> CurPath;
438 if (sys::fs::current_path(CurPath)) return FName;
439 sys::path::append(CurPath, FName.str());
440 return CurPath.str();
Nick Lewycky6d9f0612011-05-04 04:03:04 +0000441}
442
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000443bool GCOVProfiler::runOnModule(Module &M) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000444 this->M = &M;
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000445 Ctx = &M.getContext();
446
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000447 if (Options.EmitNotes) emitProfileNotes();
448 if (Options.EmitData) return emitProfileArcs();
Nick Lewycky8e0a38f2011-04-21 01:56:25 +0000449 return false;
Nick Lewyckyc5ea8522011-04-16 02:05:18 +0000450}
451
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000452static bool functionHasLines(Function *F) {
453 // Check whether this function actually has any source lines. Not only
454 // do these waste space, they also can crash gcov.
455 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
456 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
457 I != IE; ++I) {
458 const DebugLoc &Loc = I->getDebugLoc();
459 if (Loc.isUnknown()) continue;
460 if (Loc.getLine() != 0)
461 return true;
462 }
463 }
464 return false;
465}
466
Nick Lewyckyad145502013-03-13 22:55:42 +0000467void GCOVProfiler::emitProfileNotes() {
Devang Patel2b21d862011-08-17 22:49:38 +0000468 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
Nick Lewycky6404d972011-11-27 23:22:20 +0000469 if (!CU_Nodes) return;
Nick Lewycky966edd02011-04-16 01:20:23 +0000470
Nick Lewycky6404d972011-11-27 23:22:20 +0000471 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
472 // Each compile unit gets its own .gcno file. This means that whether we run
473 // this pass over the original .o's as they're produced, or run it after
474 // LTO, we'll generate the same .gcno files.
475
476 DICompileUnit CU(CU_Nodes->getOperand(i));
477 std::string ErrorInfo;
Bill Wendling85722f42013-03-28 22:40:08 +0000478 raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000479 sys::fs::F_None);
Yuchen Wubabe7492013-11-20 04:15:05 +0000480 std::string EdgeDestinations;
Nick Lewycky6404d972011-11-27 23:22:20 +0000481
482 DIArray SPs = CU.getSubprograms();
483 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
484 DISubprogram SP(SPs.getElement(i));
Manman Ren983a16c2013-06-28 05:43:10 +0000485 assert((!SP || SP.isSubprogram()) &&
486 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
487 if (!SP)
488 continue;
Nick Lewycky6404d972011-11-27 23:22:20 +0000489
490 Function *F = SP.getFunction();
491 if (!F) continue;
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000492 if (!functionHasLines(F)) continue;
Bob Wilson055a0b42014-01-31 05:24:01 +0000493
494 // gcov expects every function to start with an entry block that has a
495 // single successor, so split the entry block to make sure of that.
Yuchen Wuc87ca322013-11-22 23:07:45 +0000496 BasicBlock &EntryBlock = F->getEntryBlock();
Bob Wilson055a0b42014-01-31 05:24:01 +0000497 BasicBlock::iterator It = EntryBlock.begin();
498 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
499 ++It;
500 EntryBlock.splitBasicBlock(It);
Yuchen Wuc87ca322013-11-22 23:07:45 +0000501
Yuchen Wubabe7492013-11-20 04:15:05 +0000502 GCOVFunction *Func =
503 new GCOVFunction(SP, &out, i, Options.UseCfgChecksum);
504 Funcs.push_back(Func);
Nick Lewycky6404d972011-11-27 23:22:20 +0000505
506 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Yuchen Wubabe7492013-11-20 04:15:05 +0000507 GCOVBlock &Block = Func->getBlock(BB);
Nick Lewycky6404d972011-11-27 23:22:20 +0000508 TerminatorInst *TI = BB->getTerminator();
509 if (int successors = TI->getNumSuccessors()) {
510 for (int i = 0; i != successors; ++i) {
Yuchen Wubabe7492013-11-20 04:15:05 +0000511 Block.addEdge(Func->getBlock(TI->getSuccessor(i)));
Nick Lewycky6404d972011-11-27 23:22:20 +0000512 }
513 } else if (isa<ReturnInst>(TI)) {
Yuchen Wubabe7492013-11-20 04:15:05 +0000514 Block.addEdge(Func->getReturnBlock());
Nick Lewycky6404d972011-11-27 23:22:20 +0000515 }
516
517 uint32_t Line = 0;
518 for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
519 I != IE; ++I) {
520 const DebugLoc &Loc = I->getDebugLoc();
521 if (Loc.isUnknown()) continue;
522 if (Line == Loc.getLine()) continue;
523 Line = Loc.getLine();
524 if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
525
526 GCOVLines &Lines = Block.getFile(SP.getFilename());
527 Lines.addLine(Loc.getLine());
528 }
529 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000530 EdgeDestinations += Func->getEdgeDestinations();
Nick Lewycky6404d972011-11-27 23:22:20 +0000531 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000532
Yuchen Wu664dc762013-11-21 04:01:05 +0000533 FileChecksums.push_back(hash_value(EdgeDestinations));
Yuchen Wubabe7492013-11-20 04:15:05 +0000534 out.write("oncg", 4);
535 out.write(ReversedVersion, 4);
Yuchen Wu664dc762013-11-21 04:01:05 +0000536 out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
Yuchen Wubabe7492013-11-20 04:15:05 +0000537
538 for (SmallVectorImpl<GCOVFunction *>::iterator I = Funcs.begin(),
Yuchen Wu664dc762013-11-21 04:01:05 +0000539 E = Funcs.end(); I != E; ++I) {
540 GCOVFunction *Func = *I;
541 Func->setCfgChecksum(FileChecksums.back());
542 Func->writeOut();
543 }
Yuchen Wubabe7492013-11-20 04:15:05 +0000544
Nick Lewycky6404d972011-11-27 23:22:20 +0000545 out.write("\0\0\0\0\0\0\0\0", 8); // EOF
546 out.close();
Nick Lewycky966edd02011-04-16 01:20:23 +0000547 }
548}
549
Devang Patel2b21d862011-08-17 22:49:38 +0000550bool GCOVProfiler::emitProfileArcs() {
551 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
552 if (!CU_Nodes) return false;
Nick Lewycky966edd02011-04-16 01:20:23 +0000553
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000554 bool Result = false;
Bill Wendling15605172012-05-28 06:10:56 +0000555 bool InsertIndCounterIncrCode = false;
Devang Patel2b21d862011-08-17 22:49:38 +0000556 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
557 DICompileUnit CU(CU_Nodes->getOperand(i));
558 DIArray SPs = CU.getSubprograms();
559 SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
560 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
561 DISubprogram SP(SPs.getElement(i));
Manman Ren983a16c2013-06-28 05:43:10 +0000562 assert((!SP || SP.isSubprogram()) &&
563 "A MDNode in subprograms of a CU should be null or a DISubprogram.");
564 if (!SP)
565 continue;
Devang Patel2b21d862011-08-17 22:49:38 +0000566 Function *F = SP.getFunction();
567 if (!F) continue;
Nick Lewycky05e0f1c2014-04-18 23:32:28 +0000568 if (!functionHasLines(F)) continue;
Devang Patel2b21d862011-08-17 22:49:38 +0000569 if (!Result) Result = true;
570 unsigned Edges = 0;
571 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
572 TerminatorInst *TI = BB->getTerminator();
573 if (isa<ReturnInst>(TI))
574 ++Edges;
575 else
576 Edges += TI->getNumSuccessors();
577 }
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000578
Devang Patel2b21d862011-08-17 22:49:38 +0000579 ArrayType *CounterTy =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000580 ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
Devang Patel2b21d862011-08-17 22:49:38 +0000581 GlobalVariable *Counters =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000582 new GlobalVariable(*M, CounterTy, false,
Nick Lewycky966edd02011-04-16 01:20:23 +0000583 GlobalValue::InternalLinkage,
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000584 Constant::getNullValue(CounterTy),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000585 "__llvm_gcov_ctr");
Devang Patel2b21d862011-08-17 22:49:38 +0000586 CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000587
Devang Patel2b21d862011-08-17 22:49:38 +0000588 UniqueVector<BasicBlock *> ComplexEdgePreds;
589 UniqueVector<BasicBlock *> ComplexEdgeSuccs;
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000590
Devang Patel2b21d862011-08-17 22:49:38 +0000591 unsigned Edge = 0;
592 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
593 TerminatorInst *TI = BB->getTerminator();
594 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
595 if (Successors) {
Devang Patel2b21d862011-08-17 22:49:38 +0000596 if (Successors == 1) {
Bill Wendling707f6012013-08-20 23:52:00 +0000597 IRBuilder<> Builder(BB->getFirstInsertionPt());
Devang Patel2b21d862011-08-17 22:49:38 +0000598 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
599 Edge);
600 Value *Count = Builder.CreateLoad(Counter);
Nick Lewycky8e94d802013-02-27 05:46:30 +0000601 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patel2b21d862011-08-17 22:49:38 +0000602 Builder.CreateStore(Count, Counter);
603 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Bill Wendling707f6012013-08-20 23:52:00 +0000604 IRBuilder<> Builder(BI);
Nick Lewycky8e94d802013-02-27 05:46:30 +0000605 Value *Sel = Builder.CreateSelect(BI->getCondition(),
606 Builder.getInt64(Edge),
607 Builder.getInt64(Edge + 1));
Devang Patel2b21d862011-08-17 22:49:38 +0000608 SmallVector<Value *, 2> Idx;
Nick Lewycky8e94d802013-02-27 05:46:30 +0000609 Idx.push_back(Builder.getInt64(0));
Devang Patel2b21d862011-08-17 22:49:38 +0000610 Idx.push_back(Sel);
611 Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
612 Value *Count = Builder.CreateLoad(Counter);
Nick Lewycky8e94d802013-02-27 05:46:30 +0000613 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Devang Patel2b21d862011-08-17 22:49:38 +0000614 Builder.CreateStore(Count, Counter);
615 } else {
616 ComplexEdgePreds.insert(BB);
617 for (int i = 0; i != Successors; ++i)
618 ComplexEdgeSuccs.insert(TI->getSuccessor(i));
619 }
Bill Wendling707f6012013-08-20 23:52:00 +0000620
Devang Patel2b21d862011-08-17 22:49:38 +0000621 Edge += Successors;
Nick Lewycky966edd02011-04-16 01:20:23 +0000622 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000623 }
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000624
Devang Patel2b21d862011-08-17 22:49:38 +0000625 if (!ComplexEdgePreds.empty()) {
626 GlobalVariable *EdgeTable =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000627 buildEdgeLookupTable(F, Counters,
628 ComplexEdgePreds, ComplexEdgeSuccs);
Devang Patel2b21d862011-08-17 22:49:38 +0000629 GlobalVariable *EdgeState = getEdgeStateValue();
Duncan P. N. Exon Smithcec1c242014-03-11 02:44:45 +0000630
Devang Patel2b21d862011-08-17 22:49:38 +0000631 for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
Bill Wendling707f6012013-08-20 23:52:00 +0000632 IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
Nick Lewycky8e94d802013-02-27 05:46:30 +0000633 Builder.CreateStore(Builder.getInt32(i), EdgeState);
Devang Patel2b21d862011-08-17 22:49:38 +0000634 }
Bill Wendling707f6012013-08-20 23:52:00 +0000635
Devang Patel2b21d862011-08-17 22:49:38 +0000636 for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
Bill Wendling707f6012013-08-20 23:52:00 +0000637 // Call runtime to perform increment.
638 IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
Devang Patel2b21d862011-08-17 22:49:38 +0000639 Value *CounterPtrArray =
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000640 Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
641 i * ComplexEdgePreds.size());
Bill Wendling8ed07492012-05-25 23:55:00 +0000642
643 // Build code to increment the counter.
Bill Wendling15605172012-05-28 06:10:56 +0000644 InsertIndCounterIncrCode = true;
645 Builder.CreateCall2(getIncrementIndirectCounterFunc(),
646 EdgeState, CounterPtrArray);
Devang Patel2b21d862011-08-17 22:49:38 +0000647 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000648 }
649 }
Bill Wendlinge85f3492012-06-01 23:14:32 +0000650
Bill Wendlingc3cab812013-03-18 23:04:39 +0000651 Function *WriteoutF = insertCounterWriteout(CountersBySP);
652 Function *FlushF = insertFlush(CountersBySP);
653
654 // Create a small bit of code that registers the "__llvm_gcov_writeout" to
Bill Wendling04d57c72013-03-19 21:03:22 +0000655 // be executed at exit and the "__llvm_gcov_flush" function to be executed
656 // when "__gcov_flush" is called.
Bill Wendlingc3cab812013-03-18 23:04:39 +0000657 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
658 Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
659 "__llvm_gcov_init", M);
660 F->setUnnamedAddr(true);
661 F->setLinkage(GlobalValue::InternalLinkage);
662 F->addFnAttr(Attribute::NoInline);
663 if (Options.NoRedZone)
664 F->addFnAttr(Attribute::NoRedZone);
665
666 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
667 IRBuilder<> Builder(BB);
668
Bill Wendlingc3cab812013-03-18 23:04:39 +0000669 FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingc77e9442013-03-20 21:13:59 +0000670 Type *Params[] = {
671 PointerType::get(FTy, 0),
672 PointerType::get(FTy, 0)
673 };
674 FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
Bill Wendling04d57c72013-03-19 21:03:22 +0000675
Yuchen Wu3197b252013-10-23 20:35:00 +0000676 // Initialize the environment and register the local writeout and flush
Bill Wendlingc77e9442013-03-20 21:13:59 +0000677 // functions.
678 Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
679 Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
Bill Wendlingc3cab812013-03-18 23:04:39 +0000680 Builder.CreateRetVoid();
681
682 appendToGlobalCtors(*M, F, 0);
Nick Lewycky966edd02011-04-16 01:20:23 +0000683 }
Bill Wendling15605172012-05-28 06:10:56 +0000684
685 if (InsertIndCounterIncrCode)
686 insertIndirectCounterIncrement();
687
Devang Patel2b21d862011-08-17 22:49:38 +0000688 return Result;
Nick Lewycky966edd02011-04-16 01:20:23 +0000689}
690
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000691// All edges with successors that aren't branches are "complex", because it
692// requires complex logic to pick which counter to update.
693GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
694 Function *F,
695 GlobalVariable *Counters,
696 const UniqueVector<BasicBlock *> &Preds,
697 const UniqueVector<BasicBlock *> &Succs) {
698 // TODO: support invoke, threads. We rely on the fact that nothing can modify
699 // the whole-Module pred edge# between the time we set it and the time we next
700 // read it. Threads and invoke make this untrue.
701
702 // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
Benjamin Kramer96e1e392012-11-17 13:49:37 +0000703 size_t TableSize = Succs.size() * Preds.size();
Chris Lattner229907c2011-07-18 04:54:35 +0000704 Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
Benjamin Kramer96e1e392012-11-17 13:49:37 +0000705 ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000706
Ahmed Charles56440fd2014-03-06 05:51:42 +0000707 std::unique_ptr<Constant * []> EdgeTable(new Constant *[TableSize]);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000708 Constant *NullValue = Constant::getNullValue(Int64PtrTy);
Benjamin Kramer96e1e392012-11-17 13:49:37 +0000709 for (size_t i = 0; i != TableSize; ++i)
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000710 EdgeTable[i] = NullValue;
711
712 unsigned Edge = 0;
713 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
714 TerminatorInst *TI = BB->getTerminator();
715 int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
Nick Lewycky6aa79492011-04-28 21:35:49 +0000716 if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000717 for (int i = 0; i != Successors; ++i) {
718 BasicBlock *Succ = TI->getSuccessor(i);
Nick Lewycky8e94d802013-02-27 05:46:30 +0000719 IRBuilder<> Builder(Succ);
720 Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000721 Edge + i);
722 EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
723 (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
724 }
725 }
726 Edge += Successors;
727 }
728
Benjamin Kramer96e1e392012-11-17 13:49:37 +0000729 ArrayRef<Constant*> V(&EdgeTable[0], TableSize);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000730 GlobalVariable *EdgeTableGV =
731 new GlobalVariable(
732 *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
Jay Foad83be3612011-06-22 09:24:39 +0000733 ConstantArray::get(EdgeTableTy, V),
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000734 "__llvm_gcda_edge_table");
735 EdgeTableGV->setUnnamedAddr(true);
736 return EdgeTableGV;
737}
738
Nick Lewycky966edd02011-04-16 01:20:23 +0000739Constant *GCOVProfiler::getStartFileFunc() {
Nick Lewycky492afe82013-03-07 08:28:49 +0000740 Type *Args[] = {
741 Type::getInt8PtrTy(*Ctx), // const char *orig_filename
742 Type::getInt8PtrTy(*Ctx), // const char version[4]
Yuchen Wubabe7492013-11-20 04:15:05 +0000743 Type::getInt32Ty(*Ctx), // uint32_t checksum
Nick Lewycky492afe82013-03-07 08:28:49 +0000744 };
745 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000746 return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
747}
748
Bill Wendling15605172012-05-28 06:10:56 +0000749Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
750 Type *Int32Ty = Type::getInt32Ty(*Ctx);
Bill Wendling8ed07492012-05-25 23:55:00 +0000751 Type *Int64Ty = Type::getInt64Ty(*Ctx);
Bill Wendling15605172012-05-28 06:10:56 +0000752 Type *Args[] = {
Micah Villmow51e72462012-10-24 17:25:11 +0000753 Int32Ty->getPointerTo(), // uint32_t *predecessor
754 Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
Bill Wendling15605172012-05-28 06:10:56 +0000755 };
756 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
757 return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000758}
759
760Constant *GCOVProfiler::getEmitFunctionFunc() {
Yuchen Wubabe7492013-11-20 04:15:05 +0000761 Type *Args[] = {
Nick Lewycky4f9c3672011-05-05 02:46:38 +0000762 Type::getInt32Ty(*Ctx), // uint32_t ident
763 Type::getInt8PtrTy(*Ctx), // const char *function_name
Daniel Jasper87a24d52013-12-04 08:57:17 +0000764 Type::getInt32Ty(*Ctx), // uint32_t func_checksum
Nick Lewycky88f1d0d2013-03-09 01:33:06 +0000765 Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
Yuchen Wubabe7492013-11-20 04:15:05 +0000766 Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
Nick Lewycky4f9c3672011-05-05 02:46:38 +0000767 };
Bill Wendling8ed07492012-05-25 23:55:00 +0000768 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000769 return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000770}
771
772Constant *GCOVProfiler::getEmitArcsFunc() {
Jay Foadb804a2b2011-07-12 14:06:48 +0000773 Type *Args[] = {
Nick Lewycky966edd02011-04-16 01:20:23 +0000774 Type::getInt32Ty(*Ctx), // uint32_t num_counters
775 Type::getInt64PtrTy(*Ctx), // uint64_t *counters
776 };
Nick Lewycky492afe82013-03-07 08:28:49 +0000777 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000778 return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000779}
780
Yuchen Wu062f24c2013-11-12 04:59:08 +0000781Constant *GCOVProfiler::getSummaryInfoFunc() {
782 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
783 return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
784}
785
Bill Wendling04d57c72013-03-19 21:03:22 +0000786Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
787 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
788 return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
789}
790
Bill Wendlingc3cab812013-03-18 23:04:39 +0000791Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
792 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
793 return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
794}
795
Nick Lewycky966edd02011-04-16 01:20:23 +0000796Constant *GCOVProfiler::getEndFileFunc() {
Chris Lattner229907c2011-07-18 04:54:35 +0000797 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000798 return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
Nick Lewycky966edd02011-04-16 01:20:23 +0000799}
800
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000801GlobalVariable *GCOVProfiler::getEdgeStateValue() {
802 GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
803 if (!GV) {
804 GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
805 GlobalValue::InternalLinkage,
806 ConstantInt::get(Type::getInt32Ty(*Ctx),
807 0xffffffff),
808 "__llvm_gcov_global_state_pred");
809 GV->setUnnamedAddr(true);
810 }
811 return GV;
812}
Nick Lewycky966edd02011-04-16 01:20:23 +0000813
Bill Wendlingc3cab812013-03-18 23:04:39 +0000814Function *GCOVProfiler::insertCounterWriteout(
Bill Wendlinge8aee6b2012-08-29 18:45:41 +0000815 ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
Bill Wendling2e6e8662012-09-13 00:09:55 +0000816 FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
817 Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
818 if (!WriteoutF)
819 WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
820 "__llvm_gcov_writeout", M);
Nick Lewycky966edd02011-04-16 01:20:23 +0000821 WriteoutF->setUnnamedAddr(true);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000822 WriteoutF->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000823 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000824 WriteoutF->addFnAttr(Attribute::NoRedZone);
Bill Wendling2e6e8662012-09-13 00:09:55 +0000825
826 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000827 IRBuilder<> Builder(BB);
Nick Lewycky966edd02011-04-16 01:20:23 +0000828
829 Constant *StartFile = getStartFileFunc();
830 Constant *EmitFunction = getEmitFunctionFunc();
831 Constant *EmitArcs = getEmitArcsFunc();
Yuchen Wu062f24c2013-11-12 04:59:08 +0000832 Constant *SummaryInfo = getSummaryInfoFunc();
Nick Lewycky966edd02011-04-16 01:20:23 +0000833 Constant *EndFile = getEndFileFunc();
834
Devang Patel2b21d862011-08-17 22:49:38 +0000835 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
836 if (CU_Nodes) {
837 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
Bill Wendlingfb1f6682012-09-13 14:32:30 +0000838 DICompileUnit CU(CU_Nodes->getOperand(i));
Bill Wendling85722f42013-03-28 22:40:08 +0000839 std::string FilenameGcda = mangleName(CU, "gcda");
Yuchen Wuc15bf892013-12-04 19:18:23 +0000840 uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
Yuchen Wubabe7492013-11-20 04:15:05 +0000841 Builder.CreateCall3(StartFile,
Nick Lewycky492afe82013-03-07 08:28:49 +0000842 Builder.CreateGlobalStringPtr(FilenameGcda),
Yuchen Wubabe7492013-11-20 04:15:05 +0000843 Builder.CreateGlobalStringPtr(ReversedVersion),
Yuchen Wu2a9d9692013-11-21 04:53:39 +0000844 Builder.getInt32(CfgChecksum));
Nick Lewycky03aed112013-03-09 02:06:37 +0000845 for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
846 DISubprogram SP(CountersBySP[j].second);
Yuchen Wuc15bf892013-12-04 19:18:23 +0000847 uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
Daniel Jasper87a24d52013-12-04 08:57:17 +0000848 Builder.CreateCall5(
Nick Lewyckyd6718632013-03-19 01:37:55 +0000849 EmitFunction, Builder.getInt32(j),
850 Options.FunctionNamesInData ?
851 Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
852 Constant::getNullValue(Builder.getInt8PtrTy()),
Daniel Jasper87a24d52013-12-04 08:57:17 +0000853 Builder.getInt32(FuncChecksum),
Yuchen Wubabe7492013-11-20 04:15:05 +0000854 Builder.getInt8(Options.UseCfgChecksum),
Yuchen Wu2a9d9692013-11-21 04:53:39 +0000855 Builder.getInt32(CfgChecksum));
Nick Lewycky88f1d0d2013-03-09 01:33:06 +0000856
Nick Lewycky03aed112013-03-09 02:06:37 +0000857 GlobalVariable *GV = CountersBySP[j].first;
Devang Patel2b21d862011-08-17 22:49:38 +0000858 unsigned Arcs =
Nick Lewycky966edd02011-04-16 01:20:23 +0000859 cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
Devang Patel2b21d862011-08-17 22:49:38 +0000860 Builder.CreateCall2(EmitArcs,
Nick Lewycky8e94d802013-02-27 05:46:30 +0000861 Builder.getInt32(Arcs),
Devang Patel2b21d862011-08-17 22:49:38 +0000862 Builder.CreateConstGEP2_64(GV, 0, 0));
863 }
Yuchen Wu062f24c2013-11-12 04:59:08 +0000864 Builder.CreateCall(SummaryInfo);
Devang Patel2b21d862011-08-17 22:49:38 +0000865 Builder.CreateCall(EndFile);
Nick Lewycky966edd02011-04-16 01:20:23 +0000866 }
Nick Lewycky966edd02011-04-16 01:20:23 +0000867 }
Bill Wendlingc3cab812013-03-18 23:04:39 +0000868
Nick Lewyckyc58d2932011-04-26 03:54:16 +0000869 Builder.CreateRetVoid();
Bill Wendlingc3cab812013-03-18 23:04:39 +0000870 return WriteoutF;
Nick Lewycky966edd02011-04-16 01:20:23 +0000871}
Bill Wendling15605172012-05-28 06:10:56 +0000872
873void GCOVProfiler::insertIndirectCounterIncrement() {
874 Function *Fn =
875 cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
876 Fn->setUnnamedAddr(true);
877 Fn->setLinkage(GlobalValue::InternalLinkage);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000878 Fn->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000879 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000880 Fn->addFnAttr(Attribute::NoRedZone);
Bill Wendling15605172012-05-28 06:10:56 +0000881
Bill Wendling15605172012-05-28 06:10:56 +0000882 // Create basic blocks for function.
883 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
884 IRBuilder<> Builder(BB);
885
886 BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
887 BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
888 BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
889
890 // uint32_t pred = *predecessor;
891 // if (pred == 0xffffffff) return;
892 Argument *Arg = Fn->arg_begin();
893 Arg->setName("predecessor");
894 Value *Pred = Builder.CreateLoad(Arg, "pred");
Nick Lewycky8e94d802013-02-27 05:46:30 +0000895 Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
Bill Wendling15605172012-05-28 06:10:56 +0000896 BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
897
898 Builder.SetInsertPoint(PredNotNegOne);
899
900 // uint64_t *counter = counters[pred];
901 // if (!counter) return;
Nick Lewycky8e94d802013-02-27 05:46:30 +0000902 Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000903 Arg = std::next(Fn->arg_begin());
Bill Wendling15605172012-05-28 06:10:56 +0000904 Arg->setName("counters");
905 Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
906 Value *Counter = Builder.CreateLoad(GEP, "counter");
Nick Lewycky625f3952013-02-27 06:21:30 +0000907 Cond = Builder.CreateICmpEQ(Counter,
908 Constant::getNullValue(
909 Builder.getInt64Ty()->getPointerTo()));
Bill Wendling15605172012-05-28 06:10:56 +0000910 Builder.CreateCondBr(Cond, Exit, CounterEnd);
911
912 // ++*counter;
913 Builder.SetInsertPoint(CounterEnd);
914 Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
Nick Lewycky8e94d802013-02-27 05:46:30 +0000915 Builder.getInt64(1));
Bill Wendling15605172012-05-28 06:10:56 +0000916 Builder.CreateStore(Add, Counter);
917 Builder.CreateBr(Exit);
918
919 // Fill in the exit block.
920 Builder.SetInsertPoint(Exit);
921 Builder.CreateRetVoid();
922}
Bill Wendling2e6e8662012-09-13 00:09:55 +0000923
Bill Wendlingc3cab812013-03-18 23:04:39 +0000924Function *GCOVProfiler::
Bill Wendling2e6e8662012-09-13 00:09:55 +0000925insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
926 FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
Bill Wendlingc3cab812013-03-18 23:04:39 +0000927 Function *FlushF = M->getFunction("__llvm_gcov_flush");
Bill Wendling2e6e8662012-09-13 00:09:55 +0000928 if (!FlushF)
929 FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
Bill Wendlingc3cab812013-03-18 23:04:39 +0000930 "__llvm_gcov_flush", M);
Bill Wendling2e6e8662012-09-13 00:09:55 +0000931 else
932 FlushF->setLinkage(GlobalValue::InternalLinkage);
933 FlushF->setUnnamedAddr(true);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000934 FlushF->addFnAttr(Attribute::NoInline);
Nick Lewyckyfdfed3e2013-03-14 05:13:26 +0000935 if (Options.NoRedZone)
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000936 FlushF->addFnAttr(Attribute::NoRedZone);
Bill Wendling2e6e8662012-09-13 00:09:55 +0000937
Bill Wendling2e6e8662012-09-13 00:09:55 +0000938 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
939
940 // Write out the current counters.
941 Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
942 assert(WriteoutF && "Need to create the writeout function first!");
943
944 IRBuilder<> Builder(Entry);
945 Builder.CreateCall(WriteoutF);
946
Bill Wendlingfb1f6682012-09-13 14:32:30 +0000947 // Zero out the counters.
948 for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
949 I = CountersBySP.begin(), E = CountersBySP.end();
950 I != E; ++I) {
951 GlobalVariable *GV = I->first;
952 Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
Bill Wendling8d26bc32012-09-14 22:35:49 +0000953 Builder.CreateStore(Null, GV);
Bill Wendlingfb1f6682012-09-13 14:32:30 +0000954 }
Bill Wendling2e6e8662012-09-13 00:09:55 +0000955
956 Type *RetTy = FlushF->getReturnType();
957 if (RetTy == Type::getVoidTy(*Ctx))
958 Builder.CreateRetVoid();
959 else if (RetTy->isIntegerTy())
Bill Wendlingc3cab812013-03-18 23:04:39 +0000960 // Used if __llvm_gcov_flush was implicitly declared.
Bill Wendling2e6e8662012-09-13 00:09:55 +0000961 Builder.CreateRet(ConstantInt::get(RetTy, 0));
962 else
Bill Wendlingc3cab812013-03-18 23:04:39 +0000963 report_fatal_error("invalid return type for __llvm_gcov_flush");
964
965 return FlushF;
Bill Wendling2e6e8662012-09-13 00:09:55 +0000966}