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