GlobalModuleIndex.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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/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(std::unique_ptr<llvm::MemoryBuffer> Buffer,
  109. llvm::BitstreamCursor Cursor)
  110. : Buffer(std::move(Buffer)), IdentifierIndex(), NumIdentifierLookups(),
  111. NumIdentifierLookupHits() {
  112. auto Fail = [&Buffer](llvm::Error &&Err) {
  113. report_fatal_error("Module index '" + Buffer->getBufferIdentifier() +
  114. "' failed: " + toString(std::move(Err)));
  115. };
  116. llvm::TimeTraceScope TimeScope("Module LoadIndex", StringRef(""));
  117. // Read the global index.
  118. bool InGlobalIndexBlock = false;
  119. bool Done = false;
  120. while (!Done) {
  121. llvm::BitstreamEntry Entry;
  122. if (Expected<llvm::BitstreamEntry> Res = Cursor.advance())
  123. Entry = Res.get();
  124. else
  125. Fail(Res.takeError());
  126. switch (Entry.Kind) {
  127. case llvm::BitstreamEntry::Error:
  128. return;
  129. case llvm::BitstreamEntry::EndBlock:
  130. if (InGlobalIndexBlock) {
  131. InGlobalIndexBlock = false;
  132. Done = true;
  133. continue;
  134. }
  135. return;
  136. case llvm::BitstreamEntry::Record:
  137. // Entries in the global index block are handled below.
  138. if (InGlobalIndexBlock)
  139. break;
  140. return;
  141. case llvm::BitstreamEntry::SubBlock:
  142. if (!InGlobalIndexBlock && Entry.ID == GLOBAL_INDEX_BLOCK_ID) {
  143. if (llvm::Error Err = Cursor.EnterSubBlock(GLOBAL_INDEX_BLOCK_ID))
  144. Fail(std::move(Err));
  145. InGlobalIndexBlock = true;
  146. } else if (llvm::Error Err = Cursor.SkipBlock())
  147. Fail(std::move(Err));
  148. continue;
  149. }
  150. SmallVector<uint64_t, 64> Record;
  151. StringRef Blob;
  152. Expected<unsigned> MaybeIndexRecord =
  153. Cursor.readRecord(Entry.ID, Record, &Blob);
  154. if (!MaybeIndexRecord)
  155. Fail(MaybeIndexRecord.takeError());
  156. IndexRecordTypes IndexRecord =
  157. static_cast<IndexRecordTypes>(MaybeIndexRecord.get());
  158. switch (IndexRecord) {
  159. case INDEX_METADATA:
  160. // Make sure that the version matches.
  161. if (Record.size() < 1 || Record[0] != CurrentVersion)
  162. return;
  163. break;
  164. case MODULE: {
  165. unsigned Idx = 0;
  166. unsigned ID = Record[Idx++];
  167. // Make room for this module's information.
  168. if (ID == Modules.size())
  169. Modules.push_back(ModuleInfo());
  170. else
  171. Modules.resize(ID + 1);
  172. // Size/modification time for this module file at the time the
  173. // global index was built.
  174. Modules[ID].Size = Record[Idx++];
  175. Modules[ID].ModTime = Record[Idx++];
  176. // File name.
  177. unsigned NameLen = Record[Idx++];
  178. Modules[ID].FileName.assign(Record.begin() + Idx,
  179. Record.begin() + Idx + NameLen);
  180. Idx += NameLen;
  181. // Dependencies
  182. unsigned NumDeps = Record[Idx++];
  183. Modules[ID].Dependencies.insert(Modules[ID].Dependencies.end(),
  184. Record.begin() + Idx,
  185. Record.begin() + Idx + NumDeps);
  186. Idx += NumDeps;
  187. // Make sure we're at the end of the record.
  188. assert(Idx == Record.size() && "More module info?");
  189. // Record this module as an unresolved module.
  190. // FIXME: this doesn't work correctly for module names containing path
  191. // separators.
  192. StringRef ModuleName = llvm::sys::path::stem(Modules[ID].FileName);
  193. // Remove the -<hash of ModuleMapPath>
  194. ModuleName = ModuleName.rsplit('-').first;
  195. UnresolvedModules[ModuleName] = ID;
  196. break;
  197. }
  198. case IDENTIFIER_INDEX:
  199. // Wire up the identifier index.
  200. if (Record[0]) {
  201. IdentifierIndex = IdentifierIndexTable::Create(
  202. (const unsigned char *)Blob.data() + Record[0],
  203. (const unsigned char *)Blob.data() + sizeof(uint32_t),
  204. (const unsigned char *)Blob.data(), IdentifierIndexReaderTrait());
  205. }
  206. break;
  207. }
  208. }
  209. }
  210. GlobalModuleIndex::~GlobalModuleIndex() {
  211. delete static_cast<IdentifierIndexTable *>(IdentifierIndex);
  212. }
  213. std::pair<GlobalModuleIndex *, llvm::Error>
  214. GlobalModuleIndex::readIndex(StringRef Path) {
  215. // Load the index file, if it's there.
  216. llvm::SmallString<128> IndexPath;
  217. IndexPath += Path;
  218. llvm::sys::path::append(IndexPath, IndexFileName);
  219. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferOrErr =
  220. llvm::MemoryBuffer::getFile(IndexPath.c_str());
  221. if (!BufferOrErr)
  222. return std::make_pair(nullptr,
  223. llvm::errorCodeToError(BufferOrErr.getError()));
  224. std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(BufferOrErr.get());
  225. /// The main bitstream cursor for the main block.
  226. llvm::BitstreamCursor Cursor(*Buffer);
  227. // Sniff for the signature.
  228. for (unsigned char C : {'B', 'C', 'G', 'I'}) {
  229. if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Cursor.Read(8)) {
  230. if (Res.get() != C)
  231. return std::make_pair(
  232. nullptr, llvm::createStringError(std::errc::illegal_byte_sequence,
  233. "expected signature BCGI"));
  234. } else
  235. return std::make_pair(nullptr, Res.takeError());
  236. }
  237. return std::make_pair(new GlobalModuleIndex(std::move(Buffer), Cursor),
  238. llvm::Error::success());
  239. }
  240. void
  241. GlobalModuleIndex::getKnownModules(SmallVectorImpl<ModuleFile *> &ModuleFiles) {
  242. ModuleFiles.clear();
  243. for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
  244. if (ModuleFile *MF = Modules[I].File)
  245. ModuleFiles.push_back(MF);
  246. }
  247. }
  248. void GlobalModuleIndex::getModuleDependencies(
  249. ModuleFile *File,
  250. SmallVectorImpl<ModuleFile *> &Dependencies) {
  251. // Look for information about this module file.
  252. llvm::DenseMap<ModuleFile *, unsigned>::iterator Known
  253. = ModulesByFile.find(File);
  254. if (Known == ModulesByFile.end())
  255. return;
  256. // Record dependencies.
  257. Dependencies.clear();
  258. ArrayRef<unsigned> StoredDependencies = Modules[Known->second].Dependencies;
  259. for (unsigned I = 0, N = StoredDependencies.size(); I != N; ++I) {
  260. if (ModuleFile *MF = Modules[I].File)
  261. Dependencies.push_back(MF);
  262. }
  263. }
  264. bool GlobalModuleIndex::lookupIdentifier(StringRef Name, HitSet &Hits) {
  265. Hits.clear();
  266. // If there's no identifier index, there is nothing we can do.
  267. if (!IdentifierIndex)
  268. return false;
  269. // Look into the identifier index.
  270. ++NumIdentifierLookups;
  271. IdentifierIndexTable &Table
  272. = *static_cast<IdentifierIndexTable *>(IdentifierIndex);
  273. IdentifierIndexTable::iterator Known = Table.find(Name);
  274. if (Known == Table.end()) {
  275. return true;
  276. }
  277. SmallVector<unsigned, 2> ModuleIDs = *Known;
  278. for (unsigned I = 0, N = ModuleIDs.size(); I != N; ++I) {
  279. if (ModuleFile *MF = Modules[ModuleIDs[I]].File)
  280. Hits.insert(MF);
  281. }
  282. ++NumIdentifierLookupHits;
  283. return true;
  284. }
  285. bool GlobalModuleIndex::loadedModuleFile(ModuleFile *File) {
  286. // Look for the module in the global module index based on the module name.
  287. StringRef Name = File->ModuleName;
  288. llvm::StringMap<unsigned>::iterator Known = UnresolvedModules.find(Name);
  289. if (Known == UnresolvedModules.end()) {
  290. return true;
  291. }
  292. // Rectify this module with the global module index.
  293. ModuleInfo &Info = Modules[Known->second];
  294. // If the size and modification time match what we expected, record this
  295. // module file.
  296. bool Failed = true;
  297. if (File->File->getSize() == Info.Size &&
  298. File->File->getModificationTime() == Info.ModTime) {
  299. Info.File = File;
  300. ModulesByFile[File] = Known->second;
  301. Failed = false;
  302. }
  303. // One way or another, we have resolved this module file.
  304. UnresolvedModules.erase(Known);
  305. return Failed;
  306. }
  307. void GlobalModuleIndex::printStats() {
  308. std::fprintf(stderr, "*** Global Module Index Statistics:\n");
  309. if (NumIdentifierLookups) {
  310. fprintf(stderr, " %u / %u identifier lookups succeeded (%f%%)\n",
  311. NumIdentifierLookupHits, NumIdentifierLookups,
  312. (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
  313. }
  314. std::fprintf(stderr, "\n");
  315. }
  316. LLVM_DUMP_METHOD void GlobalModuleIndex::dump() {
  317. llvm::errs() << "*** Global Module Index Dump:\n";
  318. llvm::errs() << "Module files:\n";
  319. for (auto &MI : Modules) {
  320. llvm::errs() << "** " << MI.FileName << "\n";
  321. if (MI.File)
  322. MI.File->dump();
  323. else
  324. llvm::errs() << "\n";
  325. }
  326. llvm::errs() << "\n";
  327. }
  328. //----------------------------------------------------------------------------//
  329. // Global module index writer.
  330. //----------------------------------------------------------------------------//
  331. namespace {
  332. /// Provides information about a specific module file.
  333. struct ModuleFileInfo {
  334. /// The numberic ID for this module file.
  335. unsigned ID;
  336. /// The set of modules on which this module depends. Each entry is
  337. /// a module ID.
  338. SmallVector<unsigned, 4> Dependencies;
  339. ASTFileSignature Signature;
  340. };
  341. struct ImportedModuleFileInfo {
  342. off_t StoredSize;
  343. time_t StoredModTime;
  344. ASTFileSignature StoredSignature;
  345. ImportedModuleFileInfo(off_t Size, time_t ModTime, ASTFileSignature Sig)
  346. : StoredSize(Size), StoredModTime(ModTime), StoredSignature(Sig) {}
  347. };
  348. /// Builder that generates the global module index file.
  349. class GlobalModuleIndexBuilder {
  350. FileManager &FileMgr;
  351. const PCHContainerReader &PCHContainerRdr;
  352. /// Mapping from files to module file information.
  353. typedef llvm::MapVector<const FileEntry *, ModuleFileInfo> ModuleFilesMap;
  354. /// Information about each of the known module files.
  355. ModuleFilesMap ModuleFiles;
  356. /// Mapping from the imported module file to the imported
  357. /// information.
  358. typedef std::multimap<const FileEntry *, ImportedModuleFileInfo>
  359. ImportedModuleFilesMap;
  360. /// Information about each importing of a module file.
  361. ImportedModuleFilesMap ImportedModuleFiles;
  362. /// Mapping from identifiers to the list of module file IDs that
  363. /// consider this identifier to be interesting.
  364. typedef llvm::StringMap<SmallVector<unsigned, 2> > InterestingIdentifierMap;
  365. /// A mapping from all interesting identifiers to the set of module
  366. /// files in which those identifiers are considered interesting.
  367. InterestingIdentifierMap InterestingIdentifiers;
  368. /// Write the block-info block for the global module index file.
  369. void emitBlockInfoBlock(llvm::BitstreamWriter &Stream);
  370. /// Retrieve the module file information for the given file.
  371. ModuleFileInfo &getModuleFileInfo(const FileEntry *File) {
  372. llvm::MapVector<const FileEntry *, ModuleFileInfo>::iterator Known
  373. = ModuleFiles.find(File);
  374. if (Known != ModuleFiles.end())
  375. return Known->second;
  376. unsigned NewID = ModuleFiles.size();
  377. ModuleFileInfo &Info = ModuleFiles[File];
  378. Info.ID = NewID;
  379. return Info;
  380. }
  381. public:
  382. explicit GlobalModuleIndexBuilder(
  383. FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr)
  384. : FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr) {}
  385. /// Load the contents of the given module file into the builder.
  386. llvm::Error loadModuleFile(const FileEntry *File);
  387. /// Write the index to the given bitstream.
  388. /// \returns true if an error occurred, false otherwise.
  389. bool writeIndex(llvm::BitstreamWriter &Stream);
  390. };
  391. }
  392. static void emitBlockID(unsigned ID, const char *Name,
  393. llvm::BitstreamWriter &Stream,
  394. SmallVectorImpl<uint64_t> &Record) {
  395. Record.clear();
  396. Record.push_back(ID);
  397. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
  398. // Emit the block name if present.
  399. if (!Name || Name[0] == 0) return;
  400. Record.clear();
  401. while (*Name)
  402. Record.push_back(*Name++);
  403. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
  404. }
  405. static void emitRecordID(unsigned ID, const char *Name,
  406. llvm::BitstreamWriter &Stream,
  407. SmallVectorImpl<uint64_t> &Record) {
  408. Record.clear();
  409. Record.push_back(ID);
  410. while (*Name)
  411. Record.push_back(*Name++);
  412. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
  413. }
  414. void
  415. GlobalModuleIndexBuilder::emitBlockInfoBlock(llvm::BitstreamWriter &Stream) {
  416. SmallVector<uint64_t, 64> Record;
  417. Stream.EnterBlockInfoBlock();
  418. #define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record)
  419. #define RECORD(X) emitRecordID(X, #X, Stream, Record)
  420. BLOCK(GLOBAL_INDEX_BLOCK);
  421. RECORD(INDEX_METADATA);
  422. RECORD(MODULE);
  423. RECORD(IDENTIFIER_INDEX);
  424. #undef RECORD
  425. #undef BLOCK
  426. Stream.ExitBlock();
  427. }
  428. namespace {
  429. class InterestingASTIdentifierLookupTrait
  430. : public serialization::reader::ASTIdentifierLookupTraitBase {
  431. public:
  432. /// The identifier and whether it is "interesting".
  433. typedef std::pair<StringRef, bool> data_type;
  434. data_type ReadData(const internal_key_type& k,
  435. const unsigned char* d,
  436. unsigned DataLen) {
  437. // The first bit indicates whether this identifier is interesting.
  438. // That's all we care about.
  439. using namespace llvm::support;
  440. unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
  441. bool IsInteresting = RawID & 0x01;
  442. return std::make_pair(k, IsInteresting);
  443. }
  444. };
  445. }
  446. llvm::Error GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
  447. // Open the module file.
  448. auto Buffer = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
  449. if (!Buffer)
  450. return llvm::createStringError(Buffer.getError(),
  451. "failed getting buffer for module file");
  452. // Initialize the input stream
  453. llvm::BitstreamCursor InStream(PCHContainerRdr.ExtractPCH(**Buffer));
  454. // Sniff for the signature.
  455. for (unsigned char C : {'C', 'P', 'C', 'H'})
  456. if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = InStream.Read(8)) {
  457. if (Res.get() != C)
  458. return llvm::createStringError(std::errc::illegal_byte_sequence,
  459. "expected signature CPCH");
  460. } else
  461. return Res.takeError();
  462. // Record this module file and assign it a unique ID (if it doesn't have
  463. // one already).
  464. unsigned ID = getModuleFileInfo(File).ID;
  465. // Search for the blocks and records we care about.
  466. enum { Other, ControlBlock, ASTBlock, DiagnosticOptionsBlock } State = Other;
  467. bool Done = false;
  468. while (!Done) {
  469. Expected<llvm::BitstreamEntry> MaybeEntry = InStream.advance();
  470. if (!MaybeEntry)
  471. return MaybeEntry.takeError();
  472. llvm::BitstreamEntry Entry = MaybeEntry.get();
  473. switch (Entry.Kind) {
  474. case llvm::BitstreamEntry::Error:
  475. Done = true;
  476. continue;
  477. case llvm::BitstreamEntry::Record:
  478. // In the 'other' state, just skip the record. We don't care.
  479. if (State == Other) {
  480. if (llvm::Expected<unsigned> Skipped = InStream.skipRecord(Entry.ID))
  481. continue;
  482. else
  483. return Skipped.takeError();
  484. }
  485. // Handle potentially-interesting records below.
  486. break;
  487. case llvm::BitstreamEntry::SubBlock:
  488. if (Entry.ID == CONTROL_BLOCK_ID) {
  489. if (llvm::Error Err = InStream.EnterSubBlock(CONTROL_BLOCK_ID))
  490. return Err;
  491. // Found the control block.
  492. State = ControlBlock;
  493. continue;
  494. }
  495. if (Entry.ID == AST_BLOCK_ID) {
  496. if (llvm::Error Err = InStream.EnterSubBlock(AST_BLOCK_ID))
  497. return Err;
  498. // Found the AST block.
  499. State = ASTBlock;
  500. continue;
  501. }
  502. if (Entry.ID == UNHASHED_CONTROL_BLOCK_ID) {
  503. if (llvm::Error Err = InStream.EnterSubBlock(UNHASHED_CONTROL_BLOCK_ID))
  504. return Err;
  505. // Found the Diagnostic Options block.
  506. State = DiagnosticOptionsBlock;
  507. continue;
  508. }
  509. if (llvm::Error Err = InStream.SkipBlock())
  510. return Err;
  511. continue;
  512. case llvm::BitstreamEntry::EndBlock:
  513. State = Other;
  514. continue;
  515. }
  516. // Read the given record.
  517. SmallVector<uint64_t, 64> Record;
  518. StringRef Blob;
  519. Expected<unsigned> MaybeCode = InStream.readRecord(Entry.ID, Record, &Blob);
  520. if (!MaybeCode)
  521. return MaybeCode.takeError();
  522. unsigned Code = MaybeCode.get();
  523. // Handle module dependencies.
  524. if (State == ControlBlock && Code == IMPORTS) {
  525. // Load each of the imported PCH files.
  526. unsigned Idx = 0, N = Record.size();
  527. while (Idx < N) {
  528. // Read information about the AST file.
  529. // Skip the imported kind
  530. ++Idx;
  531. // Skip the import location
  532. ++Idx;
  533. // Load stored size/modification time.
  534. off_t StoredSize = (off_t)Record[Idx++];
  535. time_t StoredModTime = (time_t)Record[Idx++];
  536. // Skip the stored signature.
  537. // FIXME: we could read the signature out of the import and validate it.
  538. ASTFileSignature StoredSignature = {
  539. {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
  540. (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
  541. (uint32_t)Record[Idx++]}}};
  542. // Skip the module name (currently this is only used for prebuilt
  543. // modules while here we are only dealing with cached).
  544. Idx += Record[Idx] + 1;
  545. // Retrieve the imported file name.
  546. unsigned Length = Record[Idx++];
  547. SmallString<128> ImportedFile(Record.begin() + Idx,
  548. Record.begin() + Idx + Length);
  549. Idx += Length;
  550. // Find the imported module file.
  551. auto DependsOnFile
  552. = FileMgr.getFile(ImportedFile, /*OpenFile=*/false,
  553. /*CacheFailure=*/false);
  554. if (!DependsOnFile)
  555. return llvm::createStringError(std::errc::bad_file_descriptor,
  556. "imported file \"%s\" not found",
  557. ImportedFile.c_str());
  558. // Save the information in ImportedModuleFileInfo so we can verify after
  559. // loading all pcms.
  560. ImportedModuleFiles.insert(std::make_pair(
  561. *DependsOnFile, ImportedModuleFileInfo(StoredSize, StoredModTime,
  562. StoredSignature)));
  563. // Record the dependency.
  564. unsigned DependsOnID = getModuleFileInfo(*DependsOnFile).ID;
  565. getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
  566. }
  567. continue;
  568. }
  569. // Handle the identifier table
  570. if (State == ASTBlock && Code == IDENTIFIER_TABLE && Record[0] > 0) {
  571. typedef llvm::OnDiskIterableChainedHashTable<
  572. InterestingASTIdentifierLookupTrait> InterestingIdentifierTable;
  573. std::unique_ptr<InterestingIdentifierTable> Table(
  574. InterestingIdentifierTable::Create(
  575. (const unsigned char *)Blob.data() + Record[0],
  576. (const unsigned char *)Blob.data() + sizeof(uint32_t),
  577. (const unsigned char *)Blob.data()));
  578. for (InterestingIdentifierTable::data_iterator D = Table->data_begin(),
  579. DEnd = Table->data_end();
  580. D != DEnd; ++D) {
  581. std::pair<StringRef, bool> Ident = *D;
  582. if (Ident.second)
  583. InterestingIdentifiers[Ident.first].push_back(ID);
  584. else
  585. (void)InterestingIdentifiers[Ident.first];
  586. }
  587. }
  588. // Get Signature.
  589. if (State == DiagnosticOptionsBlock && Code == SIGNATURE)
  590. getModuleFileInfo(File).Signature = {
  591. {{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
  592. (uint32_t)Record[3], (uint32_t)Record[4]}}};
  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", StringRef(""));
  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. SmallVector<char, 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(
  766. (IndexPath + "-%%%%%%%%").str(), IndexPath,
  767. llvm::StringRef(OutputBuffer.data(), OutputBuffer.size()));
  768. }
  769. namespace {
  770. class GlobalIndexIdentifierIterator : public IdentifierIterator {
  771. /// The current position within the identifier lookup table.
  772. IdentifierIndexTable::key_iterator Current;
  773. /// The end position within the identifier lookup table.
  774. IdentifierIndexTable::key_iterator End;
  775. public:
  776. explicit GlobalIndexIdentifierIterator(IdentifierIndexTable &Idx) {
  777. Current = Idx.key_begin();
  778. End = Idx.key_end();
  779. }
  780. StringRef Next() override {
  781. if (Current == End)
  782. return StringRef();
  783. StringRef Result = *Current;
  784. ++Current;
  785. return Result;
  786. }
  787. };
  788. }
  789. IdentifierIterator *GlobalModuleIndex::createIdentifierIterator() const {
  790. IdentifierIndexTable &Table =
  791. *static_cast<IdentifierIndexTable *>(IdentifierIndex);
  792. return new GlobalIndexIdentifierIterator(Table);
  793. }