GlobalModuleIndex.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. //===--- GlobalModuleIndex.cpp - Global Module Index ------------*- C++ -*-===//
  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. //
  9. // This file implements the GlobalModuleIndex class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "ASTReaderInternals.h"
  13. #include "clang/Basic/FileManager.h"
  14. #include "clang/Lex/HeaderSearch.h"
  15. #include "clang/Serialization/ASTBitCodes.h"
  16. #include "clang/Serialization/GlobalModuleIndex.h"
  17. #include "clang/Serialization/Module.h"
  18. #include "clang/Serialization/PCHContainerOperations.h"
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/MapVector.h"
  21. #include "llvm/ADT/SmallString.h"
  22. #include "llvm/Bitstream/BitstreamReader.h"
  23. #include "llvm/Bitstream/BitstreamWriter.h"
  24. #include "llvm/Support/DJB.h"
  25. #include "llvm/Support/FileSystem.h"
  26. #include "llvm/Support/LockFileManager.h"
  27. #include "llvm/Support/MemoryBuffer.h"
  28. #include "llvm/Support/OnDiskHashTable.h"
  29. #include "llvm/Support/Path.h"
  30. #include "llvm/Support/TimeProfiler.h"
  31. #include <cstdio>
  32. using namespace clang;
  33. using namespace serialization;
  34. //----------------------------------------------------------------------------//
  35. // Shared constants
  36. //----------------------------------------------------------------------------//
  37. namespace {
  38. enum {
  39. /// The block containing the index.
  40. GLOBAL_INDEX_BLOCK_ID = llvm::bitc::FIRST_APPLICATION_BLOCKID
  41. };
  42. /// Describes the record types in the index.
  43. enum IndexRecordTypes {
  44. /// Contains version information and potentially other metadata,
  45. /// used to determine if we can read this global index file.
  46. INDEX_METADATA,
  47. /// Describes a module, including its file name and dependencies.
  48. MODULE,
  49. /// The index for identifiers.
  50. IDENTIFIER_INDEX
  51. };
  52. }
  53. /// The name of the global index file.
  54. static const char * const IndexFileName = "modules.idx";
  55. /// The global index file version.
  56. static const unsigned CurrentVersion = 1;
  57. //----------------------------------------------------------------------------//
  58. // Global module index reader.
  59. //----------------------------------------------------------------------------//
  60. namespace {
  61. /// Trait used to read the identifier index from the on-disk hash
  62. /// table.
  63. class IdentifierIndexReaderTrait {
  64. public:
  65. typedef StringRef external_key_type;
  66. typedef StringRef internal_key_type;
  67. typedef SmallVector<unsigned, 2> data_type;
  68. typedef unsigned hash_value_type;
  69. typedef unsigned offset_type;
  70. static bool EqualKey(const internal_key_type& a, const internal_key_type& b) {
  71. return a == b;
  72. }
  73. static hash_value_type ComputeHash(const internal_key_type& a) {
  74. return llvm::djbHash(a);
  75. }
  76. static std::pair<unsigned, unsigned>
  77. ReadKeyDataLength(const unsigned char*& d) {
  78. using namespace llvm::support;
  79. unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
  80. unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
  81. return std::make_pair(KeyLen, DataLen);
  82. }
  83. static const internal_key_type&
  84. GetInternalKey(const external_key_type& x) { return x; }
  85. static const external_key_type&
  86. GetExternalKey(const internal_key_type& x) { return x; }
  87. static internal_key_type ReadKey(const unsigned char* d, unsigned n) {
  88. return StringRef((const char *)d, n);
  89. }
  90. static data_type ReadData(const internal_key_type& k,
  91. const unsigned char* d,
  92. unsigned DataLen) {
  93. using namespace llvm::support;
  94. data_type Result;
  95. while (DataLen > 0) {
  96. unsigned ID = endian::readNext<uint32_t, little, unaligned>(d);
  97. Result.push_back(ID);
  98. DataLen -= 4;
  99. }
  100. return Result;
  101. }
  102. };
  103. typedef llvm::OnDiskIterableChainedHashTable<IdentifierIndexReaderTrait>
  104. IdentifierIndexTable;
  105. }
  106. GlobalModuleIndex::GlobalModuleIndex(std::unique_ptr<llvm::MemoryBuffer> Buffer,
  107. llvm::BitstreamCursor Cursor)
  108. : Buffer(std::move(Buffer)), IdentifierIndex(), NumIdentifierLookups(),
  109. NumIdentifierLookupHits() {
  110. auto Fail = [&Buffer](llvm::Error &&Err) {
  111. report_fatal_error("Module index '" + Buffer->getBufferIdentifier() +
  112. "' failed: " + toString(std::move(Err)));
  113. };
  114. llvm::TimeTraceScope TimeScope("Module LoadIndex", StringRef(""));
  115. // Read the global index.
  116. bool InGlobalIndexBlock = false;
  117. bool Done = false;
  118. while (!Done) {
  119. llvm::BitstreamEntry Entry;
  120. if (Expected<llvm::BitstreamEntry> Res = Cursor.advance())
  121. Entry = Res.get();
  122. else
  123. Fail(Res.takeError());
  124. switch (Entry.Kind) {
  125. case llvm::BitstreamEntry::Error:
  126. return;
  127. case llvm::BitstreamEntry::EndBlock:
  128. if (InGlobalIndexBlock) {
  129. InGlobalIndexBlock = false;
  130. Done = true;
  131. continue;
  132. }
  133. return;
  134. case llvm::BitstreamEntry::Record:
  135. // Entries in the global index block are handled below.
  136. if (InGlobalIndexBlock)
  137. break;
  138. return;
  139. case llvm::BitstreamEntry::SubBlock:
  140. if (!InGlobalIndexBlock && Entry.ID == GLOBAL_INDEX_BLOCK_ID) {
  141. if (llvm::Error Err = Cursor.EnterSubBlock(GLOBAL_INDEX_BLOCK_ID))
  142. Fail(std::move(Err));
  143. InGlobalIndexBlock = true;
  144. } else if (llvm::Error Err = Cursor.SkipBlock())
  145. Fail(std::move(Err));
  146. continue;
  147. }
  148. SmallVector<uint64_t, 64> Record;
  149. StringRef Blob;
  150. Expected<unsigned> MaybeIndexRecord =
  151. Cursor.readRecord(Entry.ID, Record, &Blob);
  152. if (!MaybeIndexRecord)
  153. Fail(MaybeIndexRecord.takeError());
  154. IndexRecordTypes IndexRecord =
  155. static_cast<IndexRecordTypes>(MaybeIndexRecord.get());
  156. switch (IndexRecord) {
  157. case INDEX_METADATA:
  158. // Make sure that the version matches.
  159. if (Record.size() < 1 || Record[0] != CurrentVersion)
  160. return;
  161. break;
  162. case MODULE: {
  163. unsigned Idx = 0;
  164. unsigned ID = Record[Idx++];
  165. // Make room for this module's information.
  166. if (ID == Modules.size())
  167. Modules.push_back(ModuleInfo());
  168. else
  169. Modules.resize(ID + 1);
  170. // Size/modification time for this module file at the time the
  171. // global index was built.
  172. Modules[ID].Size = Record[Idx++];
  173. Modules[ID].ModTime = Record[Idx++];
  174. // File name.
  175. unsigned NameLen = Record[Idx++];
  176. Modules[ID].FileName.assign(Record.begin() + Idx,
  177. Record.begin() + Idx + NameLen);
  178. Idx += NameLen;
  179. // Dependencies
  180. unsigned NumDeps = Record[Idx++];
  181. Modules[ID].Dependencies.insert(Modules[ID].Dependencies.end(),
  182. Record.begin() + Idx,
  183. Record.begin() + Idx + NumDeps);
  184. Idx += NumDeps;
  185. // Make sure we're at the end of the record.
  186. assert(Idx == Record.size() && "More module info?");
  187. // Record this module as an unresolved module.
  188. // FIXME: this doesn't work correctly for module names containing path
  189. // separators.
  190. StringRef ModuleName = llvm::sys::path::stem(Modules[ID].FileName);
  191. // Remove the -<hash of ModuleMapPath>
  192. ModuleName = ModuleName.rsplit('-').first;
  193. UnresolvedModules[ModuleName] = ID;
  194. break;
  195. }
  196. case IDENTIFIER_INDEX:
  197. // Wire up the identifier index.
  198. if (Record[0]) {
  199. IdentifierIndex = IdentifierIndexTable::Create(
  200. (const unsigned char *)Blob.data() + Record[0],
  201. (const unsigned char *)Blob.data() + sizeof(uint32_t),
  202. (const unsigned char *)Blob.data(), IdentifierIndexReaderTrait());
  203. }
  204. break;
  205. }
  206. }
  207. }
  208. GlobalModuleIndex::~GlobalModuleIndex() {
  209. delete static_cast<IdentifierIndexTable *>(IdentifierIndex);
  210. }
  211. std::pair<GlobalModuleIndex *, llvm::Error>
  212. GlobalModuleIndex::readIndex(StringRef Path) {
  213. // Load the index file, if it's there.
  214. llvm::SmallString<128> IndexPath;
  215. IndexPath += Path;
  216. llvm::sys::path::append(IndexPath, IndexFileName);
  217. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferOrErr =
  218. llvm::MemoryBuffer::getFile(IndexPath.c_str());
  219. if (!BufferOrErr)
  220. return std::make_pair(nullptr,
  221. llvm::errorCodeToError(BufferOrErr.getError()));
  222. std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(BufferOrErr.get());
  223. /// The main bitstream cursor for the main block.
  224. llvm::BitstreamCursor Cursor(*Buffer);
  225. // Sniff for the signature.
  226. for (unsigned char C : {'B', 'C', 'G', 'I'}) {
  227. if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Cursor.Read(8)) {
  228. if (Res.get() != C)
  229. return std::make_pair(
  230. nullptr, llvm::createStringError(std::errc::illegal_byte_sequence,
  231. "expected signature BCGI"));
  232. } else
  233. return std::make_pair(nullptr, Res.takeError());
  234. }
  235. return std::make_pair(new GlobalModuleIndex(std::move(Buffer), Cursor),
  236. llvm::Error::success());
  237. }
  238. void
  239. GlobalModuleIndex::getKnownModules(SmallVectorImpl<ModuleFile *> &ModuleFiles) {
  240. ModuleFiles.clear();
  241. for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
  242. if (ModuleFile *MF = Modules[I].File)
  243. ModuleFiles.push_back(MF);
  244. }
  245. }
  246. void GlobalModuleIndex::getModuleDependencies(
  247. ModuleFile *File,
  248. SmallVectorImpl<ModuleFile *> &Dependencies) {
  249. // Look for information about this module file.
  250. llvm::DenseMap<ModuleFile *, unsigned>::iterator Known
  251. = ModulesByFile.find(File);
  252. if (Known == ModulesByFile.end())
  253. return;
  254. // Record dependencies.
  255. Dependencies.clear();
  256. ArrayRef<unsigned> StoredDependencies = Modules[Known->second].Dependencies;
  257. for (unsigned I = 0, N = StoredDependencies.size(); I != N; ++I) {
  258. if (ModuleFile *MF = Modules[I].File)
  259. Dependencies.push_back(MF);
  260. }
  261. }
  262. bool GlobalModuleIndex::lookupIdentifier(StringRef Name, HitSet &Hits) {
  263. Hits.clear();
  264. // If there's no identifier index, there is nothing we can do.
  265. if (!IdentifierIndex)
  266. return false;
  267. // Look into the identifier index.
  268. ++NumIdentifierLookups;
  269. IdentifierIndexTable &Table
  270. = *static_cast<IdentifierIndexTable *>(IdentifierIndex);
  271. IdentifierIndexTable::iterator Known = Table.find(Name);
  272. if (Known == Table.end()) {
  273. return true;
  274. }
  275. SmallVector<unsigned, 2> ModuleIDs = *Known;
  276. for (unsigned I = 0, N = ModuleIDs.size(); I != N; ++I) {
  277. if (ModuleFile *MF = Modules[ModuleIDs[I]].File)
  278. Hits.insert(MF);
  279. }
  280. ++NumIdentifierLookupHits;
  281. return true;
  282. }
  283. bool GlobalModuleIndex::loadedModuleFile(ModuleFile *File) {
  284. // Look for the module in the global module index based on the module name.
  285. StringRef Name = File->ModuleName;
  286. llvm::StringMap<unsigned>::iterator Known = UnresolvedModules.find(Name);
  287. if (Known == UnresolvedModules.end()) {
  288. return true;
  289. }
  290. // Rectify this module with the global module index.
  291. ModuleInfo &Info = Modules[Known->second];
  292. // If the size and modification time match what we expected, record this
  293. // module file.
  294. bool Failed = true;
  295. if (File->File->getSize() == Info.Size &&
  296. File->File->getModificationTime() == Info.ModTime) {
  297. Info.File = File;
  298. ModulesByFile[File] = Known->second;
  299. Failed = false;
  300. }
  301. // One way or another, we have resolved this module file.
  302. UnresolvedModules.erase(Known);
  303. return Failed;
  304. }
  305. void GlobalModuleIndex::printStats() {
  306. std::fprintf(stderr, "*** Global Module Index Statistics:\n");
  307. if (NumIdentifierLookups) {
  308. fprintf(stderr, " %u / %u identifier lookups succeeded (%f%%)\n",
  309. NumIdentifierLookupHits, NumIdentifierLookups,
  310. (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
  311. }
  312. std::fprintf(stderr, "\n");
  313. }
  314. LLVM_DUMP_METHOD void GlobalModuleIndex::dump() {
  315. llvm::errs() << "*** Global Module Index Dump:\n";
  316. llvm::errs() << "Module files:\n";
  317. for (auto &MI : Modules) {
  318. llvm::errs() << "** " << MI.FileName << "\n";
  319. if (MI.File)
  320. MI.File->dump();
  321. else
  322. llvm::errs() << "\n";
  323. }
  324. llvm::errs() << "\n";
  325. }
  326. //----------------------------------------------------------------------------//
  327. // Global module index writer.
  328. //----------------------------------------------------------------------------//
  329. namespace {
  330. /// Provides information about a specific module file.
  331. struct ModuleFileInfo {
  332. /// The numberic ID for this module file.
  333. unsigned ID;
  334. /// The set of modules on which this module depends. Each entry is
  335. /// a module ID.
  336. SmallVector<unsigned, 4> Dependencies;
  337. ASTFileSignature Signature;
  338. };
  339. struct ImportedModuleFileInfo {
  340. off_t StoredSize;
  341. time_t StoredModTime;
  342. ASTFileSignature StoredSignature;
  343. ImportedModuleFileInfo(off_t Size, time_t ModTime, ASTFileSignature Sig)
  344. : StoredSize(Size), StoredModTime(ModTime), StoredSignature(Sig) {}
  345. };
  346. /// Builder that generates the global module index file.
  347. class GlobalModuleIndexBuilder {
  348. FileManager &FileMgr;
  349. const PCHContainerReader &PCHContainerRdr;
  350. /// Mapping from files to module file information.
  351. typedef llvm::MapVector<const FileEntry *, ModuleFileInfo> ModuleFilesMap;
  352. /// Information about each of the known module files.
  353. ModuleFilesMap ModuleFiles;
  354. /// Mapping from the imported module file to the imported
  355. /// information.
  356. typedef std::multimap<const FileEntry *, ImportedModuleFileInfo>
  357. ImportedModuleFilesMap;
  358. /// Information about each importing of a module file.
  359. ImportedModuleFilesMap ImportedModuleFiles;
  360. /// Mapping from identifiers to the list of module file IDs that
  361. /// consider this identifier to be interesting.
  362. typedef llvm::StringMap<SmallVector<unsigned, 2> > InterestingIdentifierMap;
  363. /// A mapping from all interesting identifiers to the set of module
  364. /// files in which those identifiers are considered interesting.
  365. InterestingIdentifierMap InterestingIdentifiers;
  366. /// Write the block-info block for the global module index file.
  367. void emitBlockInfoBlock(llvm::BitstreamWriter &Stream);
  368. /// Retrieve the module file information for the given file.
  369. ModuleFileInfo &getModuleFileInfo(const FileEntry *File) {
  370. llvm::MapVector<const FileEntry *, ModuleFileInfo>::iterator Known
  371. = ModuleFiles.find(File);
  372. if (Known != ModuleFiles.end())
  373. return Known->second;
  374. unsigned NewID = ModuleFiles.size();
  375. ModuleFileInfo &Info = ModuleFiles[File];
  376. Info.ID = NewID;
  377. return Info;
  378. }
  379. public:
  380. explicit GlobalModuleIndexBuilder(
  381. FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr)
  382. : FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr) {}
  383. /// Load the contents of the given module file into the builder.
  384. llvm::Error loadModuleFile(const FileEntry *File);
  385. /// Write the index to the given bitstream.
  386. /// \returns true if an error occurred, false otherwise.
  387. bool writeIndex(llvm::BitstreamWriter &Stream);
  388. };
  389. }
  390. static void emitBlockID(unsigned ID, const char *Name,
  391. llvm::BitstreamWriter &Stream,
  392. SmallVectorImpl<uint64_t> &Record) {
  393. Record.clear();
  394. Record.push_back(ID);
  395. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
  396. // Emit the block name if present.
  397. if (!Name || Name[0] == 0) return;
  398. Record.clear();
  399. while (*Name)
  400. Record.push_back(*Name++);
  401. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
  402. }
  403. static void emitRecordID(unsigned ID, const char *Name,
  404. llvm::BitstreamWriter &Stream,
  405. SmallVectorImpl<uint64_t> &Record) {
  406. Record.clear();
  407. Record.push_back(ID);
  408. while (*Name)
  409. Record.push_back(*Name++);
  410. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
  411. }
  412. void
  413. GlobalModuleIndexBuilder::emitBlockInfoBlock(llvm::BitstreamWriter &Stream) {
  414. SmallVector<uint64_t, 64> Record;
  415. Stream.EnterBlockInfoBlock();
  416. #define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record)
  417. #define RECORD(X) emitRecordID(X, #X, Stream, Record)
  418. BLOCK(GLOBAL_INDEX_BLOCK);
  419. RECORD(INDEX_METADATA);
  420. RECORD(MODULE);
  421. RECORD(IDENTIFIER_INDEX);
  422. #undef RECORD
  423. #undef BLOCK
  424. Stream.ExitBlock();
  425. }
  426. namespace {
  427. class InterestingASTIdentifierLookupTrait
  428. : public serialization::reader::ASTIdentifierLookupTraitBase {
  429. public:
  430. /// The identifier and whether it is "interesting".
  431. typedef std::pair<StringRef, bool> data_type;
  432. data_type ReadData(const internal_key_type& k,
  433. const unsigned char* d,
  434. unsigned DataLen) {
  435. // The first bit indicates whether this identifier is interesting.
  436. // That's all we care about.
  437. using namespace llvm::support;
  438. unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
  439. bool IsInteresting = RawID & 0x01;
  440. return std::make_pair(k, IsInteresting);
  441. }
  442. };
  443. }
  444. llvm::Error GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
  445. // Open the module file.
  446. auto Buffer = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
  447. if (!Buffer)
  448. return llvm::createStringError(Buffer.getError(),
  449. "failed getting buffer for module file");
  450. // Initialize the input stream
  451. llvm::BitstreamCursor InStream(PCHContainerRdr.ExtractPCH(**Buffer));
  452. // Sniff for the signature.
  453. for (unsigned char C : {'C', 'P', 'C', 'H'})
  454. if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = InStream.Read(8)) {
  455. if (Res.get() != C)
  456. return llvm::createStringError(std::errc::illegal_byte_sequence,
  457. "expected signature CPCH");
  458. } else
  459. return Res.takeError();
  460. // Record this module file and assign it a unique ID (if it doesn't have
  461. // one already).
  462. unsigned ID = getModuleFileInfo(File).ID;
  463. // Search for the blocks and records we care about.
  464. enum { Other, ControlBlock, ASTBlock, DiagnosticOptionsBlock } State = Other;
  465. bool Done = false;
  466. while (!Done) {
  467. Expected<llvm::BitstreamEntry> MaybeEntry = InStream.advance();
  468. if (!MaybeEntry)
  469. return MaybeEntry.takeError();
  470. llvm::BitstreamEntry Entry = MaybeEntry.get();
  471. switch (Entry.Kind) {
  472. case llvm::BitstreamEntry::Error:
  473. Done = true;
  474. continue;
  475. case llvm::BitstreamEntry::Record:
  476. // In the 'other' state, just skip the record. We don't care.
  477. if (State == Other) {
  478. if (llvm::Expected<unsigned> Skipped = InStream.skipRecord(Entry.ID))
  479. continue;
  480. else
  481. return Skipped.takeError();
  482. }
  483. // Handle potentially-interesting records below.
  484. break;
  485. case llvm::BitstreamEntry::SubBlock:
  486. if (Entry.ID == CONTROL_BLOCK_ID) {
  487. if (llvm::Error Err = InStream.EnterSubBlock(CONTROL_BLOCK_ID))
  488. return Err;
  489. // Found the control block.
  490. State = ControlBlock;
  491. continue;
  492. }
  493. if (Entry.ID == AST_BLOCK_ID) {
  494. if (llvm::Error Err = InStream.EnterSubBlock(AST_BLOCK_ID))
  495. return Err;
  496. // Found the AST block.
  497. State = ASTBlock;
  498. continue;
  499. }
  500. if (Entry.ID == UNHASHED_CONTROL_BLOCK_ID) {
  501. if (llvm::Error Err = InStream.EnterSubBlock(UNHASHED_CONTROL_BLOCK_ID))
  502. return Err;
  503. // Found the Diagnostic Options block.
  504. State = DiagnosticOptionsBlock;
  505. continue;
  506. }
  507. if (llvm::Error Err = InStream.SkipBlock())
  508. return Err;
  509. continue;
  510. case llvm::BitstreamEntry::EndBlock:
  511. State = Other;
  512. continue;
  513. }
  514. // Read the given record.
  515. SmallVector<uint64_t, 64> Record;
  516. StringRef Blob;
  517. Expected<unsigned> MaybeCode = InStream.readRecord(Entry.ID, Record, &Blob);
  518. if (!MaybeCode)
  519. return MaybeCode.takeError();
  520. unsigned Code = MaybeCode.get();
  521. // Handle module dependencies.
  522. if (State == ControlBlock && Code == IMPORTS) {
  523. // Load each of the imported PCH files.
  524. unsigned Idx = 0, N = Record.size();
  525. while (Idx < N) {
  526. // Read information about the AST file.
  527. // Skip the imported kind
  528. ++Idx;
  529. // Skip the import location
  530. ++Idx;
  531. // Load stored size/modification time.
  532. off_t StoredSize = (off_t)Record[Idx++];
  533. time_t StoredModTime = (time_t)Record[Idx++];
  534. // Skip the stored signature.
  535. // FIXME: we could read the signature out of the import and validate it.
  536. ASTFileSignature StoredSignature = {
  537. {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
  538. (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
  539. (uint32_t)Record[Idx++]}}};
  540. // Skip the module name (currently this is only used for prebuilt
  541. // modules while here we are only dealing with cached).
  542. Idx += Record[Idx] + 1;
  543. // Retrieve the imported file name.
  544. unsigned Length = Record[Idx++];
  545. SmallString<128> ImportedFile(Record.begin() + Idx,
  546. Record.begin() + Idx + Length);
  547. Idx += Length;
  548. // Find the imported module file.
  549. const FileEntry *DependsOnFile
  550. = FileMgr.getFile(ImportedFile, /*OpenFile=*/false,
  551. /*CacheFailure=*/false);
  552. if (!DependsOnFile)
  553. return llvm::createStringError(std::errc::bad_file_descriptor,
  554. "imported file \"%s\" not found",
  555. ImportedFile.c_str());
  556. // Save the information in ImportedModuleFileInfo so we can verify after
  557. // loading all pcms.
  558. ImportedModuleFiles.insert(std::make_pair(
  559. DependsOnFile, ImportedModuleFileInfo(StoredSize, StoredModTime,
  560. StoredSignature)));
  561. // Record the dependency.
  562. unsigned DependsOnID = getModuleFileInfo(DependsOnFile).ID;
  563. getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
  564. }
  565. continue;
  566. }
  567. // Handle the identifier table
  568. if (State == ASTBlock && Code == IDENTIFIER_TABLE && Record[0] > 0) {
  569. typedef llvm::OnDiskIterableChainedHashTable<
  570. InterestingASTIdentifierLookupTrait> InterestingIdentifierTable;
  571. std::unique_ptr<InterestingIdentifierTable> Table(
  572. InterestingIdentifierTable::Create(
  573. (const unsigned char *)Blob.data() + Record[0],
  574. (const unsigned char *)Blob.data() + sizeof(uint32_t),
  575. (const unsigned char *)Blob.data()));
  576. for (InterestingIdentifierTable::data_iterator D = Table->data_begin(),
  577. DEnd = Table->data_end();
  578. D != DEnd; ++D) {
  579. std::pair<StringRef, bool> Ident = *D;
  580. if (Ident.second)
  581. InterestingIdentifiers[Ident.first].push_back(ID);
  582. else
  583. (void)InterestingIdentifiers[Ident.first];
  584. }
  585. }
  586. // Get Signature.
  587. if (State == DiagnosticOptionsBlock && Code == SIGNATURE)
  588. getModuleFileInfo(File).Signature = {
  589. {{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
  590. (uint32_t)Record[3], (uint32_t)Record[4]}}};
  591. // We don't care about this record.
  592. }
  593. return llvm::Error::success();
  594. }
  595. namespace {
  596. /// Trait used to generate the identifier index as an on-disk hash
  597. /// table.
  598. class IdentifierIndexWriterTrait {
  599. public:
  600. typedef StringRef key_type;
  601. typedef StringRef key_type_ref;
  602. typedef SmallVector<unsigned, 2> data_type;
  603. typedef const SmallVector<unsigned, 2> &data_type_ref;
  604. typedef unsigned hash_value_type;
  605. typedef unsigned offset_type;
  606. static hash_value_type ComputeHash(key_type_ref Key) {
  607. return llvm::djbHash(Key);
  608. }
  609. std::pair<unsigned,unsigned>
  610. EmitKeyDataLength(raw_ostream& Out, key_type_ref Key, data_type_ref Data) {
  611. using namespace llvm::support;
  612. endian::Writer LE(Out, little);
  613. unsigned KeyLen = Key.size();
  614. unsigned DataLen = Data.size() * 4;
  615. LE.write<uint16_t>(KeyLen);
  616. LE.write<uint16_t>(DataLen);
  617. return std::make_pair(KeyLen, DataLen);
  618. }
  619. void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
  620. Out.write(Key.data(), KeyLen);
  621. }
  622. void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
  623. unsigned DataLen) {
  624. using namespace llvm::support;
  625. for (unsigned I = 0, N = Data.size(); I != N; ++I)
  626. endian::write<uint32_t>(Out, Data[I], little);
  627. }
  628. };
  629. }
  630. bool GlobalModuleIndexBuilder::writeIndex(llvm::BitstreamWriter &Stream) {
  631. for (auto MapEntry : ImportedModuleFiles) {
  632. auto *File = MapEntry.first;
  633. ImportedModuleFileInfo &Info = MapEntry.second;
  634. if (getModuleFileInfo(File).Signature) {
  635. if (getModuleFileInfo(File).Signature != Info.StoredSignature)
  636. // Verify Signature.
  637. return true;
  638. } else if (Info.StoredSize != File->getSize() ||
  639. Info.StoredModTime != File->getModificationTime())
  640. // Verify Size and ModTime.
  641. return true;
  642. }
  643. using namespace llvm;
  644. llvm::TimeTraceScope TimeScope("Module WriteIndex", StringRef(""));
  645. // Emit the file header.
  646. Stream.Emit((unsigned)'B', 8);
  647. Stream.Emit((unsigned)'C', 8);
  648. Stream.Emit((unsigned)'G', 8);
  649. Stream.Emit((unsigned)'I', 8);
  650. // Write the block-info block, which describes the records in this bitcode
  651. // file.
  652. emitBlockInfoBlock(Stream);
  653. Stream.EnterSubblock(GLOBAL_INDEX_BLOCK_ID, 3);
  654. // Write the metadata.
  655. SmallVector<uint64_t, 2> Record;
  656. Record.push_back(CurrentVersion);
  657. Stream.EmitRecord(INDEX_METADATA, Record);
  658. // Write the set of known module files.
  659. for (ModuleFilesMap::iterator M = ModuleFiles.begin(),
  660. MEnd = ModuleFiles.end();
  661. M != MEnd; ++M) {
  662. Record.clear();
  663. Record.push_back(M->second.ID);
  664. Record.push_back(M->first->getSize());
  665. Record.push_back(M->first->getModificationTime());
  666. // File name
  667. StringRef Name(M->first->getName());
  668. Record.push_back(Name.size());
  669. Record.append(Name.begin(), Name.end());
  670. // Dependencies
  671. Record.push_back(M->second.Dependencies.size());
  672. Record.append(M->second.Dependencies.begin(), M->second.Dependencies.end());
  673. Stream.EmitRecord(MODULE, Record);
  674. }
  675. // Write the identifier -> module file mapping.
  676. {
  677. llvm::OnDiskChainedHashTableGenerator<IdentifierIndexWriterTrait> Generator;
  678. IdentifierIndexWriterTrait Trait;
  679. // Populate the hash table.
  680. for (InterestingIdentifierMap::iterator I = InterestingIdentifiers.begin(),
  681. IEnd = InterestingIdentifiers.end();
  682. I != IEnd; ++I) {
  683. Generator.insert(I->first(), I->second, Trait);
  684. }
  685. // Create the on-disk hash table in a buffer.
  686. SmallString<4096> IdentifierTable;
  687. uint32_t BucketOffset;
  688. {
  689. using namespace llvm::support;
  690. llvm::raw_svector_ostream Out(IdentifierTable);
  691. // Make sure that no bucket is at offset 0
  692. endian::write<uint32_t>(Out, 0, little);
  693. BucketOffset = Generator.Emit(Out, Trait);
  694. }
  695. // Create a blob abbreviation
  696. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  697. Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_INDEX));
  698. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  699. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  700. unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  701. // Write the identifier table
  702. uint64_t Record[] = {IDENTIFIER_INDEX, BucketOffset};
  703. Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
  704. }
  705. Stream.ExitBlock();
  706. return false;
  707. }
  708. llvm::Error
  709. GlobalModuleIndex::writeIndex(FileManager &FileMgr,
  710. const PCHContainerReader &PCHContainerRdr,
  711. StringRef Path) {
  712. llvm::SmallString<128> IndexPath;
  713. IndexPath += Path;
  714. llvm::sys::path::append(IndexPath, IndexFileName);
  715. // Coordinate building the global index file with other processes that might
  716. // try to do the same.
  717. llvm::LockFileManager Locked(IndexPath);
  718. switch (Locked) {
  719. case llvm::LockFileManager::LFS_Error:
  720. return llvm::createStringError(std::errc::io_error, "LFS error");
  721. case llvm::LockFileManager::LFS_Owned:
  722. // We're responsible for building the index ourselves. Do so below.
  723. break;
  724. case llvm::LockFileManager::LFS_Shared:
  725. // Someone else is responsible for building the index. We don't care
  726. // when they finish, so we're done.
  727. return llvm::createStringError(std::errc::device_or_resource_busy,
  728. "someone else is building the index");
  729. }
  730. // The module index builder.
  731. GlobalModuleIndexBuilder Builder(FileMgr, PCHContainerRdr);
  732. // Load each of the module files.
  733. std::error_code EC;
  734. for (llvm::sys::fs::directory_iterator D(Path, EC), DEnd;
  735. D != DEnd && !EC;
  736. D.increment(EC)) {
  737. // If this isn't a module file, we don't care.
  738. if (llvm::sys::path::extension(D->path()) != ".pcm") {
  739. // ... unless it's a .pcm.lock file, which indicates that someone is
  740. // in the process of rebuilding a module. They'll rebuild the index
  741. // at the end of that translation unit, so we don't have to.
  742. if (llvm::sys::path::extension(D->path()) == ".pcm.lock")
  743. return llvm::createStringError(std::errc::device_or_resource_busy,
  744. "someone else is building the index");
  745. continue;
  746. }
  747. // If we can't find the module file, skip it.
  748. const FileEntry *ModuleFile = FileMgr.getFile(D->path());
  749. if (!ModuleFile)
  750. continue;
  751. // Load this module file.
  752. if (llvm::Error Err = Builder.loadModuleFile(ModuleFile))
  753. return Err;
  754. }
  755. // The output buffer, into which the global index will be written.
  756. SmallVector<char, 16> OutputBuffer;
  757. {
  758. llvm::BitstreamWriter OutputStream(OutputBuffer);
  759. if (Builder.writeIndex(OutputStream))
  760. return llvm::createStringError(std::errc::io_error,
  761. "failed writing index");
  762. }
  763. // Write the global index file to a temporary file.
  764. llvm::SmallString<128> IndexTmpPath;
  765. int TmpFD;
  766. if (llvm::sys::fs::createUniqueFile(IndexPath + "-%%%%%%%%", TmpFD,
  767. IndexTmpPath))
  768. return llvm::createStringError(std::errc::io_error,
  769. "failed creating unique file");
  770. // Open the temporary global index file for output.
  771. llvm::raw_fd_ostream Out(TmpFD, true);
  772. if (Out.has_error())
  773. return llvm::createStringError(Out.error(), "failed outputting to stream");
  774. // Write the index.
  775. Out.write(OutputBuffer.data(), OutputBuffer.size());
  776. Out.close();
  777. if (Out.has_error())
  778. return llvm::createStringError(Out.error(), "failed writing to stream");
  779. // Remove the old index file. It isn't relevant any more.
  780. llvm::sys::fs::remove(IndexPath);
  781. // Rename the newly-written index file to the proper name.
  782. if (std::error_code Err = llvm::sys::fs::rename(IndexTmpPath, IndexPath)) {
  783. // Remove the file on failure, don't check whether removal succeeded.
  784. llvm::sys::fs::remove(IndexTmpPath);
  785. return llvm::createStringError(Err, "failed renaming file \"%s\" to \"%s\"",
  786. IndexTmpPath.c_str(), IndexPath.c_str());
  787. }
  788. return llvm::Error::success();
  789. }
  790. namespace {
  791. class GlobalIndexIdentifierIterator : public IdentifierIterator {
  792. /// The current position within the identifier lookup table.
  793. IdentifierIndexTable::key_iterator Current;
  794. /// The end position within the identifier lookup table.
  795. IdentifierIndexTable::key_iterator End;
  796. public:
  797. explicit GlobalIndexIdentifierIterator(IdentifierIndexTable &Idx) {
  798. Current = Idx.key_begin();
  799. End = Idx.key_end();
  800. }
  801. StringRef Next() override {
  802. if (Current == End)
  803. return StringRef();
  804. StringRef Result = *Current;
  805. ++Current;
  806. return Result;
  807. }
  808. };
  809. }
  810. IdentifierIterator *GlobalModuleIndex::createIdentifierIterator() const {
  811. IdentifierIndexTable &Table =
  812. *static_cast<IdentifierIndexTable *>(IdentifierIndex);
  813. return new GlobalIndexIdentifierIterator(Table);
  814. }