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