SerializedDiagnosticPrinter.cpp revision 59b61613ed3b835f869b0f6fa1db52b8c963c5e5
1//===--- SerializedDiagnosticPrinter.cpp - Serializer for diagnostics -----===//
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#include <vector>
11#include "llvm/Bitcode/BitstreamWriter.h"
12#include "llvm/Support/raw_ostream.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/ADT/SmallString.h"
15#include "llvm/ADT/DenseSet.h"
16#include "clang/Basic/SourceManager.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/Version.h"
20#include "clang/Frontend/SerializedDiagnosticPrinter.h"
21
22using namespace clang;
23
24namespace {
25
26/// \brief A utility class for entering and exiting bitstream blocks.
27class BlockEnterExit {
28  llvm::BitstreamWriter &Stream;
29public:
30  BlockEnterExit(llvm::BitstreamWriter &stream, unsigned blockID,
31                 unsigned codelen = 3)
32    : Stream(stream) {
33      Stream.EnterSubblock(blockID, codelen);
34  }
35  ~BlockEnterExit() {
36    Stream.ExitBlock();
37  }
38};
39
40class AbbreviationMap {
41  llvm::DenseMap<unsigned, unsigned> Abbrevs;
42public:
43  AbbreviationMap() {}
44
45  void set(unsigned recordID, unsigned abbrevID) {
46    assert(Abbrevs.find(recordID) == Abbrevs.end()
47           && "Abbreviation already set.");
48    Abbrevs[recordID] = abbrevID;
49  }
50
51  unsigned get(unsigned recordID) {
52    assert(Abbrevs.find(recordID) != Abbrevs.end() &&
53           "Abbreviation not set.");
54    return Abbrevs[recordID];
55  }
56};
57
58typedef llvm::SmallVector<uint64_t, 64> RecordData;
59typedef llvm::SmallVectorImpl<uint64_t> RecordDataImpl;
60
61class SDiagsWriter : public DiagnosticConsumer {
62public:
63  SDiagsWriter(DiagnosticsEngine &diags, llvm::raw_ostream *os)
64    : Stream(Buffer), OS(os), Diags(diags), inNonNoteDiagnostic(false)
65  {
66    EmitPreamble();
67  };
68
69  ~SDiagsWriter() {}
70
71  void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
72                        const Diagnostic &Info);
73
74  void EndSourceFile();
75
76  DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
77    // It makes no sense to clone this.
78    return 0;
79  }
80
81private:
82  /// \brief Emit the preamble for the serialized diagnostics.
83  void EmitPreamble();
84
85  /// \brief Emit the BLOCKINFO block.
86  void EmitBlockInfoBlock();
87
88  /// \brief Emit the raw characters of the provided string.
89  void EmitRawStringContents(StringRef str);
90
91  /// \brief Emit the block containing categories and file names.
92  void EmitCategoriesAndFileNames();
93
94  /// \brief The version of the diagnostics file.
95  enum { Version = 1 };
96
97  /// \brief The byte buffer for the serialized content.
98  std::vector<unsigned char> Buffer;
99
100  /// \brief The BitStreamWriter for the serialized diagnostics.
101  llvm::BitstreamWriter Stream;
102
103  /// \brief The name of the diagnostics file.
104  llvm::OwningPtr<llvm::raw_ostream> OS;
105
106  /// \brief The DiagnosticsEngine tied to all diagnostic locations.
107  DiagnosticsEngine &Diags;
108
109  /// \brief The set of constructed record abbreviations.
110  AbbreviationMap Abbrevs;
111
112  /// \brief A utility buffer for constructing record content.
113  RecordData Record;
114
115  /// \brief A text buffer for rendering diagnostic text.
116  llvm::SmallString<256> diagBuf;
117
118  /// \brief The collection of diagnostic categories used.
119  llvm::DenseSet<unsigned> Categories;
120
121  /// \brief The collection of files used.
122  llvm::DenseSet<FileID> Files;
123
124  /// \brief Flag indicating whether or not we are in the process of
125  /// emitting a non-note diagnostic.
126  bool inNonNoteDiagnostic;
127
128  enum BlockIDs {
129    /// \brief The DIAG block, which acts as a container around a diagnostic.
130    BLOCK_DIAG = llvm::bitc::FIRST_APPLICATION_BLOCKID,
131    /// \brief The STRINGS block, which contains strings
132    /// from multiple diagnostics.
133    BLOCK_STRINGS
134  };
135
136  enum RecordIDs {
137    RECORD_DIAG = 1,
138    RECORD_DIAG_FLAG,
139    RECORD_CATEGORY,
140    RECORD_FILENAME
141  };
142};
143} // end anonymous namespace
144
145namespace clang {
146namespace serialized_diags {
147DiagnosticConsumer *create(llvm::raw_ostream *OS, DiagnosticsEngine &Diags) {
148  return new SDiagsWriter(Diags, OS);
149}
150} // end namespace serialized_diags
151} // end namespace clang
152
153//===----------------------------------------------------------------------===//
154// Serialization methods.
155//===----------------------------------------------------------------------===//
156
157/// \brief Emits a block ID in the BLOCKINFO block.
158static void EmitBlockID(unsigned ID, const char *Name,
159                        llvm::BitstreamWriter &Stream,
160                        RecordDataImpl &Record) {
161  Record.clear();
162  Record.push_back(ID);
163  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
164
165  // Emit the block name if present.
166  if (Name == 0 || Name[0] == 0)
167    return;
168
169  Record.clear();
170
171  while (*Name)
172    Record.push_back(*Name++);
173
174  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
175}
176
177/// \brief Emits a record ID in the BLOCKINFO block.
178static void EmitRecordID(unsigned ID, const char *Name,
179                         llvm::BitstreamWriter &Stream,
180                         RecordDataImpl &Record){
181  Record.clear();
182  Record.push_back(ID);
183
184  while (*Name)
185    Record.push_back(*Name++);
186
187  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
188}
189
190/// \brief Emits the preamble of the diagnostics file.
191void SDiagsWriter::EmitPreamble() {
192 // EmitRawStringContents("CLANG_DIAGS");
193 // Stream.Emit(Version, 32);
194
195  // Emit the file header.
196  Stream.Emit((unsigned)'D', 8);
197  Stream.Emit((unsigned)'I', 8);
198  Stream.Emit((unsigned)'A', 8);
199  Stream.Emit((unsigned)'G', 8);
200
201  EmitBlockInfoBlock();
202}
203
204void SDiagsWriter::EmitBlockInfoBlock() {
205  Stream.EnterBlockInfoBlock(3);
206
207  // ==---------------------------------------------------------------------==//
208  // The subsequent records and Abbrevs are for the "Diagnostic" block.
209  // ==---------------------------------------------------------------------==//
210
211  EmitBlockID(BLOCK_DIAG, "Diagnostic", Stream, Record);
212  EmitRecordID(RECORD_DIAG, "Diagnostic Info", Stream, Record);
213  EmitRecordID(RECORD_DIAG_FLAG, "Diagnostic Flag", Stream, Record);
214
215  // Emit Abbrevs.
216  using namespace llvm;
217
218  // Emit abbreviation for RECORD_DIAG.
219  BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
220  Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG));
221  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Diag level.
222  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16-3)); // Category.
223  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
224  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Diagnostc text.
225  Abbrevs.set(RECORD_DIAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev));
226
227
228  // Emit the abbreviation for RECORD_DIAG_FLAG.
229  Abbrev = new BitCodeAbbrev();
230  Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG_FLAG));
231  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
232  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Flag name text.
233  Abbrevs.set(RECORD_DIAG_FLAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev));
234
235  // ==---------------------------------------------------------------------==//
236  // The subsequent records and Abbrevs are for the "Strings" block.
237  // ==---------------------------------------------------------------------==//
238
239  EmitBlockID(BLOCK_STRINGS, "Strings", Stream, Record);
240  EmitRecordID(RECORD_CATEGORY, "Category Name", Stream, Record);
241  EmitRecordID(RECORD_FILENAME, "File Name", Stream, Record);
242
243  Abbrev = new BitCodeAbbrev();
244  Abbrev->Add(BitCodeAbbrevOp(RECORD_CATEGORY));
245  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // Text size.
246  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Category text.
247  Abbrevs.set(RECORD_CATEGORY, Stream.EmitBlockInfoAbbrev(BLOCK_STRINGS,
248                                                          Abbrev));
249
250  Abbrev = new BitCodeAbbrev();
251  Abbrev->Add(BitCodeAbbrevOp(RECORD_FILENAME));
252  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 64)); // Size.
253  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 64)); // Modifcation time.
254  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
255  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name text.
256  Abbrevs.set(RECORD_FILENAME, Stream.EmitBlockInfoAbbrev(BLOCK_STRINGS,
257                                                          Abbrev));
258
259  Stream.ExitBlock();
260}
261
262void SDiagsWriter::EmitRawStringContents(llvm::StringRef str) {
263  for (StringRef::const_iterator I = str.begin(), E = str.end(); I!=E; ++I)
264    Stream.Emit(*I, 8);
265}
266
267void SDiagsWriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
268                                    const Diagnostic &Info) {
269
270  if (DiagLevel != DiagnosticsEngine::Note) {
271    if (inNonNoteDiagnostic) {
272      // We have encountered a non-note diagnostic.  Finish up the previous
273      // diagnostic block before starting a new one.
274      Stream.ExitBlock();
275    }
276    inNonNoteDiagnostic = true;
277  }
278
279  Stream.EnterSubblock(BLOCK_DIAG, 3);
280
281  // Emit the RECORD_DIAG record.
282  Record.clear();
283  Record.push_back(RECORD_DIAG);
284  Record.push_back(DiagLevel);
285  unsigned category = DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
286  Record.push_back(category);
287  Categories.insert(category);
288  diagBuf.clear();
289  Info.FormatDiagnostic(diagBuf); // Compute the diagnostic text.
290  Record.push_back(diagBuf.str().size());
291  Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_DIAG), Record, diagBuf.str());
292
293  // Emit the RECORD_DIAG_FLAG record.
294  StringRef FlagName = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
295  if (!FlagName.empty()) {
296    Record.clear();
297    Record.push_back(RECORD_DIAG_FLAG);
298    Record.push_back(FlagName.size());
299    Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_DIAG_FLAG),
300                              Record, FlagName.str());
301  }
302
303  // FIXME: emit location
304  // FIXME: emit ranges
305  // FIXME: emit fixits
306
307  if (DiagLevel == DiagnosticsEngine::Note) {
308    // Notes currently cannot have child diagnostics.  Complete the
309    // diagnostic now.
310    Stream.ExitBlock();
311  }
312}
313
314template <typename T>
315static void populateAndSort(std::vector<T> &scribble,
316                            llvm::DenseSet<T> &set) {
317  scribble.clear();
318
319  for (typename llvm::DenseSet<T>::iterator it = set.begin(), ei = set.end();
320       it != ei; ++it)
321    scribble.push_back(*it);
322
323  // Sort 'scribble' so we always have a deterministic ordering in the
324  // serialized file.
325  std::sort(scribble.begin(), scribble.end());
326}
327
328void SDiagsWriter::EmitCategoriesAndFileNames() {
329
330  if (Categories.empty() && Files.empty())
331    return;
332
333  BlockEnterExit BlockEnter(Stream, BLOCK_STRINGS);
334
335  // Emit the category names.
336  {
337    std::vector<unsigned> scribble;
338    populateAndSort(scribble, Categories);
339    for (std::vector<unsigned>::iterator it = scribble.begin(),
340          ei = scribble.end(); it != ei ; ++it) {
341      Record.clear();
342      Record.push_back(RECORD_CATEGORY);
343      StringRef catName = DiagnosticIDs::getCategoryNameFromID(*it);
344      Record.push_back(catName.size());
345      Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_CATEGORY), Record, catName);
346    }
347  }
348
349  // Emit the file names.
350  {
351    std::vector<FileID> scribble;
352    populateAndSort(scribble, Files);
353    for (std::vector<FileID>::iterator it = scribble.begin(),
354         ei = scribble.end(); it != ei; ++it) {
355      SourceManager &SM = Diags.getSourceManager();
356      const FileEntry *FE = SM.getFileEntryForID(*it);
357      StringRef Name = FE->getName();
358
359      Record.clear();
360      Record.push_back(FE->getSize());
361      Record.push_back(FE->getModificationTime());
362      Record.push_back(Name.size());
363      Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_FILENAME), Record, Name);
364    }
365  }
366
367}
368
369void SDiagsWriter::EndSourceFile() {
370  if (inNonNoteDiagnostic) {
371    // Finish off any diagnostics we were in the process of emitting.
372    Stream.ExitBlock();
373    inNonNoteDiagnostic = false;
374  }
375
376  EmitCategoriesAndFileNames();
377
378  // Write the generated bitstream to "Out".
379  OS->write((char *)&Buffer.front(), Buffer.size());
380  OS->flush();
381
382  OS.reset(0);
383}
384
385