GlobalModuleIndex.cpp 29 KB

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