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 clang::io;
  75. unsigned KeyLen = ReadUnalignedLE16(d);
  76. unsigned DataLen = ReadUnalignedLE16(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 clang::io;
  90. data_type Result;
  91. while (DataLen > 0) {
  92. unsigned ID = ReadUnalignedLE32(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. llvm::OwningPtr<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.take(), Cursor), EC_None);
  209. }
  210. void
  211. GlobalModuleIndex::getKnownModules(SmallVectorImpl<ModuleFile *> &ModuleFiles) {
  212. ModuleFiles.clear();
  213. for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
  214. if (ModuleFile *MF = Modules[I].File)
  215. ModuleFiles.push_back(MF);
  216. }
  217. }
  218. void GlobalModuleIndex::getModuleDependencies(
  219. ModuleFile *File,
  220. SmallVectorImpl<ModuleFile *> &Dependencies) {
  221. // Look for information about this module file.
  222. llvm::DenseMap<ModuleFile *, unsigned>::iterator Known
  223. = ModulesByFile.find(File);
  224. if (Known == ModulesByFile.end())
  225. return;
  226. // Record dependencies.
  227. Dependencies.clear();
  228. ArrayRef<unsigned> StoredDependencies = Modules[Known->second].Dependencies;
  229. for (unsigned I = 0, N = StoredDependencies.size(); I != N; ++I) {
  230. if (ModuleFile *MF = Modules[I].File)
  231. Dependencies.push_back(MF);
  232. }
  233. }
  234. bool GlobalModuleIndex::lookupIdentifier(StringRef Name, HitSet &Hits) {
  235. Hits.clear();
  236. // If there's no identifier index, there is nothing we can do.
  237. if (!IdentifierIndex)
  238. return false;
  239. // Look into the identifier index.
  240. ++NumIdentifierLookups;
  241. IdentifierIndexTable &Table
  242. = *static_cast<IdentifierIndexTable *>(IdentifierIndex);
  243. IdentifierIndexTable::iterator Known = Table.find(Name);
  244. if (Known == Table.end()) {
  245. return true;
  246. }
  247. SmallVector<unsigned, 2> ModuleIDs = *Known;
  248. for (unsigned I = 0, N = ModuleIDs.size(); I != N; ++I) {
  249. if (ModuleFile *MF = Modules[ModuleIDs[I]].File)
  250. Hits.insert(MF);
  251. }
  252. ++NumIdentifierLookupHits;
  253. return true;
  254. }
  255. bool GlobalModuleIndex::loadedModuleFile(ModuleFile *File) {
  256. // Look for the module in the global module index based on the module name.
  257. StringRef Name = llvm::sys::path::stem(File->FileName);
  258. llvm::StringMap<unsigned>::iterator Known = UnresolvedModules.find(Name);
  259. if (Known == UnresolvedModules.end()) {
  260. return true;
  261. }
  262. // Rectify this module with the global module index.
  263. ModuleInfo &Info = Modules[Known->second];
  264. // If the size and modification time match what we expected, record this
  265. // module file.
  266. bool Failed = true;
  267. if (File->File->getSize() == Info.Size &&
  268. File->File->getModificationTime() == Info.ModTime) {
  269. Info.File = File;
  270. ModulesByFile[File] = Known->second;
  271. Failed = false;
  272. }
  273. // One way or another, we have resolved this module file.
  274. UnresolvedModules.erase(Known);
  275. return Failed;
  276. }
  277. void GlobalModuleIndex::printStats() {
  278. std::fprintf(stderr, "*** Global Module Index Statistics:\n");
  279. if (NumIdentifierLookups) {
  280. fprintf(stderr, " %u / %u identifier lookups succeeded (%f%%)\n",
  281. NumIdentifierLookupHits, NumIdentifierLookups,
  282. (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
  283. }
  284. std::fprintf(stderr, "\n");
  285. }
  286. //----------------------------------------------------------------------------//
  287. // Global module index writer.
  288. //----------------------------------------------------------------------------//
  289. namespace {
  290. /// \brief Provides information about a specific module file.
  291. struct ModuleFileInfo {
  292. /// \brief The numberic ID for this module file.
  293. unsigned ID;
  294. /// \brief The set of modules on which this module depends. Each entry is
  295. /// a module ID.
  296. SmallVector<unsigned, 4> Dependencies;
  297. };
  298. /// \brief Builder that generates the global module index file.
  299. class GlobalModuleIndexBuilder {
  300. FileManager &FileMgr;
  301. /// \brief Mapping from files to module file information.
  302. typedef llvm::MapVector<const FileEntry *, ModuleFileInfo> ModuleFilesMap;
  303. /// \brief Information about each of the known module files.
  304. ModuleFilesMap ModuleFiles;
  305. /// \brief Mapping from identifiers to the list of module file IDs that
  306. /// consider this identifier to be interesting.
  307. typedef llvm::StringMap<SmallVector<unsigned, 2> > InterestingIdentifierMap;
  308. /// \brief A mapping from all interesting identifiers to the set of module
  309. /// files in which those identifiers are considered interesting.
  310. InterestingIdentifierMap InterestingIdentifiers;
  311. /// \brief Write the block-info block for the global module index file.
  312. void emitBlockInfoBlock(llvm::BitstreamWriter &Stream);
  313. /// \brief Retrieve the module file information for the given file.
  314. ModuleFileInfo &getModuleFileInfo(const FileEntry *File) {
  315. llvm::MapVector<const FileEntry *, ModuleFileInfo>::iterator Known
  316. = ModuleFiles.find(File);
  317. if (Known != ModuleFiles.end())
  318. return Known->second;
  319. unsigned NewID = ModuleFiles.size();
  320. ModuleFileInfo &Info = ModuleFiles[File];
  321. Info.ID = NewID;
  322. return Info;
  323. }
  324. public:
  325. explicit GlobalModuleIndexBuilder(FileManager &FileMgr) : FileMgr(FileMgr){}
  326. /// \brief Load the contents of the given module file into the builder.
  327. ///
  328. /// \returns true if an error occurred, false otherwise.
  329. bool loadModuleFile(const FileEntry *File);
  330. /// \brief Write the index to the given bitstream.
  331. void writeIndex(llvm::BitstreamWriter &Stream);
  332. };
  333. }
  334. static void emitBlockID(unsigned ID, const char *Name,
  335. llvm::BitstreamWriter &Stream,
  336. SmallVectorImpl<uint64_t> &Record) {
  337. Record.clear();
  338. Record.push_back(ID);
  339. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
  340. // Emit the block name if present.
  341. if (Name == 0 || Name[0] == 0) return;
  342. Record.clear();
  343. while (*Name)
  344. Record.push_back(*Name++);
  345. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
  346. }
  347. static void emitRecordID(unsigned ID, const char *Name,
  348. llvm::BitstreamWriter &Stream,
  349. SmallVectorImpl<uint64_t> &Record) {
  350. Record.clear();
  351. Record.push_back(ID);
  352. while (*Name)
  353. Record.push_back(*Name++);
  354. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
  355. }
  356. void
  357. GlobalModuleIndexBuilder::emitBlockInfoBlock(llvm::BitstreamWriter &Stream) {
  358. SmallVector<uint64_t, 64> Record;
  359. Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
  360. #define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record)
  361. #define RECORD(X) emitRecordID(X, #X, Stream, Record)
  362. BLOCK(GLOBAL_INDEX_BLOCK);
  363. RECORD(INDEX_METADATA);
  364. RECORD(MODULE);
  365. RECORD(IDENTIFIER_INDEX);
  366. #undef RECORD
  367. #undef BLOCK
  368. Stream.ExitBlock();
  369. }
  370. namespace {
  371. class InterestingASTIdentifierLookupTrait
  372. : public serialization::reader::ASTIdentifierLookupTraitBase {
  373. public:
  374. /// \brief The identifier and whether it is "interesting".
  375. typedef std::pair<StringRef, bool> data_type;
  376. data_type ReadData(const internal_key_type& k,
  377. const unsigned char* d,
  378. unsigned DataLen) {
  379. // The first bit indicates whether this identifier is interesting.
  380. // That's all we care about.
  381. using namespace clang::io;
  382. unsigned RawID = ReadUnalignedLE32(d);
  383. bool IsInteresting = RawID & 0x01;
  384. return std::make_pair(k, IsInteresting);
  385. }
  386. };
  387. }
  388. bool GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
  389. // Open the module file.
  390. OwningPtr<llvm::MemoryBuffer> Buffer;
  391. std::string ErrorStr;
  392. Buffer.reset(FileMgr.getBufferForFile(File, &ErrorStr, /*isVolatile=*/true));
  393. if (!Buffer) {
  394. return true;
  395. }
  396. // Initialize the input stream
  397. llvm::BitstreamReader InStreamFile;
  398. llvm::BitstreamCursor InStream;
  399. InStreamFile.init((const unsigned char *)Buffer->getBufferStart(),
  400. (const unsigned char *)Buffer->getBufferEnd());
  401. InStream.init(InStreamFile);
  402. // Sniff for the signature.
  403. if (InStream.Read(8) != 'C' ||
  404. InStream.Read(8) != 'P' ||
  405. InStream.Read(8) != 'C' ||
  406. InStream.Read(8) != 'H') {
  407. return true;
  408. }
  409. // Record this module file and assign it a unique ID (if it doesn't have
  410. // one already).
  411. unsigned ID = getModuleFileInfo(File).ID;
  412. // Search for the blocks and records we care about.
  413. enum { Other, ControlBlock, ASTBlock } State = Other;
  414. bool Done = false;
  415. while (!Done) {
  416. llvm::BitstreamEntry Entry = InStream.advance();
  417. switch (Entry.Kind) {
  418. case llvm::BitstreamEntry::Error:
  419. Done = true;
  420. continue;
  421. case llvm::BitstreamEntry::Record:
  422. // In the 'other' state, just skip the record. We don't care.
  423. if (State == Other) {
  424. InStream.skipRecord(Entry.ID);
  425. continue;
  426. }
  427. // Handle potentially-interesting records below.
  428. break;
  429. case llvm::BitstreamEntry::SubBlock:
  430. if (Entry.ID == CONTROL_BLOCK_ID) {
  431. if (InStream.EnterSubBlock(CONTROL_BLOCK_ID))
  432. return true;
  433. // Found the control block.
  434. State = ControlBlock;
  435. continue;
  436. }
  437. if (Entry.ID == AST_BLOCK_ID) {
  438. if (InStream.EnterSubBlock(AST_BLOCK_ID))
  439. return true;
  440. // Found the AST block.
  441. State = ASTBlock;
  442. continue;
  443. }
  444. if (InStream.SkipBlock())
  445. return true;
  446. continue;
  447. case llvm::BitstreamEntry::EndBlock:
  448. State = Other;
  449. continue;
  450. }
  451. // Read the given record.
  452. SmallVector<uint64_t, 64> Record;
  453. StringRef Blob;
  454. unsigned Code = InStream.readRecord(Entry.ID, Record, &Blob);
  455. // Handle module dependencies.
  456. if (State == ControlBlock && Code == IMPORTS) {
  457. // Load each of the imported PCH files.
  458. unsigned Idx = 0, N = Record.size();
  459. while (Idx < N) {
  460. // Read information about the AST file.
  461. // Skip the imported kind
  462. ++Idx;
  463. // Skip the import location
  464. ++Idx;
  465. // Load stored size/modification time.
  466. off_t StoredSize = (off_t)Record[Idx++];
  467. time_t StoredModTime = (time_t)Record[Idx++];
  468. // Retrieve the imported file name.
  469. unsigned Length = Record[Idx++];
  470. SmallString<128> ImportedFile(Record.begin() + Idx,
  471. Record.begin() + Idx + Length);
  472. Idx += Length;
  473. // Find the imported module file.
  474. const FileEntry *DependsOnFile
  475. = FileMgr.getFile(ImportedFile, /*openFile=*/false,
  476. /*cacheFailure=*/false);
  477. if (!DependsOnFile ||
  478. (StoredSize != DependsOnFile->getSize()) ||
  479. (StoredModTime != DependsOnFile->getModificationTime()))
  480. return true;
  481. // Record the dependency.
  482. unsigned DependsOnID = getModuleFileInfo(DependsOnFile).ID;
  483. getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
  484. }
  485. continue;
  486. }
  487. // Handle the identifier table
  488. if (State == ASTBlock && Code == IDENTIFIER_TABLE && Record[0] > 0) {
  489. typedef OnDiskChainedHashTable<InterestingASTIdentifierLookupTrait>
  490. InterestingIdentifierTable;
  491. llvm::OwningPtr<InterestingIdentifierTable>
  492. Table(InterestingIdentifierTable::Create(
  493. (const unsigned char *)Blob.data() + Record[0],
  494. (const unsigned char *)Blob.data()));
  495. for (InterestingIdentifierTable::data_iterator D = Table->data_begin(),
  496. DEnd = Table->data_end();
  497. D != DEnd; ++D) {
  498. std::pair<StringRef, bool> Ident = *D;
  499. if (Ident.second)
  500. InterestingIdentifiers[Ident.first].push_back(ID);
  501. else
  502. (void)InterestingIdentifiers[Ident.first];
  503. }
  504. }
  505. // We don't care about this record.
  506. }
  507. return false;
  508. }
  509. namespace {
  510. /// \brief Trait used to generate the identifier index as an on-disk hash
  511. /// table.
  512. class IdentifierIndexWriterTrait {
  513. public:
  514. typedef StringRef key_type;
  515. typedef StringRef key_type_ref;
  516. typedef SmallVector<unsigned, 2> data_type;
  517. typedef const SmallVector<unsigned, 2> &data_type_ref;
  518. static unsigned ComputeHash(key_type_ref Key) {
  519. return llvm::HashString(Key);
  520. }
  521. std::pair<unsigned,unsigned>
  522. EmitKeyDataLength(raw_ostream& Out, key_type_ref Key, data_type_ref Data) {
  523. unsigned KeyLen = Key.size();
  524. unsigned DataLen = Data.size() * 4;
  525. clang::io::Emit16(Out, KeyLen);
  526. clang::io::Emit16(Out, DataLen);
  527. return std::make_pair(KeyLen, DataLen);
  528. }
  529. void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
  530. Out.write(Key.data(), KeyLen);
  531. }
  532. void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
  533. unsigned DataLen) {
  534. for (unsigned I = 0, N = Data.size(); I != N; ++I)
  535. clang::io::Emit32(Out, Data[I]);
  536. }
  537. };
  538. }
  539. void GlobalModuleIndexBuilder::writeIndex(llvm::BitstreamWriter &Stream) {
  540. using namespace llvm;
  541. // Emit the file header.
  542. Stream.Emit((unsigned)'B', 8);
  543. Stream.Emit((unsigned)'C', 8);
  544. Stream.Emit((unsigned)'G', 8);
  545. Stream.Emit((unsigned)'I', 8);
  546. // Write the block-info block, which describes the records in this bitcode
  547. // file.
  548. emitBlockInfoBlock(Stream);
  549. Stream.EnterSubblock(GLOBAL_INDEX_BLOCK_ID, 3);
  550. // Write the metadata.
  551. SmallVector<uint64_t, 2> Record;
  552. Record.push_back(CurrentVersion);
  553. Stream.EmitRecord(INDEX_METADATA, Record);
  554. // Write the set of known module files.
  555. for (ModuleFilesMap::iterator M = ModuleFiles.begin(),
  556. MEnd = ModuleFiles.end();
  557. M != MEnd; ++M) {
  558. Record.clear();
  559. Record.push_back(M->second.ID);
  560. Record.push_back(M->first->getSize());
  561. Record.push_back(M->first->getModificationTime());
  562. // File name
  563. StringRef Name(M->first->getName());
  564. Record.push_back(Name.size());
  565. Record.append(Name.begin(), Name.end());
  566. // Dependencies
  567. Record.push_back(M->second.Dependencies.size());
  568. Record.append(M->second.Dependencies.begin(), M->second.Dependencies.end());
  569. Stream.EmitRecord(MODULE, Record);
  570. }
  571. // Write the identifier -> module file mapping.
  572. {
  573. OnDiskChainedHashTableGenerator<IdentifierIndexWriterTrait> Generator;
  574. IdentifierIndexWriterTrait Trait;
  575. // Populate the hash table.
  576. for (InterestingIdentifierMap::iterator I = InterestingIdentifiers.begin(),
  577. IEnd = InterestingIdentifiers.end();
  578. I != IEnd; ++I) {
  579. Generator.insert(I->first(), I->second, Trait);
  580. }
  581. // Create the on-disk hash table in a buffer.
  582. SmallString<4096> IdentifierTable;
  583. uint32_t BucketOffset;
  584. {
  585. llvm::raw_svector_ostream Out(IdentifierTable);
  586. // Make sure that no bucket is at offset 0
  587. clang::io::Emit32(Out, 0);
  588. BucketOffset = Generator.Emit(Out, Trait);
  589. }
  590. // Create a blob abbreviation
  591. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  592. Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_INDEX));
  593. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  594. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  595. unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
  596. // Write the identifier table
  597. Record.clear();
  598. Record.push_back(IDENTIFIER_INDEX);
  599. Record.push_back(BucketOffset);
  600. Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
  601. }
  602. Stream.ExitBlock();
  603. }
  604. GlobalModuleIndex::ErrorCode
  605. GlobalModuleIndex::writeIndex(FileManager &FileMgr, StringRef Path) {
  606. llvm::SmallString<128> IndexPath;
  607. IndexPath += Path;
  608. llvm::sys::path::append(IndexPath, IndexFileName);
  609. // Coordinate building the global index file with other processes that might
  610. // try to do the same.
  611. llvm::LockFileManager Locked(IndexPath);
  612. switch (Locked) {
  613. case llvm::LockFileManager::LFS_Error:
  614. return EC_IOError;
  615. case llvm::LockFileManager::LFS_Owned:
  616. // We're responsible for building the index ourselves. Do so below.
  617. break;
  618. case llvm::LockFileManager::LFS_Shared:
  619. // Someone else is responsible for building the index. We don't care
  620. // when they finish, so we're done.
  621. return EC_Building;
  622. }
  623. // The module index builder.
  624. GlobalModuleIndexBuilder Builder(FileMgr);
  625. // Load each of the module files.
  626. llvm::error_code EC;
  627. for (llvm::sys::fs::directory_iterator D(Path, EC), DEnd;
  628. D != DEnd && !EC;
  629. D.increment(EC)) {
  630. // If this isn't a module file, we don't care.
  631. if (llvm::sys::path::extension(D->path()) != ".pcm") {
  632. // ... unless it's a .pcm.lock file, which indicates that someone is
  633. // in the process of rebuilding a module. They'll rebuild the index
  634. // at the end of that translation unit, so we don't have to.
  635. if (llvm::sys::path::extension(D->path()) == ".pcm.lock")
  636. return EC_Building;
  637. continue;
  638. }
  639. // If we can't find the module file, skip it.
  640. const FileEntry *ModuleFile = FileMgr.getFile(D->path());
  641. if (!ModuleFile)
  642. continue;
  643. // Load this module file.
  644. if (Builder.loadModuleFile(ModuleFile))
  645. return EC_IOError;
  646. }
  647. // The output buffer, into which the global index will be written.
  648. SmallVector<char, 16> OutputBuffer;
  649. {
  650. llvm::BitstreamWriter OutputStream(OutputBuffer);
  651. Builder.writeIndex(OutputStream);
  652. }
  653. // Write the global index file to a temporary file.
  654. llvm::SmallString<128> IndexTmpPath;
  655. int TmpFD;
  656. if (llvm::sys::fs::createUniqueFile(IndexPath + "-%%%%%%%%", TmpFD,
  657. IndexTmpPath))
  658. return EC_IOError;
  659. // Open the temporary global index file for output.
  660. llvm::raw_fd_ostream Out(TmpFD, true);
  661. if (Out.has_error())
  662. return EC_IOError;
  663. // Write the index.
  664. Out.write(OutputBuffer.data(), OutputBuffer.size());
  665. Out.close();
  666. if (Out.has_error())
  667. return EC_IOError;
  668. // Remove the old index file. It isn't relevant any more.
  669. bool OldIndexExisted;
  670. llvm::sys::fs::remove(IndexPath.str(), OldIndexExisted);
  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(), OldIndexExisted);
  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. virtual StringRef Next() {
  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. }