SerializedDiagnosticPrinter.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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. #include "clang/Frontend/SerializedDiagnosticPrinter.h"
  10. #include "clang/Basic/Diagnostic.h"
  11. #include "clang/Basic/DiagnosticOptions.h"
  12. #include "clang/Basic/FileManager.h"
  13. #include "clang/Basic/SourceManager.h"
  14. #include "clang/Basic/Version.h"
  15. #include "clang/Frontend/DiagnosticRenderer.h"
  16. #include "clang/Frontend/FrontendDiagnostic.h"
  17. #include "clang/Frontend/SerializedDiagnosticReader.h"
  18. #include "clang/Frontend/SerializedDiagnostics.h"
  19. #include "clang/Frontend/TextDiagnosticPrinter.h"
  20. #include "clang/Lex/Lexer.h"
  21. #include "llvm/ADT/DenseSet.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SmallString.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include <vector>
  27. using namespace clang;
  28. using namespace clang::serialized_diags;
  29. namespace {
  30. class AbbreviationMap {
  31. llvm::DenseMap<unsigned, unsigned> Abbrevs;
  32. public:
  33. AbbreviationMap() {}
  34. void set(unsigned recordID, unsigned abbrevID) {
  35. assert(Abbrevs.find(recordID) == Abbrevs.end()
  36. && "Abbreviation already set.");
  37. Abbrevs[recordID] = abbrevID;
  38. }
  39. unsigned get(unsigned recordID) {
  40. assert(Abbrevs.find(recordID) != Abbrevs.end() &&
  41. "Abbreviation not set.");
  42. return Abbrevs[recordID];
  43. }
  44. };
  45. typedef SmallVector<uint64_t, 64> RecordData;
  46. typedef SmallVectorImpl<uint64_t> RecordDataImpl;
  47. class SDiagsWriter;
  48. class SDiagsRenderer : public DiagnosticNoteRenderer {
  49. SDiagsWriter &Writer;
  50. public:
  51. SDiagsRenderer(SDiagsWriter &Writer, const LangOptions &LangOpts,
  52. DiagnosticOptions *DiagOpts)
  53. : DiagnosticNoteRenderer(LangOpts, DiagOpts), Writer(Writer) {}
  54. ~SDiagsRenderer() override {}
  55. protected:
  56. void emitDiagnosticMessage(SourceLocation Loc,
  57. PresumedLoc PLoc,
  58. DiagnosticsEngine::Level Level,
  59. StringRef Message,
  60. ArrayRef<CharSourceRange> Ranges,
  61. const SourceManager *SM,
  62. DiagOrStoredDiag D) override;
  63. void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
  64. DiagnosticsEngine::Level Level,
  65. ArrayRef<CharSourceRange> Ranges,
  66. const SourceManager &SM) override {}
  67. void emitNote(SourceLocation Loc, StringRef Message,
  68. const SourceManager *SM) override;
  69. void emitCodeContext(SourceLocation Loc,
  70. DiagnosticsEngine::Level Level,
  71. SmallVectorImpl<CharSourceRange>& Ranges,
  72. ArrayRef<FixItHint> Hints,
  73. const SourceManager &SM) override;
  74. void beginDiagnostic(DiagOrStoredDiag D,
  75. DiagnosticsEngine::Level Level) override;
  76. void endDiagnostic(DiagOrStoredDiag D,
  77. DiagnosticsEngine::Level Level) override;
  78. };
  79. typedef llvm::DenseMap<unsigned, unsigned> AbbrevLookup;
  80. class SDiagsMerger : SerializedDiagnosticReader {
  81. SDiagsWriter &Writer;
  82. AbbrevLookup FileLookup;
  83. AbbrevLookup CategoryLookup;
  84. AbbrevLookup DiagFlagLookup;
  85. public:
  86. SDiagsMerger(SDiagsWriter &Writer)
  87. : SerializedDiagnosticReader(), Writer(Writer) {}
  88. std::error_code mergeRecordsFromFile(const char *File) {
  89. return readDiagnostics(File);
  90. }
  91. protected:
  92. std::error_code visitStartOfDiagnostic() override;
  93. std::error_code visitEndOfDiagnostic() override;
  94. std::error_code visitCategoryRecord(unsigned ID, StringRef Name) override;
  95. std::error_code visitDiagFlagRecord(unsigned ID, StringRef Name) override;
  96. std::error_code visitDiagnosticRecord(
  97. unsigned Severity, const serialized_diags::Location &Location,
  98. unsigned Category, unsigned Flag, StringRef Message) override;
  99. std::error_code visitFilenameRecord(unsigned ID, unsigned Size,
  100. unsigned Timestamp,
  101. StringRef Name) override;
  102. std::error_code visitFixitRecord(const serialized_diags::Location &Start,
  103. const serialized_diags::Location &End,
  104. StringRef CodeToInsert) override;
  105. std::error_code
  106. visitSourceRangeRecord(const serialized_diags::Location &Start,
  107. const serialized_diags::Location &End) override;
  108. private:
  109. std::error_code adjustSourceLocFilename(RecordData &Record,
  110. unsigned int offset);
  111. void adjustAbbrevID(RecordData &Record, AbbrevLookup &Lookup,
  112. unsigned NewAbbrev);
  113. void writeRecordWithAbbrev(unsigned ID, RecordData &Record);
  114. void writeRecordWithBlob(unsigned ID, RecordData &Record, StringRef Blob);
  115. };
  116. class SDiagsWriter : public DiagnosticConsumer {
  117. friend class SDiagsRenderer;
  118. friend class SDiagsMerger;
  119. struct SharedState;
  120. explicit SDiagsWriter(IntrusiveRefCntPtr<SharedState> State)
  121. : LangOpts(nullptr), OriginalInstance(false), MergeChildRecords(false),
  122. State(State) {}
  123. public:
  124. SDiagsWriter(StringRef File, DiagnosticOptions *Diags, bool MergeChildRecords)
  125. : LangOpts(nullptr), OriginalInstance(true),
  126. MergeChildRecords(MergeChildRecords),
  127. State(new SharedState(File, Diags)) {
  128. if (MergeChildRecords)
  129. RemoveOldDiagnostics();
  130. EmitPreamble();
  131. }
  132. ~SDiagsWriter() override {}
  133. void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
  134. const Diagnostic &Info) override;
  135. void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override {
  136. LangOpts = &LO;
  137. }
  138. void finish() override;
  139. private:
  140. /// \brief Build a DiagnosticsEngine to emit diagnostics about the diagnostics
  141. DiagnosticsEngine *getMetaDiags();
  142. /// \brief Remove old copies of the serialized diagnostics. This is necessary
  143. /// so that we can detect when subprocesses write diagnostics that we should
  144. /// merge into our own.
  145. void RemoveOldDiagnostics();
  146. /// \brief Emit the preamble for the serialized diagnostics.
  147. void EmitPreamble();
  148. /// \brief Emit the BLOCKINFO block.
  149. void EmitBlockInfoBlock();
  150. /// \brief Emit the META data block.
  151. void EmitMetaBlock();
  152. /// \brief Start a DIAG block.
  153. void EnterDiagBlock();
  154. /// \brief End a DIAG block.
  155. void ExitDiagBlock();
  156. /// \brief Emit a DIAG record.
  157. void EmitDiagnosticMessage(SourceLocation Loc,
  158. PresumedLoc PLoc,
  159. DiagnosticsEngine::Level Level,
  160. StringRef Message,
  161. const SourceManager *SM,
  162. DiagOrStoredDiag D);
  163. /// \brief Emit FIXIT and SOURCE_RANGE records for a diagnostic.
  164. void EmitCodeContext(SmallVectorImpl<CharSourceRange> &Ranges,
  165. ArrayRef<FixItHint> Hints,
  166. const SourceManager &SM);
  167. /// \brief Emit a record for a CharSourceRange.
  168. void EmitCharSourceRange(CharSourceRange R, const SourceManager &SM);
  169. /// \brief Emit the string information for the category.
  170. unsigned getEmitCategory(unsigned category = 0);
  171. /// \brief Emit the string information for diagnostic flags.
  172. unsigned getEmitDiagnosticFlag(DiagnosticsEngine::Level DiagLevel,
  173. unsigned DiagID = 0);
  174. unsigned getEmitDiagnosticFlag(StringRef DiagName);
  175. /// \brief Emit (lazily) the file string and retrieved the file identifier.
  176. unsigned getEmitFile(const char *Filename);
  177. /// \brief Add SourceLocation information the specified record.
  178. void AddLocToRecord(SourceLocation Loc, const SourceManager *SM,
  179. PresumedLoc PLoc, RecordDataImpl &Record,
  180. unsigned TokSize = 0);
  181. /// \brief Add SourceLocation information the specified record.
  182. void AddLocToRecord(SourceLocation Loc, RecordDataImpl &Record,
  183. const SourceManager *SM,
  184. unsigned TokSize = 0) {
  185. AddLocToRecord(Loc, SM, SM ? SM->getPresumedLoc(Loc) : PresumedLoc(),
  186. Record, TokSize);
  187. }
  188. /// \brief Add CharSourceRange information the specified record.
  189. void AddCharSourceRangeToRecord(CharSourceRange R, RecordDataImpl &Record,
  190. const SourceManager &SM);
  191. /// \brief Language options, which can differ from one clone of this client
  192. /// to another.
  193. const LangOptions *LangOpts;
  194. /// \brief Whether this is the original instance (rather than one of its
  195. /// clones), responsible for writing the file at the end.
  196. bool OriginalInstance;
  197. /// \brief Whether this instance should aggregate diagnostics that are
  198. /// generated from child processes.
  199. bool MergeChildRecords;
  200. /// \brief State that is shared among the various clones of this diagnostic
  201. /// consumer.
  202. struct SharedState : RefCountedBase<SharedState> {
  203. SharedState(StringRef File, DiagnosticOptions *Diags)
  204. : DiagOpts(Diags), Stream(Buffer), OutputFile(File.str()),
  205. EmittedAnyDiagBlocks(false) {}
  206. /// \brief Diagnostic options.
  207. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
  208. /// \brief The byte buffer for the serialized content.
  209. SmallString<1024> Buffer;
  210. /// \brief The BitStreamWriter for the serialized diagnostics.
  211. llvm::BitstreamWriter Stream;
  212. /// \brief The name of the diagnostics file.
  213. std::string OutputFile;
  214. /// \brief The set of constructed record abbreviations.
  215. AbbreviationMap Abbrevs;
  216. /// \brief A utility buffer for constructing record content.
  217. RecordData Record;
  218. /// \brief A text buffer for rendering diagnostic text.
  219. SmallString<256> diagBuf;
  220. /// \brief The collection of diagnostic categories used.
  221. llvm::DenseSet<unsigned> Categories;
  222. /// \brief The collection of files used.
  223. llvm::DenseMap<const char *, unsigned> Files;
  224. typedef llvm::DenseMap<const void *, std::pair<unsigned, StringRef> >
  225. DiagFlagsTy;
  226. /// \brief Map for uniquing strings.
  227. DiagFlagsTy DiagFlags;
  228. /// \brief Whether we have already started emission of any DIAG blocks. Once
  229. /// this becomes \c true, we never close a DIAG block until we know that we're
  230. /// starting another one or we're done.
  231. bool EmittedAnyDiagBlocks;
  232. /// \brief Engine for emitting diagnostics about the diagnostics.
  233. std::unique_ptr<DiagnosticsEngine> MetaDiagnostics;
  234. };
  235. /// \brief State shared among the various clones of this diagnostic consumer.
  236. IntrusiveRefCntPtr<SharedState> State;
  237. };
  238. } // end anonymous namespace
  239. namespace clang {
  240. namespace serialized_diags {
  241. std::unique_ptr<DiagnosticConsumer>
  242. create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords) {
  243. return llvm::make_unique<SDiagsWriter>(OutputFile, Diags, MergeChildRecords);
  244. }
  245. } // end namespace serialized_diags
  246. } // end namespace clang
  247. //===----------------------------------------------------------------------===//
  248. // Serialization methods.
  249. //===----------------------------------------------------------------------===//
  250. /// \brief Emits a block ID in the BLOCKINFO block.
  251. static void EmitBlockID(unsigned ID, const char *Name,
  252. llvm::BitstreamWriter &Stream,
  253. RecordDataImpl &Record) {
  254. Record.clear();
  255. Record.push_back(ID);
  256. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
  257. // Emit the block name if present.
  258. if (!Name || Name[0] == 0)
  259. return;
  260. Record.clear();
  261. while (*Name)
  262. Record.push_back(*Name++);
  263. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
  264. }
  265. /// \brief Emits a record ID in the BLOCKINFO block.
  266. static void EmitRecordID(unsigned ID, const char *Name,
  267. llvm::BitstreamWriter &Stream,
  268. RecordDataImpl &Record){
  269. Record.clear();
  270. Record.push_back(ID);
  271. while (*Name)
  272. Record.push_back(*Name++);
  273. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
  274. }
  275. void SDiagsWriter::AddLocToRecord(SourceLocation Loc,
  276. const SourceManager *SM,
  277. PresumedLoc PLoc,
  278. RecordDataImpl &Record,
  279. unsigned TokSize) {
  280. if (PLoc.isInvalid()) {
  281. // Emit a "sentinel" location.
  282. Record.push_back((unsigned)0); // File.
  283. Record.push_back((unsigned)0); // Line.
  284. Record.push_back((unsigned)0); // Column.
  285. Record.push_back((unsigned)0); // Offset.
  286. return;
  287. }
  288. Record.push_back(getEmitFile(PLoc.getFilename()));
  289. Record.push_back(PLoc.getLine());
  290. Record.push_back(PLoc.getColumn()+TokSize);
  291. Record.push_back(SM->getFileOffset(Loc));
  292. }
  293. void SDiagsWriter::AddCharSourceRangeToRecord(CharSourceRange Range,
  294. RecordDataImpl &Record,
  295. const SourceManager &SM) {
  296. AddLocToRecord(Range.getBegin(), Record, &SM);
  297. unsigned TokSize = 0;
  298. if (Range.isTokenRange())
  299. TokSize = Lexer::MeasureTokenLength(Range.getEnd(),
  300. SM, *LangOpts);
  301. AddLocToRecord(Range.getEnd(), Record, &SM, TokSize);
  302. }
  303. unsigned SDiagsWriter::getEmitFile(const char *FileName){
  304. if (!FileName)
  305. return 0;
  306. unsigned &entry = State->Files[FileName];
  307. if (entry)
  308. return entry;
  309. // Lazily generate the record for the file.
  310. entry = State->Files.size();
  311. RecordData Record;
  312. Record.push_back(RECORD_FILENAME);
  313. Record.push_back(entry);
  314. Record.push_back(0); // For legacy.
  315. Record.push_back(0); // For legacy.
  316. StringRef Name(FileName);
  317. Record.push_back(Name.size());
  318. State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_FILENAME), Record,
  319. Name);
  320. return entry;
  321. }
  322. void SDiagsWriter::EmitCharSourceRange(CharSourceRange R,
  323. const SourceManager &SM) {
  324. State->Record.clear();
  325. State->Record.push_back(RECORD_SOURCE_RANGE);
  326. AddCharSourceRangeToRecord(R, State->Record, SM);
  327. State->Stream.EmitRecordWithAbbrev(State->Abbrevs.get(RECORD_SOURCE_RANGE),
  328. State->Record);
  329. }
  330. /// \brief Emits the preamble of the diagnostics file.
  331. void SDiagsWriter::EmitPreamble() {
  332. // Emit the file header.
  333. State->Stream.Emit((unsigned)'D', 8);
  334. State->Stream.Emit((unsigned)'I', 8);
  335. State->Stream.Emit((unsigned)'A', 8);
  336. State->Stream.Emit((unsigned)'G', 8);
  337. EmitBlockInfoBlock();
  338. EmitMetaBlock();
  339. }
  340. static void AddSourceLocationAbbrev(llvm::BitCodeAbbrev *Abbrev) {
  341. using namespace llvm;
  342. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // File ID.
  343. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Line.
  344. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Column.
  345. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Offset;
  346. }
  347. static void AddRangeLocationAbbrev(llvm::BitCodeAbbrev *Abbrev) {
  348. AddSourceLocationAbbrev(Abbrev);
  349. AddSourceLocationAbbrev(Abbrev);
  350. }
  351. void SDiagsWriter::EmitBlockInfoBlock() {
  352. State->Stream.EnterBlockInfoBlock(3);
  353. using namespace llvm;
  354. llvm::BitstreamWriter &Stream = State->Stream;
  355. RecordData &Record = State->Record;
  356. AbbreviationMap &Abbrevs = State->Abbrevs;
  357. // ==---------------------------------------------------------------------==//
  358. // The subsequent records and Abbrevs are for the "Meta" block.
  359. // ==---------------------------------------------------------------------==//
  360. EmitBlockID(BLOCK_META, "Meta", Stream, Record);
  361. EmitRecordID(RECORD_VERSION, "Version", Stream, Record);
  362. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  363. Abbrev->Add(BitCodeAbbrevOp(RECORD_VERSION));
  364. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  365. Abbrevs.set(RECORD_VERSION, Stream.EmitBlockInfoAbbrev(BLOCK_META, Abbrev));
  366. // ==---------------------------------------------------------------------==//
  367. // The subsequent records and Abbrevs are for the "Diagnostic" block.
  368. // ==---------------------------------------------------------------------==//
  369. EmitBlockID(BLOCK_DIAG, "Diag", Stream, Record);
  370. EmitRecordID(RECORD_DIAG, "DiagInfo", Stream, Record);
  371. EmitRecordID(RECORD_SOURCE_RANGE, "SrcRange", Stream, Record);
  372. EmitRecordID(RECORD_CATEGORY, "CatName", Stream, Record);
  373. EmitRecordID(RECORD_DIAG_FLAG, "DiagFlag", Stream, Record);
  374. EmitRecordID(RECORD_FILENAME, "FileName", Stream, Record);
  375. EmitRecordID(RECORD_FIXIT, "FixIt", Stream, Record);
  376. // Emit abbreviation for RECORD_DIAG.
  377. Abbrev = new BitCodeAbbrev();
  378. Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG));
  379. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Diag level.
  380. AddSourceLocationAbbrev(Abbrev);
  381. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Category.
  382. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped Diag ID.
  383. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
  384. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Diagnostc text.
  385. Abbrevs.set(RECORD_DIAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev));
  386. // Emit abbrevation for RECORD_CATEGORY.
  387. Abbrev = new BitCodeAbbrev();
  388. Abbrev->Add(BitCodeAbbrevOp(RECORD_CATEGORY));
  389. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Category ID.
  390. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // Text size.
  391. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Category text.
  392. Abbrevs.set(RECORD_CATEGORY, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev));
  393. // Emit abbrevation for RECORD_SOURCE_RANGE.
  394. Abbrev = new BitCodeAbbrev();
  395. Abbrev->Add(BitCodeAbbrevOp(RECORD_SOURCE_RANGE));
  396. AddRangeLocationAbbrev(Abbrev);
  397. Abbrevs.set(RECORD_SOURCE_RANGE,
  398. Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev));
  399. // Emit the abbreviation for RECORD_DIAG_FLAG.
  400. Abbrev = new BitCodeAbbrev();
  401. Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG_FLAG));
  402. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped Diag ID.
  403. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
  404. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Flag name text.
  405. Abbrevs.set(RECORD_DIAG_FLAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG,
  406. Abbrev));
  407. // Emit the abbreviation for RECORD_FILENAME.
  408. Abbrev = new BitCodeAbbrev();
  409. Abbrev->Add(BitCodeAbbrevOp(RECORD_FILENAME));
  410. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped file ID.
  411. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Size.
  412. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Modifcation time.
  413. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
  414. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name text.
  415. Abbrevs.set(RECORD_FILENAME, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG,
  416. Abbrev));
  417. // Emit the abbreviation for RECORD_FIXIT.
  418. Abbrev = new BitCodeAbbrev();
  419. Abbrev->Add(BitCodeAbbrevOp(RECORD_FIXIT));
  420. AddRangeLocationAbbrev(Abbrev);
  421. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
  422. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // FixIt text.
  423. Abbrevs.set(RECORD_FIXIT, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG,
  424. Abbrev));
  425. Stream.ExitBlock();
  426. }
  427. void SDiagsWriter::EmitMetaBlock() {
  428. llvm::BitstreamWriter &Stream = State->Stream;
  429. RecordData &Record = State->Record;
  430. AbbreviationMap &Abbrevs = State->Abbrevs;
  431. Stream.EnterSubblock(BLOCK_META, 3);
  432. Record.clear();
  433. Record.push_back(RECORD_VERSION);
  434. Record.push_back(VersionNumber);
  435. Stream.EmitRecordWithAbbrev(Abbrevs.get(RECORD_VERSION), Record);
  436. Stream.ExitBlock();
  437. }
  438. unsigned SDiagsWriter::getEmitCategory(unsigned int category) {
  439. if (!State->Categories.insert(category).second)
  440. return category;
  441. // We use a local version of 'Record' so that we can be generating
  442. // another record when we lazily generate one for the category entry.
  443. RecordData Record;
  444. Record.push_back(RECORD_CATEGORY);
  445. Record.push_back(category);
  446. StringRef catName = DiagnosticIDs::getCategoryNameFromID(category);
  447. Record.push_back(catName.size());
  448. State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_CATEGORY), Record,
  449. catName);
  450. return category;
  451. }
  452. unsigned SDiagsWriter::getEmitDiagnosticFlag(DiagnosticsEngine::Level DiagLevel,
  453. unsigned DiagID) {
  454. if (DiagLevel == DiagnosticsEngine::Note)
  455. return 0; // No flag for notes.
  456. StringRef FlagName = DiagnosticIDs::getWarningOptionForDiag(DiagID);
  457. return getEmitDiagnosticFlag(FlagName);
  458. }
  459. unsigned SDiagsWriter::getEmitDiagnosticFlag(StringRef FlagName) {
  460. if (FlagName.empty())
  461. return 0;
  462. // Here we assume that FlagName points to static data whose pointer
  463. // value is fixed. This allows us to unique by diagnostic groups.
  464. const void *data = FlagName.data();
  465. std::pair<unsigned, StringRef> &entry = State->DiagFlags[data];
  466. if (entry.first == 0) {
  467. entry.first = State->DiagFlags.size();
  468. entry.second = FlagName;
  469. // Lazily emit the string in a separate record.
  470. RecordData Record;
  471. Record.push_back(RECORD_DIAG_FLAG);
  472. Record.push_back(entry.first);
  473. Record.push_back(FlagName.size());
  474. State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_DIAG_FLAG),
  475. Record, FlagName);
  476. }
  477. return entry.first;
  478. }
  479. void SDiagsWriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
  480. const Diagnostic &Info) {
  481. // Enter the block for a non-note diagnostic immediately, rather than waiting
  482. // for beginDiagnostic, in case associated notes are emitted before we get
  483. // there.
  484. if (DiagLevel != DiagnosticsEngine::Note) {
  485. if (State->EmittedAnyDiagBlocks)
  486. ExitDiagBlock();
  487. EnterDiagBlock();
  488. State->EmittedAnyDiagBlocks = true;
  489. }
  490. // Compute the diagnostic text.
  491. State->diagBuf.clear();
  492. Info.FormatDiagnostic(State->diagBuf);
  493. if (Info.getLocation().isInvalid()) {
  494. // Special-case diagnostics with no location. We may not have entered a
  495. // source file in this case, so we can't use the normal DiagnosticsRenderer
  496. // machinery.
  497. // Make sure we bracket all notes as "sub-diagnostics". This matches
  498. // the behavior in SDiagsRenderer::emitDiagnostic().
  499. if (DiagLevel == DiagnosticsEngine::Note)
  500. EnterDiagBlock();
  501. EmitDiagnosticMessage(SourceLocation(), PresumedLoc(), DiagLevel,
  502. State->diagBuf, nullptr, &Info);
  503. if (DiagLevel == DiagnosticsEngine::Note)
  504. ExitDiagBlock();
  505. return;
  506. }
  507. assert(Info.hasSourceManager() && LangOpts &&
  508. "Unexpected diagnostic with valid location outside of a source file");
  509. SDiagsRenderer Renderer(*this, *LangOpts, &*State->DiagOpts);
  510. Renderer.emitDiagnostic(Info.getLocation(), DiagLevel,
  511. State->diagBuf,
  512. Info.getRanges(),
  513. Info.getFixItHints(),
  514. &Info.getSourceManager(),
  515. &Info);
  516. }
  517. static serialized_diags::Level getStableLevel(DiagnosticsEngine::Level Level) {
  518. switch (Level) {
  519. #define CASE(X) case DiagnosticsEngine::X: return serialized_diags::X;
  520. CASE(Ignored)
  521. CASE(Note)
  522. CASE(Remark)
  523. CASE(Warning)
  524. CASE(Error)
  525. CASE(Fatal)
  526. #undef CASE
  527. }
  528. llvm_unreachable("invalid diagnostic level");
  529. }
  530. void SDiagsWriter::EmitDiagnosticMessage(SourceLocation Loc,
  531. PresumedLoc PLoc,
  532. DiagnosticsEngine::Level Level,
  533. StringRef Message,
  534. const SourceManager *SM,
  535. DiagOrStoredDiag D) {
  536. llvm::BitstreamWriter &Stream = State->Stream;
  537. RecordData &Record = State->Record;
  538. AbbreviationMap &Abbrevs = State->Abbrevs;
  539. // Emit the RECORD_DIAG record.
  540. Record.clear();
  541. Record.push_back(RECORD_DIAG);
  542. Record.push_back(getStableLevel(Level));
  543. AddLocToRecord(Loc, SM, PLoc, Record);
  544. if (const Diagnostic *Info = D.dyn_cast<const Diagnostic*>()) {
  545. // Emit the category string lazily and get the category ID.
  546. unsigned DiagID = DiagnosticIDs::getCategoryNumberForDiag(Info->getID());
  547. Record.push_back(getEmitCategory(DiagID));
  548. // Emit the diagnostic flag string lazily and get the mapped ID.
  549. Record.push_back(getEmitDiagnosticFlag(Level, Info->getID()));
  550. } else {
  551. Record.push_back(getEmitCategory());
  552. Record.push_back(getEmitDiagnosticFlag(Level));
  553. }
  554. Record.push_back(Message.size());
  555. Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_DIAG), Record, Message);
  556. }
  557. void
  558. SDiagsRenderer::emitDiagnosticMessage(SourceLocation Loc,
  559. PresumedLoc PLoc,
  560. DiagnosticsEngine::Level Level,
  561. StringRef Message,
  562. ArrayRef<clang::CharSourceRange> Ranges,
  563. const SourceManager *SM,
  564. DiagOrStoredDiag D) {
  565. Writer.EmitDiagnosticMessage(Loc, PLoc, Level, Message, SM, D);
  566. }
  567. void SDiagsWriter::EnterDiagBlock() {
  568. State->Stream.EnterSubblock(BLOCK_DIAG, 4);
  569. }
  570. void SDiagsWriter::ExitDiagBlock() {
  571. State->Stream.ExitBlock();
  572. }
  573. void SDiagsRenderer::beginDiagnostic(DiagOrStoredDiag D,
  574. DiagnosticsEngine::Level Level) {
  575. if (Level == DiagnosticsEngine::Note)
  576. Writer.EnterDiagBlock();
  577. }
  578. void SDiagsRenderer::endDiagnostic(DiagOrStoredDiag D,
  579. DiagnosticsEngine::Level Level) {
  580. // Only end note diagnostics here, because we can't be sure when we've seen
  581. // the last note associated with a non-note diagnostic.
  582. if (Level == DiagnosticsEngine::Note)
  583. Writer.ExitDiagBlock();
  584. }
  585. void SDiagsWriter::EmitCodeContext(SmallVectorImpl<CharSourceRange> &Ranges,
  586. ArrayRef<FixItHint> Hints,
  587. const SourceManager &SM) {
  588. llvm::BitstreamWriter &Stream = State->Stream;
  589. RecordData &Record = State->Record;
  590. AbbreviationMap &Abbrevs = State->Abbrevs;
  591. // Emit Source Ranges.
  592. for (ArrayRef<CharSourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
  593. I != E; ++I)
  594. if (I->isValid())
  595. EmitCharSourceRange(*I, SM);
  596. // Emit FixIts.
  597. for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
  598. I != E; ++I) {
  599. const FixItHint &Fix = *I;
  600. if (Fix.isNull())
  601. continue;
  602. Record.clear();
  603. Record.push_back(RECORD_FIXIT);
  604. AddCharSourceRangeToRecord(Fix.RemoveRange, Record, SM);
  605. Record.push_back(Fix.CodeToInsert.size());
  606. Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_FIXIT), Record,
  607. Fix.CodeToInsert);
  608. }
  609. }
  610. void SDiagsRenderer::emitCodeContext(SourceLocation Loc,
  611. DiagnosticsEngine::Level Level,
  612. SmallVectorImpl<CharSourceRange> &Ranges,
  613. ArrayRef<FixItHint> Hints,
  614. const SourceManager &SM) {
  615. Writer.EmitCodeContext(Ranges, Hints, SM);
  616. }
  617. void SDiagsRenderer::emitNote(SourceLocation Loc, StringRef Message,
  618. const SourceManager *SM) {
  619. Writer.EnterDiagBlock();
  620. PresumedLoc PLoc = SM ? SM->getPresumedLoc(Loc) : PresumedLoc();
  621. Writer.EmitDiagnosticMessage(Loc, PLoc, DiagnosticsEngine::Note,
  622. Message, SM, DiagOrStoredDiag());
  623. Writer.ExitDiagBlock();
  624. }
  625. DiagnosticsEngine *SDiagsWriter::getMetaDiags() {
  626. // FIXME: It's slightly absurd to create a new diagnostics engine here, but
  627. // the other options that are available today are worse:
  628. //
  629. // 1. Teach DiagnosticsConsumers to emit diagnostics to the engine they are a
  630. // part of. The DiagnosticsEngine would need to know not to send
  631. // diagnostics back to the consumer that failed. This would require us to
  632. // rework ChainedDiagnosticsConsumer and teach the engine about multiple
  633. // consumers, which is difficult today because most APIs interface with
  634. // consumers rather than the engine itself.
  635. //
  636. // 2. Pass a DiagnosticsEngine to SDiagsWriter on creation - this would need
  637. // to be distinct from the engine the writer was being added to and would
  638. // normally not be used.
  639. if (!State->MetaDiagnostics) {
  640. IntrusiveRefCntPtr<DiagnosticIDs> IDs(new DiagnosticIDs());
  641. auto Client =
  642. new TextDiagnosticPrinter(llvm::errs(), State->DiagOpts.get());
  643. State->MetaDiagnostics = llvm::make_unique<DiagnosticsEngine>(
  644. IDs, State->DiagOpts.get(), Client);
  645. }
  646. return State->MetaDiagnostics.get();
  647. }
  648. void SDiagsWriter::RemoveOldDiagnostics() {
  649. if (!llvm::sys::fs::remove(State->OutputFile))
  650. return;
  651. getMetaDiags()->Report(diag::warn_fe_serialized_diag_merge_failure);
  652. // Disable merging child records, as whatever is in this file may be
  653. // misleading.
  654. MergeChildRecords = false;
  655. }
  656. void SDiagsWriter::finish() {
  657. // The original instance is responsible for writing the file.
  658. if (!OriginalInstance)
  659. return;
  660. // Finish off any diagnostic we were in the process of emitting.
  661. if (State->EmittedAnyDiagBlocks)
  662. ExitDiagBlock();
  663. if (MergeChildRecords) {
  664. if (!State->EmittedAnyDiagBlocks)
  665. // We have no diagnostics of our own, so we can just leave the child
  666. // process' output alone
  667. return;
  668. if (llvm::sys::fs::exists(State->OutputFile))
  669. if (SDiagsMerger(*this).mergeRecordsFromFile(State->OutputFile.c_str()))
  670. getMetaDiags()->Report(diag::warn_fe_serialized_diag_merge_failure);
  671. }
  672. std::error_code EC;
  673. auto OS = llvm::make_unique<llvm::raw_fd_ostream>(State->OutputFile.c_str(),
  674. EC, llvm::sys::fs::F_None);
  675. if (EC) {
  676. getMetaDiags()->Report(diag::warn_fe_serialized_diag_failure)
  677. << State->OutputFile << EC.message();
  678. return;
  679. }
  680. // Write the generated bitstream to "Out".
  681. OS->write((char *)&State->Buffer.front(), State->Buffer.size());
  682. OS->flush();
  683. }
  684. std::error_code SDiagsMerger::visitStartOfDiagnostic() {
  685. Writer.EnterDiagBlock();
  686. return std::error_code();
  687. }
  688. std::error_code SDiagsMerger::visitEndOfDiagnostic() {
  689. Writer.ExitDiagBlock();
  690. return std::error_code();
  691. }
  692. std::error_code
  693. SDiagsMerger::visitSourceRangeRecord(const serialized_diags::Location &Start,
  694. const serialized_diags::Location &End) {
  695. RecordData Record;
  696. Record.push_back(RECORD_SOURCE_RANGE);
  697. Record.push_back(FileLookup[Start.FileID]);
  698. Record.push_back(Start.Line);
  699. Record.push_back(Start.Col);
  700. Record.push_back(Start.Offset);
  701. Record.push_back(FileLookup[End.FileID]);
  702. Record.push_back(End.Line);
  703. Record.push_back(End.Col);
  704. Record.push_back(End.Offset);
  705. Writer.State->Stream.EmitRecordWithAbbrev(
  706. Writer.State->Abbrevs.get(RECORD_SOURCE_RANGE), Record);
  707. return std::error_code();
  708. }
  709. std::error_code SDiagsMerger::visitDiagnosticRecord(
  710. unsigned Severity, const serialized_diags::Location &Location,
  711. unsigned Category, unsigned Flag, StringRef Message) {
  712. RecordData MergedRecord;
  713. MergedRecord.push_back(RECORD_DIAG);
  714. MergedRecord.push_back(Severity);
  715. MergedRecord.push_back(FileLookup[Location.FileID]);
  716. MergedRecord.push_back(Location.Line);
  717. MergedRecord.push_back(Location.Col);
  718. MergedRecord.push_back(Location.Offset);
  719. MergedRecord.push_back(CategoryLookup[Category]);
  720. MergedRecord.push_back(Flag ? DiagFlagLookup[Flag] : 0);
  721. MergedRecord.push_back(Message.size());
  722. Writer.State->Stream.EmitRecordWithBlob(
  723. Writer.State->Abbrevs.get(RECORD_DIAG), MergedRecord, Message);
  724. return std::error_code();
  725. }
  726. std::error_code
  727. SDiagsMerger::visitFixitRecord(const serialized_diags::Location &Start,
  728. const serialized_diags::Location &End,
  729. StringRef Text) {
  730. RecordData Record;
  731. Record.push_back(RECORD_FIXIT);
  732. Record.push_back(FileLookup[Start.FileID]);
  733. Record.push_back(Start.Line);
  734. Record.push_back(Start.Col);
  735. Record.push_back(Start.Offset);
  736. Record.push_back(FileLookup[End.FileID]);
  737. Record.push_back(End.Line);
  738. Record.push_back(End.Col);
  739. Record.push_back(End.Offset);
  740. Record.push_back(Text.size());
  741. Writer.State->Stream.EmitRecordWithBlob(
  742. Writer.State->Abbrevs.get(RECORD_FIXIT), Record, Text);
  743. return std::error_code();
  744. }
  745. std::error_code SDiagsMerger::visitFilenameRecord(unsigned ID, unsigned Size,
  746. unsigned Timestamp,
  747. StringRef Name) {
  748. FileLookup[ID] = Writer.getEmitFile(Name.str().c_str());
  749. return std::error_code();
  750. }
  751. std::error_code SDiagsMerger::visitCategoryRecord(unsigned ID, StringRef Name) {
  752. CategoryLookup[ID] = Writer.getEmitCategory(ID);
  753. return std::error_code();
  754. }
  755. std::error_code SDiagsMerger::visitDiagFlagRecord(unsigned ID, StringRef Name) {
  756. DiagFlagLookup[ID] = Writer.getEmitDiagnosticFlag(Name);
  757. return std::error_code();
  758. }