GlobalModuleIndex.cpp 26 KB

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