blob: 631683d92f04babd9d8adb053615f4b4d030cdd3 [file] [log] [blame]
Douglas Gregor5e306b12013-01-23 22:38:11 +00001//===--- 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
14#include "ASTReaderInternals.h"
15#include "clang/Basic/FileManager.h"
16#include "clang/Basic/OnDiskHashTable.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000017#include "clang/Lex/HeaderSearch.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000018#include "clang/Serialization/ASTBitCodes.h"
19#include "clang/Serialization/GlobalModuleIndex.h"
Douglas Gregor603cd862013-03-22 18:50:14 +000020#include "clang/Serialization/Module.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000021#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/MapVector.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Bitcode/BitstreamReader.h"
26#include "llvm/Bitcode/BitstreamWriter.h"
Douglas Gregor8ec343c2013-01-23 22:45:24 +000027#include "llvm/Support/FileSystem.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000028#include "llvm/Support/LockFileManager.h"
29#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola552c1692013-06-11 22:15:02 +000030#include "llvm/Support/Path.h"
NAKAMURA Takumif0add232013-01-25 01:47:07 +000031#include <cstdio>
Douglas Gregor5e306b12013-01-23 22:38:11 +000032using namespace clang;
33using namespace serialization;
34
35//----------------------------------------------------------------------------//
36// Shared constants
37//----------------------------------------------------------------------------//
38namespace {
39 enum {
40 /// \brief The block containing the index.
41 GLOBAL_INDEX_BLOCK_ID = llvm::bitc::FIRST_APPLICATION_BLOCKID
42 };
43
44 /// \brief Describes the record types in the index.
45 enum IndexRecordTypes {
46 /// \brief Contains version information and potentially other metadata,
47 /// used to determine if we can read this global index file.
Douglas Gregore060e572013-01-25 01:03:03 +000048 INDEX_METADATA,
Douglas Gregor5e306b12013-01-23 22:38:11 +000049 /// \brief Describes a module, including its file name and dependencies.
50 MODULE,
51 /// \brief The index for identifiers.
52 IDENTIFIER_INDEX
53 };
54}
55
56/// \brief The name of the global index file.
57static const char * const IndexFileName = "modules.idx";
58
59/// \brief The global index file version.
60static const unsigned CurrentVersion = 1;
61
62//----------------------------------------------------------------------------//
Douglas Gregore060e572013-01-25 01:03:03 +000063// Global module index reader.
64//----------------------------------------------------------------------------//
65
66namespace {
67
68/// \brief Trait used to read the identifier index from the on-disk hash
69/// table.
70class IdentifierIndexReaderTrait {
71public:
72 typedef StringRef external_key_type;
73 typedef StringRef internal_key_type;
74 typedef SmallVector<unsigned, 2> data_type;
75
76 static bool EqualKey(const internal_key_type& a, const internal_key_type& b) {
77 return a == b;
78 }
79
80 static unsigned ComputeHash(const internal_key_type& a) {
81 return llvm::HashString(a);
82 }
83
84 static std::pair<unsigned, unsigned>
85 ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +000086 using namespace llvm::support;
87 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
88 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Douglas Gregore060e572013-01-25 01:03:03 +000089 return std::make_pair(KeyLen, DataLen);
90 }
91
92 static const internal_key_type&
93 GetInternalKey(const external_key_type& x) { return x; }
94
95 static const external_key_type&
96 GetExternalKey(const internal_key_type& x) { return x; }
97
98 static internal_key_type ReadKey(const unsigned char* d, unsigned n) {
99 return StringRef((const char *)d, n);
100 }
101
102 static data_type ReadData(const internal_key_type& k,
103 const unsigned char* d,
104 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000105 using namespace llvm::support;
Douglas Gregore060e572013-01-25 01:03:03 +0000106
107 data_type Result;
108 while (DataLen > 0) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000109 unsigned ID = endian::readNext<uint32_t, little, unaligned>(d);
Douglas Gregore060e572013-01-25 01:03:03 +0000110 Result.push_back(ID);
111 DataLen -= 4;
112 }
113
114 return Result;
115 }
116};
117
Justin Bognerda4e6502014-04-14 16:34:29 +0000118typedef OnDiskIterableChainedHashTable<IdentifierIndexReaderTrait>
119 IdentifierIndexTable;
Douglas Gregore060e572013-01-25 01:03:03 +0000120
Douglas Gregore060e572013-01-25 01:03:03 +0000121}
122
Douglas Gregor7029ce12013-03-19 00:28:20 +0000123GlobalModuleIndex::GlobalModuleIndex(llvm::MemoryBuffer *Buffer,
Douglas Gregore060e572013-01-25 01:03:03 +0000124 llvm::BitstreamCursor Cursor)
Douglas Gregor603cd862013-03-22 18:50:14 +0000125 : Buffer(Buffer), IdentifierIndex(),
Douglas Gregor7211ac12013-01-25 23:32:03 +0000126 NumIdentifierLookups(), NumIdentifierLookupHits()
Douglas Gregore060e572013-01-25 01:03:03 +0000127{
Douglas Gregore060e572013-01-25 01:03:03 +0000128 // Read the global index.
Douglas Gregore060e572013-01-25 01:03:03 +0000129 bool InGlobalIndexBlock = false;
130 bool Done = false;
Douglas Gregore060e572013-01-25 01:03:03 +0000131 while (!Done) {
132 llvm::BitstreamEntry Entry = Cursor.advance();
133
134 switch (Entry.Kind) {
135 case llvm::BitstreamEntry::Error:
136 return;
137
138 case llvm::BitstreamEntry::EndBlock:
139 if (InGlobalIndexBlock) {
140 InGlobalIndexBlock = false;
141 Done = true;
142 continue;
143 }
144 return;
145
146
147 case llvm::BitstreamEntry::Record:
148 // Entries in the global index block are handled below.
149 if (InGlobalIndexBlock)
150 break;
151
152 return;
153
154 case llvm::BitstreamEntry::SubBlock:
155 if (!InGlobalIndexBlock && Entry.ID == GLOBAL_INDEX_BLOCK_ID) {
156 if (Cursor.EnterSubBlock(GLOBAL_INDEX_BLOCK_ID))
157 return;
158
159 InGlobalIndexBlock = true;
160 } else if (Cursor.SkipBlock()) {
161 return;
162 }
163 continue;
164 }
165
166 SmallVector<uint64_t, 64> Record;
167 StringRef Blob;
168 switch ((IndexRecordTypes)Cursor.readRecord(Entry.ID, Record, &Blob)) {
169 case INDEX_METADATA:
170 // Make sure that the version matches.
171 if (Record.size() < 1 || Record[0] != CurrentVersion)
172 return;
173 break;
174
175 case MODULE: {
176 unsigned Idx = 0;
177 unsigned ID = Record[Idx++];
Douglas Gregor7029ce12013-03-19 00:28:20 +0000178
179 // Make room for this module's information.
180 if (ID == Modules.size())
181 Modules.push_back(ModuleInfo());
182 else
183 Modules.resize(ID + 1);
184
185 // Size/modification time for this module file at the time the
186 // global index was built.
187 Modules[ID].Size = Record[Idx++];
188 Modules[ID].ModTime = Record[Idx++];
Douglas Gregore060e572013-01-25 01:03:03 +0000189
190 // File name.
191 unsigned NameLen = Record[Idx++];
Douglas Gregor7029ce12013-03-19 00:28:20 +0000192 Modules[ID].FileName.assign(Record.begin() + Idx,
193 Record.begin() + Idx + NameLen);
Douglas Gregore060e572013-01-25 01:03:03 +0000194 Idx += NameLen;
195
196 // Dependencies
197 unsigned NumDeps = Record[Idx++];
Douglas Gregor7029ce12013-03-19 00:28:20 +0000198 Modules[ID].Dependencies.insert(Modules[ID].Dependencies.end(),
199 Record.begin() + Idx,
200 Record.begin() + Idx + NumDeps);
201 Idx += NumDeps;
Douglas Gregore060e572013-01-25 01:03:03 +0000202
Douglas Gregor7029ce12013-03-19 00:28:20 +0000203 // Make sure we're at the end of the record.
204 assert(Idx == Record.size() && "More module info?");
Douglas Gregor603cd862013-03-22 18:50:14 +0000205
206 // Record this module as an unresolved module.
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000207 // FIXME: this doesn't work correctly for module names containing path
208 // separators.
209 StringRef ModuleName = llvm::sys::path::stem(Modules[ID].FileName);
210 // Remove the -<hash of ModuleMapPath>
211 ModuleName = ModuleName.rsplit('-').first;
212 UnresolvedModules[ModuleName] = ID;
Douglas Gregore060e572013-01-25 01:03:03 +0000213 break;
214 }
215
216 case IDENTIFIER_INDEX:
217 // Wire up the identifier index.
218 if (Record[0]) {
219 IdentifierIndex = IdentifierIndexTable::Create(
Justin Bognerda4e6502014-04-14 16:34:29 +0000220 (const unsigned char *)Blob.data() + Record[0],
221 (const unsigned char *)Blob.data() + sizeof(uint32_t),
222 (const unsigned char *)Blob.data(), IdentifierIndexReaderTrait());
Douglas Gregore060e572013-01-25 01:03:03 +0000223 }
224 break;
225 }
226 }
Douglas Gregore060e572013-01-25 01:03:03 +0000227}
228
229GlobalModuleIndex::~GlobalModuleIndex() { }
230
231std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode>
Douglas Gregor7029ce12013-03-19 00:28:20 +0000232GlobalModuleIndex::readIndex(StringRef Path) {
Douglas Gregore060e572013-01-25 01:03:03 +0000233 // Load the index file, if it's there.
234 llvm::SmallString<128> IndexPath;
235 IndexPath += Path;
236 llvm::sys::path::append(IndexPath, IndexFileName);
237
Ahmed Charlesb8984322014-03-07 20:03:18 +0000238 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Rafael Espindola1a3605c2013-10-25 19:00:49 +0000239 if (llvm::MemoryBuffer::getFile(IndexPath.c_str(), Buffer) !=
240 llvm::errc::success)
Douglas Gregore060e572013-01-25 01:03:03 +0000241 return std::make_pair((GlobalModuleIndex *)0, EC_NotFound);
242
243 /// \brief The bitstream reader from which we'll read the AST file.
244 llvm::BitstreamReader Reader((const unsigned char *)Buffer->getBufferStart(),
245 (const unsigned char *)Buffer->getBufferEnd());
246
247 /// \brief The main bitstream cursor for the main block.
248 llvm::BitstreamCursor Cursor(Reader);
249
250 // Sniff for the signature.
251 if (Cursor.Read(8) != 'B' ||
252 Cursor.Read(8) != 'C' ||
253 Cursor.Read(8) != 'G' ||
254 Cursor.Read(8) != 'I') {
255 return std::make_pair((GlobalModuleIndex *)0, EC_IOError);
256 }
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000257
258 return std::make_pair(new GlobalModuleIndex(Buffer.release(), Cursor),
259 EC_None);
Douglas Gregore060e572013-01-25 01:03:03 +0000260}
261
Douglas Gregor7029ce12013-03-19 00:28:20 +0000262void
263GlobalModuleIndex::getKnownModules(SmallVectorImpl<ModuleFile *> &ModuleFiles) {
Douglas Gregore060e572013-01-25 01:03:03 +0000264 ModuleFiles.clear();
265 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
Douglas Gregor603cd862013-03-22 18:50:14 +0000266 if (ModuleFile *MF = Modules[I].File)
267 ModuleFiles.push_back(MF);
Douglas Gregore060e572013-01-25 01:03:03 +0000268 }
269}
270
271void GlobalModuleIndex::getModuleDependencies(
Douglas Gregor7029ce12013-03-19 00:28:20 +0000272 ModuleFile *File,
273 SmallVectorImpl<ModuleFile *> &Dependencies) {
Douglas Gregore060e572013-01-25 01:03:03 +0000274 // Look for information about this module file.
Douglas Gregor7029ce12013-03-19 00:28:20 +0000275 llvm::DenseMap<ModuleFile *, unsigned>::iterator Known
276 = ModulesByFile.find(File);
Douglas Gregore060e572013-01-25 01:03:03 +0000277 if (Known == ModulesByFile.end())
278 return;
279
280 // Record dependencies.
Douglas Gregor7029ce12013-03-19 00:28:20 +0000281 Dependencies.clear();
282 ArrayRef<unsigned> StoredDependencies = Modules[Known->second].Dependencies;
283 for (unsigned I = 0, N = StoredDependencies.size(); I != N; ++I) {
Douglas Gregor603cd862013-03-22 18:50:14 +0000284 if (ModuleFile *MF = Modules[I].File)
Douglas Gregor7029ce12013-03-19 00:28:20 +0000285 Dependencies.push_back(MF);
286 }
Douglas Gregore060e572013-01-25 01:03:03 +0000287}
288
Douglas Gregor7211ac12013-01-25 23:32:03 +0000289bool GlobalModuleIndex::lookupIdentifier(StringRef Name, HitSet &Hits) {
290 Hits.clear();
Douglas Gregore060e572013-01-25 01:03:03 +0000291
292 // If there's no identifier index, there is nothing we can do.
293 if (!IdentifierIndex)
294 return false;
295
296 // Look into the identifier index.
297 ++NumIdentifierLookups;
298 IdentifierIndexTable &Table
299 = *static_cast<IdentifierIndexTable *>(IdentifierIndex);
300 IdentifierIndexTable::iterator Known = Table.find(Name);
301 if (Known == Table.end()) {
302 return true;
303 }
304
305 SmallVector<unsigned, 2> ModuleIDs = *Known;
306 for (unsigned I = 0, N = ModuleIDs.size(); I != N; ++I) {
Douglas Gregor603cd862013-03-22 18:50:14 +0000307 if (ModuleFile *MF = Modules[ModuleIDs[I]].File)
308 Hits.insert(MF);
Douglas Gregore060e572013-01-25 01:03:03 +0000309 }
310
311 ++NumIdentifierLookupHits;
312 return true;
313}
314
Douglas Gregor603cd862013-03-22 18:50:14 +0000315bool GlobalModuleIndex::loadedModuleFile(ModuleFile *File) {
316 // Look for the module in the global module index based on the module name.
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000317 StringRef Name = File->ModuleName;
Douglas Gregor603cd862013-03-22 18:50:14 +0000318 llvm::StringMap<unsigned>::iterator Known = UnresolvedModules.find(Name);
319 if (Known == UnresolvedModules.end()) {
320 return true;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000321 }
322
Douglas Gregor603cd862013-03-22 18:50:14 +0000323 // Rectify this module with the global module index.
324 ModuleInfo &Info = Modules[Known->second];
325
326 // If the size and modification time match what we expected, record this
327 // module file.
328 bool Failed = true;
329 if (File->File->getSize() == Info.Size &&
330 File->File->getModificationTime() == Info.ModTime) {
331 Info.File = File;
332 ModulesByFile[File] = Known->second;
333
334 Failed = false;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000335 }
336
Douglas Gregor603cd862013-03-22 18:50:14 +0000337 // One way or another, we have resolved this module file.
338 UnresolvedModules.erase(Known);
339 return Failed;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000340}
341
Douglas Gregore060e572013-01-25 01:03:03 +0000342void GlobalModuleIndex::printStats() {
343 std::fprintf(stderr, "*** Global Module Index Statistics:\n");
344 if (NumIdentifierLookups) {
345 fprintf(stderr, " %u / %u identifier lookups succeeded (%f%%)\n",
346 NumIdentifierLookupHits, NumIdentifierLookups,
347 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
348 }
Douglas Gregore060e572013-01-25 01:03:03 +0000349 std::fprintf(stderr, "\n");
350}
351
John Thompsonbcdcc922014-04-16 21:03:41 +0000352void GlobalModuleIndex::dump() {
John Thompsona39baf12014-04-17 17:06:13 +0000353 llvm::errs() << "*** Global Module Index Dump:\n";
354 llvm::errs() << "Module files:\n";
John Thompson4f52d442014-04-17 18:17:36 +0000355 for (auto &MI : Modules) {
John Thompsona39baf12014-04-17 17:06:13 +0000356 llvm::errs() << "** " << MI.FileName << "\n";
357 if (MI.File)
358 MI.File->dump();
John Thompsonbcdcc922014-04-16 21:03:41 +0000359 else
John Thompsona39baf12014-04-17 17:06:13 +0000360 llvm::errs() << "\n";
John Thompsonbcdcc922014-04-16 21:03:41 +0000361 }
John Thompsona39baf12014-04-17 17:06:13 +0000362 llvm::errs() << "\n";
John Thompsonbcdcc922014-04-16 21:03:41 +0000363}
364
Douglas Gregore060e572013-01-25 01:03:03 +0000365//----------------------------------------------------------------------------//
Douglas Gregor5e306b12013-01-23 22:38:11 +0000366// Global module index writer.
367//----------------------------------------------------------------------------//
368
369namespace {
370 /// \brief Provides information about a specific module file.
371 struct ModuleFileInfo {
372 /// \brief The numberic ID for this module file.
373 unsigned ID;
374
375 /// \brief The set of modules on which this module depends. Each entry is
376 /// a module ID.
377 SmallVector<unsigned, 4> Dependencies;
378 };
379
380 /// \brief Builder that generates the global module index file.
381 class GlobalModuleIndexBuilder {
382 FileManager &FileMgr;
383
384 /// \brief Mapping from files to module file information.
385 typedef llvm::MapVector<const FileEntry *, ModuleFileInfo> ModuleFilesMap;
386
387 /// \brief Information about each of the known module files.
388 ModuleFilesMap ModuleFiles;
389
390 /// \brief Mapping from identifiers to the list of module file IDs that
391 /// consider this identifier to be interesting.
392 typedef llvm::StringMap<SmallVector<unsigned, 2> > InterestingIdentifierMap;
393
394 /// \brief A mapping from all interesting identifiers to the set of module
395 /// files in which those identifiers are considered interesting.
396 InterestingIdentifierMap InterestingIdentifiers;
397
398 /// \brief Write the block-info block for the global module index file.
399 void emitBlockInfoBlock(llvm::BitstreamWriter &Stream);
400
401 /// \brief Retrieve the module file information for the given file.
402 ModuleFileInfo &getModuleFileInfo(const FileEntry *File) {
403 llvm::MapVector<const FileEntry *, ModuleFileInfo>::iterator Known
404 = ModuleFiles.find(File);
405 if (Known != ModuleFiles.end())
406 return Known->second;
407
408 unsigned NewID = ModuleFiles.size();
409 ModuleFileInfo &Info = ModuleFiles[File];
410 Info.ID = NewID;
411 return Info;
412 }
413
414 public:
415 explicit GlobalModuleIndexBuilder(FileManager &FileMgr) : FileMgr(FileMgr){}
416
417 /// \brief Load the contents of the given module file into the builder.
418 ///
419 /// \returns true if an error occurred, false otherwise.
420 bool loadModuleFile(const FileEntry *File);
421
422 /// \brief Write the index to the given bitstream.
423 void writeIndex(llvm::BitstreamWriter &Stream);
424 };
425}
426
427static void emitBlockID(unsigned ID, const char *Name,
428 llvm::BitstreamWriter &Stream,
429 SmallVectorImpl<uint64_t> &Record) {
430 Record.clear();
431 Record.push_back(ID);
432 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
433
434 // Emit the block name if present.
435 if (Name == 0 || Name[0] == 0) return;
436 Record.clear();
437 while (*Name)
438 Record.push_back(*Name++);
439 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
440}
441
442static void emitRecordID(unsigned ID, const char *Name,
443 llvm::BitstreamWriter &Stream,
444 SmallVectorImpl<uint64_t> &Record) {
445 Record.clear();
446 Record.push_back(ID);
447 while (*Name)
448 Record.push_back(*Name++);
449 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
450}
451
452void
453GlobalModuleIndexBuilder::emitBlockInfoBlock(llvm::BitstreamWriter &Stream) {
454 SmallVector<uint64_t, 64> Record;
455 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
456
457#define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record)
458#define RECORD(X) emitRecordID(X, #X, Stream, Record)
459 BLOCK(GLOBAL_INDEX_BLOCK);
Douglas Gregore060e572013-01-25 01:03:03 +0000460 RECORD(INDEX_METADATA);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000461 RECORD(MODULE);
462 RECORD(IDENTIFIER_INDEX);
463#undef RECORD
464#undef BLOCK
465
466 Stream.ExitBlock();
467}
468
Douglas Gregore060e572013-01-25 01:03:03 +0000469namespace {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000470 class InterestingASTIdentifierLookupTrait
471 : public serialization::reader::ASTIdentifierLookupTraitBase {
472
473 public:
474 /// \brief The identifier and whether it is "interesting".
475 typedef std::pair<StringRef, bool> data_type;
476
477 data_type ReadData(const internal_key_type& k,
478 const unsigned char* d,
479 unsigned DataLen) {
480 // The first bit indicates whether this identifier is interesting.
481 // That's all we care about.
Justin Bogner57ba0b22014-03-28 22:03:24 +0000482 using namespace llvm::support;
483 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000484 bool IsInteresting = RawID & 0x01;
485 return std::make_pair(k, IsInteresting);
486 }
487 };
488}
489
490bool GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
491 // Open the module file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000492 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Douglas Gregorcb680662013-02-06 18:08:37 +0000493 std::string ErrorStr;
494 Buffer.reset(FileMgr.getBufferForFile(File, &ErrorStr, /*isVolatile=*/true));
Douglas Gregor5e306b12013-01-23 22:38:11 +0000495 if (!Buffer) {
496 return true;
497 }
498
499 // Initialize the input stream
500 llvm::BitstreamReader InStreamFile;
501 llvm::BitstreamCursor InStream;
502 InStreamFile.init((const unsigned char *)Buffer->getBufferStart(),
503 (const unsigned char *)Buffer->getBufferEnd());
504 InStream.init(InStreamFile);
505
506 // Sniff for the signature.
507 if (InStream.Read(8) != 'C' ||
508 InStream.Read(8) != 'P' ||
509 InStream.Read(8) != 'C' ||
510 InStream.Read(8) != 'H') {
511 return true;
512 }
513
514 // Record this module file and assign it a unique ID (if it doesn't have
515 // one already).
516 unsigned ID = getModuleFileInfo(File).ID;
517
518 // Search for the blocks and records we care about.
Douglas Gregore060e572013-01-25 01:03:03 +0000519 enum { Other, ControlBlock, ASTBlock } State = Other;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000520 bool Done = false;
521 while (!Done) {
Douglas Gregore060e572013-01-25 01:03:03 +0000522 llvm::BitstreamEntry Entry = InStream.advance();
Douglas Gregor5e306b12013-01-23 22:38:11 +0000523 switch (Entry.Kind) {
524 case llvm::BitstreamEntry::Error:
Douglas Gregore060e572013-01-25 01:03:03 +0000525 Done = true;
526 continue;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000527
528 case llvm::BitstreamEntry::Record:
Douglas Gregore060e572013-01-25 01:03:03 +0000529 // In the 'other' state, just skip the record. We don't care.
530 if (State == Other) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000531 InStream.skipRecord(Entry.ID);
532 continue;
533 }
534
535 // Handle potentially-interesting records below.
536 break;
537
538 case llvm::BitstreamEntry::SubBlock:
Douglas Gregore060e572013-01-25 01:03:03 +0000539 if (Entry.ID == CONTROL_BLOCK_ID) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000540 if (InStream.EnterSubBlock(CONTROL_BLOCK_ID))
541 return true;
542
543 // Found the control block.
544 State = ControlBlock;
545 continue;
546 }
547
Douglas Gregore060e572013-01-25 01:03:03 +0000548 if (Entry.ID == AST_BLOCK_ID) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000549 if (InStream.EnterSubBlock(AST_BLOCK_ID))
550 return true;
551
552 // Found the AST block.
553 State = ASTBlock;
554 continue;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000555 }
556
557 if (InStream.SkipBlock())
558 return true;
559
560 continue;
561
562 case llvm::BitstreamEntry::EndBlock:
Douglas Gregore060e572013-01-25 01:03:03 +0000563 State = Other;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000564 continue;
565 }
566
567 // Read the given record.
568 SmallVector<uint64_t, 64> Record;
569 StringRef Blob;
570 unsigned Code = InStream.readRecord(Entry.ID, Record, &Blob);
571
572 // Handle module dependencies.
573 if (State == ControlBlock && Code == IMPORTS) {
574 // Load each of the imported PCH files.
575 unsigned Idx = 0, N = Record.size();
576 while (Idx < N) {
577 // Read information about the AST file.
578
579 // Skip the imported kind
580 ++Idx;
581
582 // Skip the import location
583 ++Idx;
584
Douglas Gregor7029ce12013-03-19 00:28:20 +0000585 // Load stored size/modification time.
586 off_t StoredSize = (off_t)Record[Idx++];
587 time_t StoredModTime = (time_t)Record[Idx++];
588
Douglas Gregor5e306b12013-01-23 22:38:11 +0000589 // Retrieve the imported file name.
590 unsigned Length = Record[Idx++];
591 SmallString<128> ImportedFile(Record.begin() + Idx,
592 Record.begin() + Idx + Length);
593 Idx += Length;
594
595 // Find the imported module file.
Douglas Gregordadd85d2013-02-08 21:27:45 +0000596 const FileEntry *DependsOnFile
597 = FileMgr.getFile(ImportedFile, /*openFile=*/false,
598 /*cacheFailure=*/false);
Douglas Gregor7029ce12013-03-19 00:28:20 +0000599 if (!DependsOnFile ||
600 (StoredSize != DependsOnFile->getSize()) ||
601 (StoredModTime != DependsOnFile->getModificationTime()))
Douglas Gregor5e306b12013-01-23 22:38:11 +0000602 return true;
603
604 // Record the dependency.
605 unsigned DependsOnID = getModuleFileInfo(DependsOnFile).ID;
606 getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
607 }
608
609 continue;
610 }
611
612 // Handle the identifier table
613 if (State == ASTBlock && Code == IDENTIFIER_TABLE && Record[0] > 0) {
Justin Bognerda4e6502014-04-14 16:34:29 +0000614 typedef
615 OnDiskIterableChainedHashTable<InterestingASTIdentifierLookupTrait>
616 InterestingIdentifierTable;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000617 std::unique_ptr<InterestingIdentifierTable> Table(
618 InterestingIdentifierTable::Create(
619 (const unsigned char *)Blob.data() + Record[0],
Justin Bognerda4e6502014-04-14 16:34:29 +0000620 (const unsigned char *)Blob.data() + sizeof(uint32_t),
Ahmed Charlesb8984322014-03-07 20:03:18 +0000621 (const unsigned char *)Blob.data()));
Douglas Gregor5e306b12013-01-23 22:38:11 +0000622 for (InterestingIdentifierTable::data_iterator D = Table->data_begin(),
623 DEnd = Table->data_end();
624 D != DEnd; ++D) {
625 std::pair<StringRef, bool> Ident = *D;
626 if (Ident.second)
627 InterestingIdentifiers[Ident.first].push_back(ID);
Douglas Gregore060e572013-01-25 01:03:03 +0000628 else
629 (void)InterestingIdentifiers[Ident.first];
Douglas Gregor5e306b12013-01-23 22:38:11 +0000630 }
631 }
632
Douglas Gregor5e306b12013-01-23 22:38:11 +0000633 // We don't care about this record.
634 }
635
636 return false;
637}
638
639namespace {
640
641/// \brief Trait used to generate the identifier index as an on-disk hash
642/// table.
643class IdentifierIndexWriterTrait {
644public:
645 typedef StringRef key_type;
646 typedef StringRef key_type_ref;
647 typedef SmallVector<unsigned, 2> data_type;
648 typedef const SmallVector<unsigned, 2> &data_type_ref;
649
650 static unsigned ComputeHash(key_type_ref Key) {
651 return llvm::HashString(Key);
652 }
653
654 std::pair<unsigned,unsigned>
655 EmitKeyDataLength(raw_ostream& Out, key_type_ref Key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +0000656 using namespace llvm::support;
657 endian::Writer<little> LE(Out);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000658 unsigned KeyLen = Key.size();
659 unsigned DataLen = Data.size() * 4;
Justin Bognere1c147c2014-03-28 22:03:19 +0000660 LE.write<uint16_t>(KeyLen);
661 LE.write<uint16_t>(DataLen);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000662 return std::make_pair(KeyLen, DataLen);
663 }
664
665 void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
666 Out.write(Key.data(), KeyLen);
667 }
668
669 void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
670 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +0000671 using namespace llvm::support;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000672 for (unsigned I = 0, N = Data.size(); I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +0000673 endian::Writer<little>(Out).write<uint32_t>(Data[I]);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000674 }
675};
676
677}
678
679void GlobalModuleIndexBuilder::writeIndex(llvm::BitstreamWriter &Stream) {
680 using namespace llvm;
681
682 // Emit the file header.
683 Stream.Emit((unsigned)'B', 8);
684 Stream.Emit((unsigned)'C', 8);
685 Stream.Emit((unsigned)'G', 8);
686 Stream.Emit((unsigned)'I', 8);
687
688 // Write the block-info block, which describes the records in this bitcode
689 // file.
690 emitBlockInfoBlock(Stream);
691
692 Stream.EnterSubblock(GLOBAL_INDEX_BLOCK_ID, 3);
693
694 // Write the metadata.
695 SmallVector<uint64_t, 2> Record;
696 Record.push_back(CurrentVersion);
Douglas Gregore060e572013-01-25 01:03:03 +0000697 Stream.EmitRecord(INDEX_METADATA, Record);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000698
699 // Write the set of known module files.
700 for (ModuleFilesMap::iterator M = ModuleFiles.begin(),
701 MEnd = ModuleFiles.end();
702 M != MEnd; ++M) {
703 Record.clear();
704 Record.push_back(M->second.ID);
705 Record.push_back(M->first->getSize());
706 Record.push_back(M->first->getModificationTime());
707
708 // File name
709 StringRef Name(M->first->getName());
710 Record.push_back(Name.size());
711 Record.append(Name.begin(), Name.end());
712
713 // Dependencies
714 Record.push_back(M->second.Dependencies.size());
715 Record.append(M->second.Dependencies.begin(), M->second.Dependencies.end());
716 Stream.EmitRecord(MODULE, Record);
717 }
718
719 // Write the identifier -> module file mapping.
720 {
721 OnDiskChainedHashTableGenerator<IdentifierIndexWriterTrait> Generator;
722 IdentifierIndexWriterTrait Trait;
723
724 // Populate the hash table.
725 for (InterestingIdentifierMap::iterator I = InterestingIdentifiers.begin(),
726 IEnd = InterestingIdentifiers.end();
727 I != IEnd; ++I) {
728 Generator.insert(I->first(), I->second, Trait);
729 }
730
731 // Create the on-disk hash table in a buffer.
732 SmallString<4096> IdentifierTable;
733 uint32_t BucketOffset;
734 {
Justin Bognere1c147c2014-03-28 22:03:19 +0000735 using namespace llvm::support;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000736 llvm::raw_svector_ostream Out(IdentifierTable);
737 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +0000738 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000739 BucketOffset = Generator.Emit(Out, Trait);
740 }
741
742 // Create a blob abbreviation
743 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
744 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_INDEX));
745 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
746 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
747 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
748
749 // Write the identifier table
750 Record.clear();
751 Record.push_back(IDENTIFIER_INDEX);
752 Record.push_back(BucketOffset);
753 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
754 }
755
Douglas Gregor5e306b12013-01-23 22:38:11 +0000756 Stream.ExitBlock();
757}
758
759GlobalModuleIndex::ErrorCode
760GlobalModuleIndex::writeIndex(FileManager &FileMgr, StringRef Path) {
761 llvm::SmallString<128> IndexPath;
762 IndexPath += Path;
763 llvm::sys::path::append(IndexPath, IndexFileName);
764
765 // Coordinate building the global index file with other processes that might
766 // try to do the same.
767 llvm::LockFileManager Locked(IndexPath);
768 switch (Locked) {
769 case llvm::LockFileManager::LFS_Error:
770 return EC_IOError;
771
772 case llvm::LockFileManager::LFS_Owned:
773 // We're responsible for building the index ourselves. Do so below.
774 break;
775
776 case llvm::LockFileManager::LFS_Shared:
777 // Someone else is responsible for building the index. We don't care
778 // when they finish, so we're done.
779 return EC_Building;
780 }
781
782 // The module index builder.
783 GlobalModuleIndexBuilder Builder(FileMgr);
784
785 // Load each of the module files.
786 llvm::error_code EC;
787 for (llvm::sys::fs::directory_iterator D(Path, EC), DEnd;
788 D != DEnd && !EC;
789 D.increment(EC)) {
790 // If this isn't a module file, we don't care.
791 if (llvm::sys::path::extension(D->path()) != ".pcm") {
792 // ... unless it's a .pcm.lock file, which indicates that someone is
793 // in the process of rebuilding a module. They'll rebuild the index
794 // at the end of that translation unit, so we don't have to.
795 if (llvm::sys::path::extension(D->path()) == ".pcm.lock")
796 return EC_Building;
797
798 continue;
799 }
800
801 // If we can't find the module file, skip it.
802 const FileEntry *ModuleFile = FileMgr.getFile(D->path());
803 if (!ModuleFile)
804 continue;
805
806 // Load this module file.
807 if (Builder.loadModuleFile(ModuleFile))
808 return EC_IOError;
809 }
810
811 // The output buffer, into which the global index will be written.
812 SmallVector<char, 16> OutputBuffer;
813 {
814 llvm::BitstreamWriter OutputStream(OutputBuffer);
815 Builder.writeIndex(OutputStream);
816 }
817
818 // Write the global index file to a temporary file.
819 llvm::SmallString<128> IndexTmpPath;
820 int TmpFD;
Rafael Espindola18627112013-07-05 21:13:58 +0000821 if (llvm::sys::fs::createUniqueFile(IndexPath + "-%%%%%%%%", TmpFD,
822 IndexTmpPath))
Douglas Gregor5e306b12013-01-23 22:38:11 +0000823 return EC_IOError;
824
825 // Open the temporary global index file for output.
NAKAMURA Takumie00c9862013-01-24 08:20:11 +0000826 llvm::raw_fd_ostream Out(TmpFD, true);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000827 if (Out.has_error())
828 return EC_IOError;
829
830 // Write the index.
831 Out.write(OutputBuffer.data(), OutputBuffer.size());
832 Out.close();
833 if (Out.has_error())
834 return EC_IOError;
835
836 // Remove the old index file. It isn't relevant any more.
Rafael Espindola2a008782014-01-10 21:32:14 +0000837 llvm::sys::fs::remove(IndexPath.str());
Douglas Gregor5e306b12013-01-23 22:38:11 +0000838
839 // Rename the newly-written index file to the proper name.
840 if (llvm::sys::fs::rename(IndexTmpPath.str(), IndexPath.str())) {
841 // Rename failed; just remove the
Rafael Espindola2a008782014-01-10 21:32:14 +0000842 llvm::sys::fs::remove(IndexTmpPath.str());
Douglas Gregor5e306b12013-01-23 22:38:11 +0000843 return EC_IOError;
844 }
845
846 // We're done.
847 return EC_None;
848}
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000849
850namespace {
851 class GlobalIndexIdentifierIterator : public IdentifierIterator {
852 /// \brief The current position within the identifier lookup table.
853 IdentifierIndexTable::key_iterator Current;
854
855 /// \brief The end position within the identifier lookup table.
856 IdentifierIndexTable::key_iterator End;
857
858 public:
859 explicit GlobalIndexIdentifierIterator(IdentifierIndexTable &Idx) {
860 Current = Idx.key_begin();
861 End = Idx.key_end();
862 }
863
Craig Topper3e89dfe2014-03-13 02:13:41 +0000864 StringRef Next() override {
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000865 if (Current == End)
866 return StringRef();
867
868 StringRef Result = *Current;
869 ++Current;
870 return Result;
871 }
872 };
873}
874
875IdentifierIterator *GlobalModuleIndex::createIdentifierIterator() const {
876 IdentifierIndexTable &Table =
877 *static_cast<IdentifierIndexTable *>(IdentifierIndex);
878 return new GlobalIndexIdentifierIterator(Table);
879}