GCOV.cpp: Use PRIu64 instead of %lu.
[oota-llvm.git] / lib / IR / GCOV.cpp
1 //===- GCOV.cpp - LLVM coverage tool --------------------------------------===//
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 // GCOV implements the interface to read and write coverage files that use
11 // 'gcov' format.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Support/Debug.h"
16 #include "llvm/Support/GCOV.h"
17 #include "llvm/ADT/OwningPtr.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/Support/MemoryObject.h"
21 #include "llvm/Support/system_error.h"
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 // GCOVFile implementation.
26
27 /// ~GCOVFile - Delete GCOVFile and its content.
28 GCOVFile::~GCOVFile() {
29   DeleteContainerPointers(Functions);
30 }
31
32 /// readGCNO - Read GCNO buffer.
33 bool GCOVFile::readGCNO(GCOVBuffer &Buffer) {
34   if (!Buffer.readGCNOFormat()) return false;
35   if (!Buffer.readGCOVVersion(Version)) return false;
36
37   if (!Buffer.readInt(Checksum)) return false;
38   while (true) {
39     if (!Buffer.readFunctionTag()) break;
40     GCOVFunction *GFun = new GCOVFunction(*this);
41     if (!GFun->readGCNO(Buffer, Version))
42       return false;
43     Functions.push_back(GFun);
44   }
45
46   GCNOInitialized = true;
47   return true;
48 }
49
50 /// readGCDA - Read GCDA buffer. It is required that readGCDA() can only be
51 /// called after readGCNO().
52 bool GCOVFile::readGCDA(GCOVBuffer &Buffer) {
53   assert(GCNOInitialized && "readGCDA() can only be called after readGCNO()");
54   if (!Buffer.readGCDAFormat()) return false;
55   GCOV::GCOVVersion GCDAVersion;
56   if (!Buffer.readGCOVVersion(GCDAVersion)) return false;
57   if (Version != GCDAVersion) {
58     errs() << "GCOV versions do not match.\n";
59     return false;
60   }
61
62   uint32_t GCDAChecksum;
63   if (!Buffer.readInt(GCDAChecksum)) return false;
64   if (Checksum != GCDAChecksum) {
65     errs() << "File checksums do not match: " << Checksum << " != "
66            << GCDAChecksum << ".\n";
67     return false;
68   }
69   for (size_t i = 0, e = Functions.size(); i < e; ++i) {
70     if (!Buffer.readFunctionTag()) {
71       errs() << "Unexpected number of functions.\n";
72       return false;
73     }
74     if (!Functions[i]->readGCDA(Buffer, Version))
75       return false;
76   }
77   if (Buffer.readObjectTag()) {
78     uint32_t Length;
79     uint32_t Dummy;
80     if (!Buffer.readInt(Length)) return false;
81     if (!Buffer.readInt(Dummy)) return false; // checksum
82     if (!Buffer.readInt(Dummy)) return false; // num
83     if (!Buffer.readInt(RunCount)) return false;;
84     Buffer.advanceCursor(Length-3);
85   }
86   while (Buffer.readProgramTag()) {
87     uint32_t Length;
88     if (!Buffer.readInt(Length)) return false;
89     Buffer.advanceCursor(Length);
90     ++ProgramCount;
91   }
92
93   return true;
94 }
95
96 /// dump - Dump GCOVFile content to dbgs() for debugging purposes.
97 void GCOVFile::dump() const {
98   for (SmallVectorImpl<GCOVFunction *>::const_iterator I = Functions.begin(),
99          E = Functions.end(); I != E; ++I)
100     (*I)->dump();
101 }
102
103 /// collectLineCounts - Collect line counts. This must be used after
104 /// reading .gcno and .gcda files.
105 void GCOVFile::collectLineCounts(FileInfo &FI) {
106   for (SmallVectorImpl<GCOVFunction *>::iterator I = Functions.begin(),
107          E = Functions.end(); I != E; ++I)
108     (*I)->collectLineCounts(FI);
109   FI.setRunCount(RunCount);
110   FI.setProgramCount(ProgramCount);
111 }
112
113 //===----------------------------------------------------------------------===//
114 // GCOVFunction implementation.
115
116 /// ~GCOVFunction - Delete GCOVFunction and its content.
117 GCOVFunction::~GCOVFunction() {
118   DeleteContainerPointers(Blocks);
119   DeleteContainerPointers(Edges);
120 }
121
122 /// readGCNO - Read a function from the GCNO buffer. Return false if an error
123 /// occurs.
124 bool GCOVFunction::readGCNO(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
125   uint32_t Dummy;
126   if (!Buff.readInt(Dummy)) return false; // Function header length
127   if (!Buff.readInt(Ident)) return false;
128   if (!Buff.readInt(Checksum)) return false;
129   if (Version != GCOV::V402) {
130     uint32_t CfgChecksum;
131     if (!Buff.readInt(CfgChecksum)) return false;
132     if (Parent.getChecksum() != CfgChecksum) {
133       errs() << "File checksums do not match: " << Parent.getChecksum()
134              << " != " << CfgChecksum << " in (" << Name << ").\n";
135       return false;
136     }
137   }
138   if (!Buff.readString(Name)) return false;
139   if (!Buff.readString(Filename)) return false;
140   if (!Buff.readInt(LineNumber)) return false;
141
142   // read blocks.
143   if (!Buff.readBlockTag()) {
144     errs() << "Block tag not found.\n";
145     return false;
146   }
147   uint32_t BlockCount;
148   if (!Buff.readInt(BlockCount)) return false;
149   for (uint32_t i = 0, e = BlockCount; i != e; ++i) {
150     if (!Buff.readInt(Dummy)) return false; // Block flags;
151     Blocks.push_back(new GCOVBlock(*this, i));
152   }
153
154   // read edges.
155   while (Buff.readEdgeTag()) {
156     uint32_t EdgeCount;
157     if (!Buff.readInt(EdgeCount)) return false;
158     EdgeCount = (EdgeCount - 1) / 2;
159     uint32_t BlockNo;
160     if (!Buff.readInt(BlockNo)) return false;
161     if (BlockNo >= BlockCount) {
162       errs() << "Unexpected block number: " << BlockNo << " (in " << Name
163              << ").\n";
164       return false;
165     }
166     for (uint32_t i = 0, e = EdgeCount; i != e; ++i) {
167       uint32_t Dst;
168       if (!Buff.readInt(Dst)) return false;
169       GCOVEdge *Edge = new GCOVEdge(Blocks[BlockNo], Blocks[Dst]);
170       Edges.push_back(Edge);
171       Blocks[BlockNo]->addDstEdge(Edge);
172       Blocks[Dst]->addSrcEdge(Edge);
173       if (!Buff.readInt(Dummy)) return false; // Edge flag
174     }
175   }
176
177   // read line table.
178   while (Buff.readLineTag()) {
179     uint32_t LineTableLength;
180     if (!Buff.readInt(LineTableLength)) return false;
181     uint32_t EndPos = Buff.getCursor() + LineTableLength*4;
182     uint32_t BlockNo;
183     if (!Buff.readInt(BlockNo)) return false;
184     if (BlockNo >= BlockCount) {
185       errs() << "Unexpected block number: " << BlockNo << " (in " << Name
186              << ").\n";
187       return false;
188     }
189     GCOVBlock *Block = Blocks[BlockNo];
190     if (!Buff.readInt(Dummy)) return false; // flag
191     while (Buff.getCursor() != (EndPos - 4)) {
192       StringRef F;
193       if (!Buff.readString(F)) return false;
194       if (Filename != F) {
195         errs() << "Multiple sources for a single basic block: " << Filename
196                << " != " << F << " (in " << Name << ").\n";
197         return false;
198       }
199       if (Buff.getCursor() == (EndPos - 4)) break;
200       while (true) {
201         uint32_t Line;
202         if (!Buff.readInt(Line)) return false;
203         if (!Line) break;
204         Block->addLine(Line);
205       }
206     }
207     if (!Buff.readInt(Dummy)) return false; // flag
208   }
209   return true;
210 }
211
212 /// readGCDA - Read a function from the GCDA buffer. Return false if an error
213 /// occurs.
214 bool GCOVFunction::readGCDA(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
215   uint32_t Dummy;
216   if (!Buff.readInt(Dummy)) return false; // Function header length
217
218   uint32_t GCDAIdent;
219   if (!Buff.readInt(GCDAIdent)) return false;
220   if (Ident != GCDAIdent) {
221     errs() << "Function identifiers do not match: " << Ident << " != "
222            << GCDAIdent << " (in " << Name << ").\n";
223     return false;
224   }
225
226   uint32_t GCDAChecksum;
227   if (!Buff.readInt(GCDAChecksum)) return false;
228   if (Checksum != GCDAChecksum) {
229     errs() << "Function checksums do not match: " << Checksum << " != "
230            << GCDAChecksum << " (in " << Name << ").\n";
231     return false;
232   }
233
234   uint32_t CfgChecksum;
235   if (Version != GCOV::V402) {
236     if (!Buff.readInt(CfgChecksum)) return false;
237     if (Parent.getChecksum() != CfgChecksum) {
238       errs() << "File checksums do not match: " << Parent.getChecksum()
239              << " != " << CfgChecksum << " (in " << Name << ").\n";
240       return false;
241     }
242   }
243
244   StringRef GCDAName;
245   if (!Buff.readString(GCDAName)) return false;
246   if (Name != GCDAName) {
247     errs() << "Function names do not match: " << Name << " != " << GCDAName
248            << ".\n";
249     return false;
250   }
251
252   if (!Buff.readArcTag()) {
253     errs() << "Arc tag not found (in " << Name << ").\n";
254     return false;
255   }
256
257   uint32_t Count;
258   if (!Buff.readInt(Count)) return false;
259   Count /= 2;
260
261   // This for loop adds the counts for each block. A second nested loop is
262   // required to combine the edge counts that are contained in the GCDA file.
263   for (uint32_t BlockNo = 0; Count > 0; ++BlockNo) {
264     // The last block is always reserved for exit block
265     if (BlockNo >= Blocks.size()-1) {
266       errs() << "Unexpected number of edges (in " << Name << ").\n";
267       return false;
268     }
269     GCOVBlock &Block = *Blocks[BlockNo];
270     for (size_t EdgeNo = 0, End = Block.getNumDstEdges(); EdgeNo < End;
271            ++EdgeNo) {
272       if (Count == 0) {
273         errs() << "Unexpected number of edges (in " << Name << ").\n";
274         return false;
275       }
276       uint64_t ArcCount;
277       if (!Buff.readInt64(ArcCount)) return false;
278       Block.addCount(EdgeNo, ArcCount);
279       --Count;
280     }
281   }
282   return true;
283 }
284
285 /// dump - Dump GCOVFunction content to dbgs() for debugging purposes.
286 void GCOVFunction::dump() const {
287   dbgs() <<  "===== " << Name << " @ " << Filename << ":" << LineNumber << "\n";
288   for (SmallVectorImpl<GCOVBlock *>::const_iterator I = Blocks.begin(),
289          E = Blocks.end(); I != E; ++I)
290     (*I)->dump();
291 }
292
293 /// collectLineCounts - Collect line counts. This must be used after
294 /// reading .gcno and .gcda files.
295 void GCOVFunction::collectLineCounts(FileInfo &FI) {
296   for (SmallVectorImpl<GCOVBlock *>::iterator I = Blocks.begin(),
297          E = Blocks.end(); I != E; ++I)
298     (*I)->collectLineCounts(FI);
299 }
300
301 //===----------------------------------------------------------------------===//
302 // GCOVBlock implementation.
303
304 /// ~GCOVBlock - Delete GCOVBlock and its content.
305 GCOVBlock::~GCOVBlock() {
306   SrcEdges.clear();
307   DstEdges.clear();
308   Lines.clear();
309 }
310
311 /// addCount - Add to block counter while storing the edge count. If the
312 /// destination has no outgoing edges, also update that block's count too.
313 void GCOVBlock::addCount(size_t DstEdgeNo, uint64_t N) {
314   assert(DstEdgeNo < DstEdges.size()); // up to caller to ensure EdgeNo is valid
315   DstEdges[DstEdgeNo]->Count = N;
316   Counter += N;
317   if (!DstEdges[DstEdgeNo]->Dst->getNumDstEdges())
318     DstEdges[DstEdgeNo]->Dst->Counter += N;
319 }
320
321 /// collectLineCounts - Collect line counts. This must be used after
322 /// reading .gcno and .gcda files.
323 void GCOVBlock::collectLineCounts(FileInfo &FI) {
324   for (SmallVectorImpl<uint32_t>::iterator I = Lines.begin(),
325          E = Lines.end(); I != E; ++I)
326     FI.addBlockLine(Parent.getFilename(), *I, this);
327 }
328
329 /// dump - Dump GCOVBlock content to dbgs() for debugging purposes.
330 void GCOVBlock::dump() const {
331   dbgs() << "Block : " << Number << " Counter : " << Counter << "\n";
332   if (!SrcEdges.empty()) {
333     dbgs() << "\tSource Edges : ";
334     for (EdgeIterator I = SrcEdges.begin(), E = SrcEdges.end(); I != E; ++I) {
335       const GCOVEdge *Edge = *I;
336       dbgs() << Edge->Src->Number << " (" << Edge->Count << "), ";
337     }
338     dbgs() << "\n";
339   }
340   if (!DstEdges.empty()) {
341     dbgs() << "\tDestination Edges : ";
342     for (EdgeIterator I = DstEdges.begin(), E = DstEdges.end(); I != E; ++I) {
343       const GCOVEdge *Edge = *I;
344       dbgs() << Edge->Dst->Number << " (" << Edge->Count << "), ";
345     }
346     dbgs() << "\n";
347   }
348   if (!Lines.empty()) {
349     dbgs() << "\tLines : ";
350     for (SmallVectorImpl<uint32_t>::const_iterator I = Lines.begin(),
351            E = Lines.end(); I != E; ++I)
352       dbgs() << (*I) << ",";
353     dbgs() << "\n";
354   }
355 }
356
357 //===----------------------------------------------------------------------===//
358 // FileInfo implementation.
359
360 /// print -  Print source files with collected line count information.
361 void FileInfo::print(StringRef GCNOFile, StringRef GCDAFile,
362                      const GCOVOptions &Options) const {
363   for (StringMap<LineData>::const_iterator I = LineInfo.begin(),
364          E = LineInfo.end(); I != E; ++I) {
365     StringRef Filename = I->first();
366     OwningPtr<MemoryBuffer> Buff;
367     if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
368       errs() << Filename << ": " << ec.message() << "\n";
369       return;
370     }
371     StringRef AllLines = Buff->getBuffer();
372
373     std::string CovFilename = Filename.str() + ".gcov";
374     std::string ErrorInfo;
375     raw_fd_ostream OS(CovFilename.c_str(), ErrorInfo);
376     if (!ErrorInfo.empty())
377       errs() << ErrorInfo << "\n";
378
379     OS << "        -:    0:Source:" << Filename << "\n";
380     OS << "        -:    0:Graph:" << GCNOFile << "\n";
381     OS << "        -:    0:Data:" << GCDAFile << "\n";
382     OS << "        -:    0:Runs:" << RunCount << "\n";
383     OS << "        -:    0:Programs:" << ProgramCount << "\n";
384
385     const LineData &Line = I->second;
386     for (uint32_t i = 0; !AllLines.empty(); ++i) {
387       LineData::const_iterator BlocksIt = Line.find(i);
388
389       if (BlocksIt != Line.end()) {
390         // Add up the block counts to form line counts.
391         const BlockVector &Blocks = BlocksIt->second;
392         uint64_t LineCount = 0;
393         for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
394                I != E; ++I) {
395           const GCOVBlock *Block = *I;
396           if (Options.AllBlocks) {
397             // Only take the highest block count for that line.
398             uint64_t BlockCount = Block->getCount();
399             LineCount = LineCount > BlockCount ? LineCount : BlockCount;
400           } else {
401             // Sum up all of the block counts.
402             LineCount += Block->getCount();
403           }
404         }
405         if (LineCount == 0)
406           OS << "    #####:";
407         else
408           OS << format("%9" PRIu64 ":", LineCount);
409       } else {
410         OS << "        -:";
411       }
412       std::pair<StringRef, StringRef> P = AllLines.split('\n');
413       OS << format("%5u:", i+1) << P.first << "\n";
414       AllLines = P.second;
415
416       if (Options.AllBlocks && BlocksIt != Line.end()) {
417         // Output the counts for each block at the last line of the block.
418         uint32_t BlockNo = 0;
419         const BlockVector &Blocks = BlocksIt->second;
420         for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
421                I != E; ++I) {
422           const GCOVBlock *Block = *I;
423           if (Block->getLastLine() != i+1)
424             continue;
425
426           if (Block->getCount() == 0)
427             OS << "    $$$$$:";
428           else
429             OS << format("%9" PRIu64 ":", (uint64_t)Block->getCount());
430           OS << format("%5u-block  %u\n", i+1, BlockNo++);
431         }
432       }
433     }
434   }
435 }