SerializedDiagnosticPrinter.cpp 31 KB

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