blob: 3bc7b8fc7292378866bab0b6db312c80c30a67df [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() {
353 std::fprintf(stderr, "*** Global Module Index Dump:\n");
354 std::fprintf(stderr, "Module files:\n");
355 for (llvm::SmallVector<ModuleInfo, 16>::iterator I = Modules.begin(),
356 E = Modules.end(); I != E; ++I) {
357 ModuleInfo *MI = (ModuleInfo*)I;
358 std::fprintf(stderr, "** %s\n", MI->FileName.c_str());
359 if (MI->File)
360 MI->File->dump();
361 else
362 std::fprintf(stderr, "\n");
363 }
364 std::fprintf(stderr, "\n");
365}
366
Douglas Gregore060e572013-01-25 01:03:03 +0000367//----------------------------------------------------------------------------//
Douglas Gregor5e306b12013-01-23 22:38:11 +0000368// Global module index writer.
369//----------------------------------------------------------------------------//
370
371namespace {
372 /// \brief Provides information about a specific module file.
373 struct ModuleFileInfo {
374 /// \brief The numberic ID for this module file.
375 unsigned ID;
376
377 /// \brief The set of modules on which this module depends. Each entry is
378 /// a module ID.
379 SmallVector<unsigned, 4> Dependencies;
380 };
381
382 /// \brief Builder that generates the global module index file.
383 class GlobalModuleIndexBuilder {
384 FileManager &FileMgr;
385
386 /// \brief Mapping from files to module file information.
387 typedef llvm::MapVector<const FileEntry *, ModuleFileInfo> ModuleFilesMap;
388
389 /// \brief Information about each of the known module files.
390 ModuleFilesMap ModuleFiles;
391
392 /// \brief Mapping from identifiers to the list of module file IDs that
393 /// consider this identifier to be interesting.
394 typedef llvm::StringMap<SmallVector<unsigned, 2> > InterestingIdentifierMap;
395
396 /// \brief A mapping from all interesting identifiers to the set of module
397 /// files in which those identifiers are considered interesting.
398 InterestingIdentifierMap InterestingIdentifiers;
399
400 /// \brief Write the block-info block for the global module index file.
401 void emitBlockInfoBlock(llvm::BitstreamWriter &Stream);
402
403 /// \brief Retrieve the module file information for the given file.
404 ModuleFileInfo &getModuleFileInfo(const FileEntry *File) {
405 llvm::MapVector<const FileEntry *, ModuleFileInfo>::iterator Known
406 = ModuleFiles.find(File);
407 if (Known != ModuleFiles.end())
408 return Known->second;
409
410 unsigned NewID = ModuleFiles.size();
411 ModuleFileInfo &Info = ModuleFiles[File];
412 Info.ID = NewID;
413 return Info;
414 }
415
416 public:
417 explicit GlobalModuleIndexBuilder(FileManager &FileMgr) : FileMgr(FileMgr){}
418
419 /// \brief Load the contents of the given module file into the builder.
420 ///
421 /// \returns true if an error occurred, false otherwise.
422 bool loadModuleFile(const FileEntry *File);
423
424 /// \brief Write the index to the given bitstream.
425 void writeIndex(llvm::BitstreamWriter &Stream);
426 };
427}
428
429static void emitBlockID(unsigned ID, const char *Name,
430 llvm::BitstreamWriter &Stream,
431 SmallVectorImpl<uint64_t> &Record) {
432 Record.clear();
433 Record.push_back(ID);
434 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
435
436 // Emit the block name if present.
437 if (Name == 0 || Name[0] == 0) return;
438 Record.clear();
439 while (*Name)
440 Record.push_back(*Name++);
441 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
442}
443
444static void emitRecordID(unsigned ID, const char *Name,
445 llvm::BitstreamWriter &Stream,
446 SmallVectorImpl<uint64_t> &Record) {
447 Record.clear();
448 Record.push_back(ID);
449 while (*Name)
450 Record.push_back(*Name++);
451 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
452}
453
454void
455GlobalModuleIndexBuilder::emitBlockInfoBlock(llvm::BitstreamWriter &Stream) {
456 SmallVector<uint64_t, 64> Record;
457 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
458
459#define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record)
460#define RECORD(X) emitRecordID(X, #X, Stream, Record)
461 BLOCK(GLOBAL_INDEX_BLOCK);
Douglas Gregore060e572013-01-25 01:03:03 +0000462 RECORD(INDEX_METADATA);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000463 RECORD(MODULE);
464 RECORD(IDENTIFIER_INDEX);
465#undef RECORD
466#undef BLOCK
467
468 Stream.ExitBlock();
469}
470
Douglas Gregore060e572013-01-25 01:03:03 +0000471namespace {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000472 class InterestingASTIdentifierLookupTrait
473 : public serialization::reader::ASTIdentifierLookupTraitBase {
474
475 public:
476 /// \brief The identifier and whether it is "interesting".
477 typedef std::pair<StringRef, bool> data_type;
478
479 data_type ReadData(const internal_key_type& k,
480 const unsigned char* d,
481 unsigned DataLen) {
482 // The first bit indicates whether this identifier is interesting.
483 // That's all we care about.
Justin Bogner57ba0b22014-03-28 22:03:24 +0000484 using namespace llvm::support;
485 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000486 bool IsInteresting = RawID & 0x01;
487 return std::make_pair(k, IsInteresting);
488 }
489 };
490}
491
492bool GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
493 // Open the module file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000494 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Douglas Gregorcb680662013-02-06 18:08:37 +0000495 std::string ErrorStr;
496 Buffer.reset(FileMgr.getBufferForFile(File, &ErrorStr, /*isVolatile=*/true));
Douglas Gregor5e306b12013-01-23 22:38:11 +0000497 if (!Buffer) {
498 return true;
499 }
500
501 // Initialize the input stream
502 llvm::BitstreamReader InStreamFile;
503 llvm::BitstreamCursor InStream;
504 InStreamFile.init((const unsigned char *)Buffer->getBufferStart(),
505 (const unsigned char *)Buffer->getBufferEnd());
506 InStream.init(InStreamFile);
507
508 // Sniff for the signature.
509 if (InStream.Read(8) != 'C' ||
510 InStream.Read(8) != 'P' ||
511 InStream.Read(8) != 'C' ||
512 InStream.Read(8) != 'H') {
513 return true;
514 }
515
516 // Record this module file and assign it a unique ID (if it doesn't have
517 // one already).
518 unsigned ID = getModuleFileInfo(File).ID;
519
520 // Search for the blocks and records we care about.
Douglas Gregore060e572013-01-25 01:03:03 +0000521 enum { Other, ControlBlock, ASTBlock } State = Other;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000522 bool Done = false;
523 while (!Done) {
Douglas Gregore060e572013-01-25 01:03:03 +0000524 llvm::BitstreamEntry Entry = InStream.advance();
Douglas Gregor5e306b12013-01-23 22:38:11 +0000525 switch (Entry.Kind) {
526 case llvm::BitstreamEntry::Error:
Douglas Gregore060e572013-01-25 01:03:03 +0000527 Done = true;
528 continue;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000529
530 case llvm::BitstreamEntry::Record:
Douglas Gregore060e572013-01-25 01:03:03 +0000531 // In the 'other' state, just skip the record. We don't care.
532 if (State == Other) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000533 InStream.skipRecord(Entry.ID);
534 continue;
535 }
536
537 // Handle potentially-interesting records below.
538 break;
539
540 case llvm::BitstreamEntry::SubBlock:
Douglas Gregore060e572013-01-25 01:03:03 +0000541 if (Entry.ID == CONTROL_BLOCK_ID) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000542 if (InStream.EnterSubBlock(CONTROL_BLOCK_ID))
543 return true;
544
545 // Found the control block.
546 State = ControlBlock;
547 continue;
548 }
549
Douglas Gregore060e572013-01-25 01:03:03 +0000550 if (Entry.ID == AST_BLOCK_ID) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000551 if (InStream.EnterSubBlock(AST_BLOCK_ID))
552 return true;
553
554 // Found the AST block.
555 State = ASTBlock;
556 continue;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000557 }
558
559 if (InStream.SkipBlock())
560 return true;
561
562 continue;
563
564 case llvm::BitstreamEntry::EndBlock:
Douglas Gregore060e572013-01-25 01:03:03 +0000565 State = Other;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000566 continue;
567 }
568
569 // Read the given record.
570 SmallVector<uint64_t, 64> Record;
571 StringRef Blob;
572 unsigned Code = InStream.readRecord(Entry.ID, Record, &Blob);
573
574 // Handle module dependencies.
575 if (State == ControlBlock && Code == IMPORTS) {
576 // Load each of the imported PCH files.
577 unsigned Idx = 0, N = Record.size();
578 while (Idx < N) {
579 // Read information about the AST file.
580
581 // Skip the imported kind
582 ++Idx;
583
584 // Skip the import location
585 ++Idx;
586
Douglas Gregor7029ce12013-03-19 00:28:20 +0000587 // Load stored size/modification time.
588 off_t StoredSize = (off_t)Record[Idx++];
589 time_t StoredModTime = (time_t)Record[Idx++];
590
Douglas Gregor5e306b12013-01-23 22:38:11 +0000591 // Retrieve the imported file name.
592 unsigned Length = Record[Idx++];
593 SmallString<128> ImportedFile(Record.begin() + Idx,
594 Record.begin() + Idx + Length);
595 Idx += Length;
596
597 // Find the imported module file.
Douglas Gregordadd85d2013-02-08 21:27:45 +0000598 const FileEntry *DependsOnFile
599 = FileMgr.getFile(ImportedFile, /*openFile=*/false,
600 /*cacheFailure=*/false);
Douglas Gregor7029ce12013-03-19 00:28:20 +0000601 if (!DependsOnFile ||
602 (StoredSize != DependsOnFile->getSize()) ||
603 (StoredModTime != DependsOnFile->getModificationTime()))
Douglas Gregor5e306b12013-01-23 22:38:11 +0000604 return true;
605
606 // Record the dependency.
607 unsigned DependsOnID = getModuleFileInfo(DependsOnFile).ID;
608 getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
609 }
610
611 continue;
612 }
613
614 // Handle the identifier table
615 if (State == ASTBlock && Code == IDENTIFIER_TABLE && Record[0] > 0) {
Justin Bognerda4e6502014-04-14 16:34:29 +0000616 typedef
617 OnDiskIterableChainedHashTable<InterestingASTIdentifierLookupTrait>
618 InterestingIdentifierTable;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000619 std::unique_ptr<InterestingIdentifierTable> Table(
620 InterestingIdentifierTable::Create(
621 (const unsigned char *)Blob.data() + Record[0],
Justin Bognerda4e6502014-04-14 16:34:29 +0000622 (const unsigned char *)Blob.data() + sizeof(uint32_t),
Ahmed Charlesb8984322014-03-07 20:03:18 +0000623 (const unsigned char *)Blob.data()));
Douglas Gregor5e306b12013-01-23 22:38:11 +0000624 for (InterestingIdentifierTable::data_iterator D = Table->data_begin(),
625 DEnd = Table->data_end();
626 D != DEnd; ++D) {
627 std::pair<StringRef, bool> Ident = *D;
628 if (Ident.second)
629 InterestingIdentifiers[Ident.first].push_back(ID);
Douglas Gregore060e572013-01-25 01:03:03 +0000630 else
631 (void)InterestingIdentifiers[Ident.first];
Douglas Gregor5e306b12013-01-23 22:38:11 +0000632 }
633 }
634
Douglas Gregor5e306b12013-01-23 22:38:11 +0000635 // We don't care about this record.
636 }
637
638 return false;
639}
640
641namespace {
642
643/// \brief Trait used to generate the identifier index as an on-disk hash
644/// table.
645class IdentifierIndexWriterTrait {
646public:
647 typedef StringRef key_type;
648 typedef StringRef key_type_ref;
649 typedef SmallVector<unsigned, 2> data_type;
650 typedef const SmallVector<unsigned, 2> &data_type_ref;
651
652 static unsigned ComputeHash(key_type_ref Key) {
653 return llvm::HashString(Key);
654 }
655
656 std::pair<unsigned,unsigned>
657 EmitKeyDataLength(raw_ostream& Out, key_type_ref Key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +0000658 using namespace llvm::support;
659 endian::Writer<little> LE(Out);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000660 unsigned KeyLen = Key.size();
661 unsigned DataLen = Data.size() * 4;
Justin Bognere1c147c2014-03-28 22:03:19 +0000662 LE.write<uint16_t>(KeyLen);
663 LE.write<uint16_t>(DataLen);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000664 return std::make_pair(KeyLen, DataLen);
665 }
666
667 void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
668 Out.write(Key.data(), KeyLen);
669 }
670
671 void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
672 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +0000673 using namespace llvm::support;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000674 for (unsigned I = 0, N = Data.size(); I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +0000675 endian::Writer<little>(Out).write<uint32_t>(Data[I]);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000676 }
677};
678
679}
680
681void GlobalModuleIndexBuilder::writeIndex(llvm::BitstreamWriter &Stream) {
682 using namespace llvm;
683
684 // Emit the file header.
685 Stream.Emit((unsigned)'B', 8);
686 Stream.Emit((unsigned)'C', 8);
687 Stream.Emit((unsigned)'G', 8);
688 Stream.Emit((unsigned)'I', 8);
689
690 // Write the block-info block, which describes the records in this bitcode
691 // file.
692 emitBlockInfoBlock(Stream);
693
694 Stream.EnterSubblock(GLOBAL_INDEX_BLOCK_ID, 3);
695
696 // Write the metadata.
697 SmallVector<uint64_t, 2> Record;
698 Record.push_back(CurrentVersion);
Douglas Gregore060e572013-01-25 01:03:03 +0000699 Stream.EmitRecord(INDEX_METADATA, Record);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000700
701 // Write the set of known module files.
702 for (ModuleFilesMap::iterator M = ModuleFiles.begin(),
703 MEnd = ModuleFiles.end();
704 M != MEnd; ++M) {
705 Record.clear();
706 Record.push_back(M->second.ID);
707 Record.push_back(M->first->getSize());
708 Record.push_back(M->first->getModificationTime());
709
710 // File name
711 StringRef Name(M->first->getName());
712 Record.push_back(Name.size());
713 Record.append(Name.begin(), Name.end());
714
715 // Dependencies
716 Record.push_back(M->second.Dependencies.size());
717 Record.append(M->second.Dependencies.begin(), M->second.Dependencies.end());
718 Stream.EmitRecord(MODULE, Record);
719 }
720
721 // Write the identifier -> module file mapping.
722 {
723 OnDiskChainedHashTableGenerator<IdentifierIndexWriterTrait> Generator;
724 IdentifierIndexWriterTrait Trait;
725
726 // Populate the hash table.
727 for (InterestingIdentifierMap::iterator I = InterestingIdentifiers.begin(),
728 IEnd = InterestingIdentifiers.end();
729 I != IEnd; ++I) {
730 Generator.insert(I->first(), I->second, Trait);
731 }
732
733 // Create the on-disk hash table in a buffer.
734 SmallString<4096> IdentifierTable;
735 uint32_t BucketOffset;
736 {
Justin Bognere1c147c2014-03-28 22:03:19 +0000737 using namespace llvm::support;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000738 llvm::raw_svector_ostream Out(IdentifierTable);
739 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +0000740 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000741 BucketOffset = Generator.Emit(Out, Trait);
742 }
743
744 // Create a blob abbreviation
745 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
746 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_INDEX));
747 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
748 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
749 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
750
751 // Write the identifier table
752 Record.clear();
753 Record.push_back(IDENTIFIER_INDEX);
754 Record.push_back(BucketOffset);
755 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
756 }
757
Douglas Gregor5e306b12013-01-23 22:38:11 +0000758 Stream.ExitBlock();
759}
760
761GlobalModuleIndex::ErrorCode
762GlobalModuleIndex::writeIndex(FileManager &FileMgr, StringRef Path) {
763 llvm::SmallString<128> IndexPath;
764 IndexPath += Path;
765 llvm::sys::path::append(IndexPath, IndexFileName);
766
767 // Coordinate building the global index file with other processes that might
768 // try to do the same.
769 llvm::LockFileManager Locked(IndexPath);
770 switch (Locked) {
771 case llvm::LockFileManager::LFS_Error:
772 return EC_IOError;
773
774 case llvm::LockFileManager::LFS_Owned:
775 // We're responsible for building the index ourselves. Do so below.
776 break;
777
778 case llvm::LockFileManager::LFS_Shared:
779 // Someone else is responsible for building the index. We don't care
780 // when they finish, so we're done.
781 return EC_Building;
782 }
783
784 // The module index builder.
785 GlobalModuleIndexBuilder Builder(FileMgr);
786
787 // Load each of the module files.
788 llvm::error_code EC;
789 for (llvm::sys::fs::directory_iterator D(Path, EC), DEnd;
790 D != DEnd && !EC;
791 D.increment(EC)) {
792 // If this isn't a module file, we don't care.
793 if (llvm::sys::path::extension(D->path()) != ".pcm") {
794 // ... unless it's a .pcm.lock file, which indicates that someone is
795 // in the process of rebuilding a module. They'll rebuild the index
796 // at the end of that translation unit, so we don't have to.
797 if (llvm::sys::path::extension(D->path()) == ".pcm.lock")
798 return EC_Building;
799
800 continue;
801 }
802
803 // If we can't find the module file, skip it.
804 const FileEntry *ModuleFile = FileMgr.getFile(D->path());
805 if (!ModuleFile)
806 continue;
807
808 // Load this module file.
809 if (Builder.loadModuleFile(ModuleFile))
810 return EC_IOError;
811 }
812
813 // The output buffer, into which the global index will be written.
814 SmallVector<char, 16> OutputBuffer;
815 {
816 llvm::BitstreamWriter OutputStream(OutputBuffer);
817 Builder.writeIndex(OutputStream);
818 }
819
820 // Write the global index file to a temporary file.
821 llvm::SmallString<128> IndexTmpPath;
822 int TmpFD;
Rafael Espindola18627112013-07-05 21:13:58 +0000823 if (llvm::sys::fs::createUniqueFile(IndexPath + "-%%%%%%%%", TmpFD,
824 IndexTmpPath))
Douglas Gregor5e306b12013-01-23 22:38:11 +0000825 return EC_IOError;
826
827 // Open the temporary global index file for output.
NAKAMURA Takumie00c9862013-01-24 08:20:11 +0000828 llvm::raw_fd_ostream Out(TmpFD, true);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000829 if (Out.has_error())
830 return EC_IOError;
831
832 // Write the index.
833 Out.write(OutputBuffer.data(), OutputBuffer.size());
834 Out.close();
835 if (Out.has_error())
836 return EC_IOError;
837
838 // Remove the old index file. It isn't relevant any more.
Rafael Espindola2a008782014-01-10 21:32:14 +0000839 llvm::sys::fs::remove(IndexPath.str());
Douglas Gregor5e306b12013-01-23 22:38:11 +0000840
841 // Rename the newly-written index file to the proper name.
842 if (llvm::sys::fs::rename(IndexTmpPath.str(), IndexPath.str())) {
843 // Rename failed; just remove the
Rafael Espindola2a008782014-01-10 21:32:14 +0000844 llvm::sys::fs::remove(IndexTmpPath.str());
Douglas Gregor5e306b12013-01-23 22:38:11 +0000845 return EC_IOError;
846 }
847
848 // We're done.
849 return EC_None;
850}
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000851
852namespace {
853 class GlobalIndexIdentifierIterator : public IdentifierIterator {
854 /// \brief The current position within the identifier lookup table.
855 IdentifierIndexTable::key_iterator Current;
856
857 /// \brief The end position within the identifier lookup table.
858 IdentifierIndexTable::key_iterator End;
859
860 public:
861 explicit GlobalIndexIdentifierIterator(IdentifierIndexTable &Idx) {
862 Current = Idx.key_begin();
863 End = Idx.key_end();
864 }
865
Craig Topper3e89dfe2014-03-13 02:13:41 +0000866 StringRef Next() override {
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000867 if (Current == End)
868 return StringRef();
869
870 StringRef Result = *Current;
871 ++Current;
872 return Result;
873 }
874 };
875}
876
877IdentifierIterator *GlobalModuleIndex::createIdentifierIterator() const {
878 IdentifierIndexTable &Table =
879 *static_cast<IdentifierIndexTable *>(IdentifierIndex);
880 return new GlobalIndexIdentifierIterator(Table);
881}