SerializedDiagnosticPrinter.cpp 32 KB

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