GlobalModuleIndex.cpp 31 KB

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