blob: ebcfa9f50674c90178cdb3d6863e6bce6198bee5 [file] [log] [blame]
Douglas Gregor5e306b12013-01-23 22:38:11 +00001//===--- GlobalModuleIndex.cpp - Global Module Index ------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Douglas Gregor5e306b12013-01-23 22:38:11 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the GlobalModuleIndex class.
10//
11//===----------------------------------------------------------------------===//
12
Anton Afanasyevd880de22019-03-30 08:42:48 +000013
Douglas Gregor5e306b12013-01-23 22:38:11 +000014#include "ASTReaderInternals.h"
15#include "clang/Basic/FileManager.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000016#include "clang/Lex/HeaderSearch.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000017#include "clang/Serialization/ASTBitCodes.h"
18#include "clang/Serialization/GlobalModuleIndex.h"
Douglas Gregor603cd862013-03-22 18:50:14 +000019#include "clang/Serialization/Module.h"
Richard Trieuf3b00462018-12-12 02:53:59 +000020#include "clang/Serialization/PCHContainerOperations.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"
Douglas Gregor5e306b12013-01-23 22:38:11 +000024#include "llvm/Bitcode/BitstreamReader.h"
25#include "llvm/Bitcode/BitstreamWriter.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +000026#include "llvm/Support/DJB.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"
Justin Bognerbb094f02014-04-18 19:57:06 +000030#include "llvm/Support/OnDiskHashTable.h"
Rafael Espindola552c1692013-06-11 22:15:02 +000031#include "llvm/Support/Path.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000032#include "llvm/Support/TimeProfiler.h"
NAKAMURA Takumif0add232013-01-25 01:47:07 +000033#include <cstdio>
Douglas Gregor5e306b12013-01-23 22:38:11 +000034using namespace clang;
35using namespace serialization;
36
37//----------------------------------------------------------------------------//
38// Shared constants
39//----------------------------------------------------------------------------//
40namespace {
41 enum {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000042 /// The block containing the index.
Douglas Gregor5e306b12013-01-23 22:38:11 +000043 GLOBAL_INDEX_BLOCK_ID = llvm::bitc::FIRST_APPLICATION_BLOCKID
44 };
45
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000046 /// Describes the record types in the index.
Douglas Gregor5e306b12013-01-23 22:38:11 +000047 enum IndexRecordTypes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000048 /// Contains version information and potentially other metadata,
Douglas Gregor5e306b12013-01-23 22:38:11 +000049 /// used to determine if we can read this global index file.
Douglas Gregore060e572013-01-25 01:03:03 +000050 INDEX_METADATA,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000051 /// Describes a module, including its file name and dependencies.
Douglas Gregor5e306b12013-01-23 22:38:11 +000052 MODULE,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000053 /// The index for identifiers.
Douglas Gregor5e306b12013-01-23 22:38:11 +000054 IDENTIFIER_INDEX
55 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000056}
Douglas Gregor5e306b12013-01-23 22:38:11 +000057
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000058/// The name of the global index file.
Douglas Gregor5e306b12013-01-23 22:38:11 +000059static const char * const IndexFileName = "modules.idx";
60
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000061/// The global index file version.
Douglas Gregor5e306b12013-01-23 22:38:11 +000062static const unsigned CurrentVersion = 1;
63
64//----------------------------------------------------------------------------//
Douglas Gregore060e572013-01-25 01:03:03 +000065// Global module index reader.
66//----------------------------------------------------------------------------//
67
68namespace {
69
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000070/// Trait used to read the identifier index from the on-disk hash
Douglas Gregore060e572013-01-25 01:03:03 +000071/// table.
72class IdentifierIndexReaderTrait {
73public:
74 typedef StringRef external_key_type;
75 typedef StringRef internal_key_type;
76 typedef SmallVector<unsigned, 2> data_type;
Justin Bogner25463f12014-04-18 20:27:24 +000077 typedef unsigned hash_value_type;
78 typedef unsigned offset_type;
Douglas Gregore060e572013-01-25 01:03:03 +000079
80 static bool EqualKey(const internal_key_type& a, const internal_key_type& b) {
81 return a == b;
82 }
83
Justin Bogner25463f12014-04-18 20:27:24 +000084 static hash_value_type ComputeHash(const internal_key_type& a) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +000085 return llvm::djbHash(a);
Douglas Gregore060e572013-01-25 01:03:03 +000086 }
87
88 static std::pair<unsigned, unsigned>
89 ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +000090 using namespace llvm::support;
91 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
92 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Douglas Gregore060e572013-01-25 01:03:03 +000093 return std::make_pair(KeyLen, DataLen);
94 }
95
96 static const internal_key_type&
97 GetInternalKey(const external_key_type& x) { return x; }
98
99 static const external_key_type&
100 GetExternalKey(const internal_key_type& x) { return x; }
101
102 static internal_key_type ReadKey(const unsigned char* d, unsigned n) {
103 return StringRef((const char *)d, n);
104 }
105
106 static data_type ReadData(const internal_key_type& k,
107 const unsigned char* d,
108 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000109 using namespace llvm::support;
Douglas Gregore060e572013-01-25 01:03:03 +0000110
111 data_type Result;
112 while (DataLen > 0) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000113 unsigned ID = endian::readNext<uint32_t, little, unaligned>(d);
Douglas Gregore060e572013-01-25 01:03:03 +0000114 Result.push_back(ID);
115 DataLen -= 4;
116 }
117
118 return Result;
119 }
120};
121
Justin Bognerbb094f02014-04-18 19:57:06 +0000122typedef llvm::OnDiskIterableChainedHashTable<IdentifierIndexReaderTrait>
Justin Bognerda4e6502014-04-14 16:34:29 +0000123 IdentifierIndexTable;
Douglas Gregore060e572013-01-25 01:03:03 +0000124
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000125}
Douglas Gregore060e572013-01-25 01:03:03 +0000126
David Blaikieafa10d32014-08-11 18:47:26 +0000127GlobalModuleIndex::GlobalModuleIndex(std::unique_ptr<llvm::MemoryBuffer> Buffer,
Douglas Gregore060e572013-01-25 01:03:03 +0000128 llvm::BitstreamCursor Cursor)
David Blaikieafa10d32014-08-11 18:47:26 +0000129 : Buffer(std::move(Buffer)), IdentifierIndex(), NumIdentifierLookups(),
130 NumIdentifierLookupHits() {
Anton Afanasyevd880de22019-03-30 08:42:48 +0000131 llvm::TimeTraceScope TimeScope("Module LoadIndex", StringRef(""));
Douglas Gregore060e572013-01-25 01:03:03 +0000132 // Read the global index.
Douglas Gregore060e572013-01-25 01:03:03 +0000133 bool InGlobalIndexBlock = false;
134 bool Done = false;
Douglas Gregore060e572013-01-25 01:03:03 +0000135 while (!Done) {
136 llvm::BitstreamEntry Entry = Cursor.advance();
137
138 switch (Entry.Kind) {
139 case llvm::BitstreamEntry::Error:
140 return;
141
142 case llvm::BitstreamEntry::EndBlock:
143 if (InGlobalIndexBlock) {
144 InGlobalIndexBlock = false;
145 Done = true;
146 continue;
147 }
148 return;
149
150
151 case llvm::BitstreamEntry::Record:
152 // Entries in the global index block are handled below.
153 if (InGlobalIndexBlock)
154 break;
155
156 return;
157
158 case llvm::BitstreamEntry::SubBlock:
159 if (!InGlobalIndexBlock && Entry.ID == GLOBAL_INDEX_BLOCK_ID) {
160 if (Cursor.EnterSubBlock(GLOBAL_INDEX_BLOCK_ID))
161 return;
162
163 InGlobalIndexBlock = true;
164 } else if (Cursor.SkipBlock()) {
165 return;
166 }
167 continue;
168 }
169
170 SmallVector<uint64_t, 64> Record;
171 StringRef Blob;
172 switch ((IndexRecordTypes)Cursor.readRecord(Entry.ID, Record, &Blob)) {
173 case INDEX_METADATA:
174 // Make sure that the version matches.
175 if (Record.size() < 1 || Record[0] != CurrentVersion)
176 return;
177 break;
178
179 case MODULE: {
180 unsigned Idx = 0;
181 unsigned ID = Record[Idx++];
Douglas Gregor7029ce12013-03-19 00:28:20 +0000182
183 // Make room for this module's information.
184 if (ID == Modules.size())
185 Modules.push_back(ModuleInfo());
186 else
187 Modules.resize(ID + 1);
188
189 // Size/modification time for this module file at the time the
190 // global index was built.
191 Modules[ID].Size = Record[Idx++];
192 Modules[ID].ModTime = Record[Idx++];
Douglas Gregore060e572013-01-25 01:03:03 +0000193
194 // File name.
195 unsigned NameLen = Record[Idx++];
Douglas Gregor7029ce12013-03-19 00:28:20 +0000196 Modules[ID].FileName.assign(Record.begin() + Idx,
197 Record.begin() + Idx + NameLen);
Douglas Gregore060e572013-01-25 01:03:03 +0000198 Idx += NameLen;
199
200 // Dependencies
201 unsigned NumDeps = Record[Idx++];
Douglas Gregor7029ce12013-03-19 00:28:20 +0000202 Modules[ID].Dependencies.insert(Modules[ID].Dependencies.end(),
203 Record.begin() + Idx,
204 Record.begin() + Idx + NumDeps);
205 Idx += NumDeps;
Douglas Gregore060e572013-01-25 01:03:03 +0000206
Douglas Gregor7029ce12013-03-19 00:28:20 +0000207 // Make sure we're at the end of the record.
208 assert(Idx == Record.size() && "More module info?");
Douglas Gregor603cd862013-03-22 18:50:14 +0000209
210 // Record this module as an unresolved module.
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000211 // FIXME: this doesn't work correctly for module names containing path
212 // separators.
213 StringRef ModuleName = llvm::sys::path::stem(Modules[ID].FileName);
214 // Remove the -<hash of ModuleMapPath>
215 ModuleName = ModuleName.rsplit('-').first;
216 UnresolvedModules[ModuleName] = ID;
Douglas Gregore060e572013-01-25 01:03:03 +0000217 break;
218 }
219
220 case IDENTIFIER_INDEX:
221 // Wire up the identifier index.
222 if (Record[0]) {
223 IdentifierIndex = IdentifierIndexTable::Create(
Justin Bognerda4e6502014-04-14 16:34:29 +0000224 (const unsigned char *)Blob.data() + Record[0],
225 (const unsigned char *)Blob.data() + sizeof(uint32_t),
226 (const unsigned char *)Blob.data(), IdentifierIndexReaderTrait());
Douglas Gregore060e572013-01-25 01:03:03 +0000227 }
228 break;
229 }
230 }
Douglas Gregore060e572013-01-25 01:03:03 +0000231}
232
Nico Webere68b8472014-04-25 19:45:23 +0000233GlobalModuleIndex::~GlobalModuleIndex() {
234 delete static_cast<IdentifierIndexTable *>(IdentifierIndex);
235}
Douglas Gregore060e572013-01-25 01:03:03 +0000236
237std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode>
Douglas Gregor7029ce12013-03-19 00:28:20 +0000238GlobalModuleIndex::readIndex(StringRef Path) {
Douglas Gregore060e572013-01-25 01:03:03 +0000239 // Load the index file, if it's there.
240 llvm::SmallString<128> IndexPath;
241 IndexPath += Path;
242 llvm::sys::path::append(IndexPath, IndexFileName);
243
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000244 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferOrErr =
245 llvm::MemoryBuffer::getFile(IndexPath.c_str());
246 if (!BufferOrErr)
Craig Toppera13603a2014-05-22 05:54:18 +0000247 return std::make_pair(nullptr, EC_NotFound);
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000248 std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(BufferOrErr.get());
Douglas Gregore060e572013-01-25 01:03:03 +0000249
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000250 /// The main bitstream cursor for the main block.
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000251 llvm::BitstreamCursor Cursor(*Buffer);
Douglas Gregore060e572013-01-25 01:03:03 +0000252
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') {
Craig Toppera13603a2014-05-22 05:54:18 +0000258 return std::make_pair(nullptr, EC_IOError);
Douglas Gregore060e572013-01-25 01:03:03 +0000259 }
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000260
David Blaikieafa10d32014-08-11 18:47:26 +0000261 return std::make_pair(new GlobalModuleIndex(std::move(Buffer), Cursor),
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000262 EC_None);
Douglas Gregore060e572013-01-25 01:03:03 +0000263}
264
Douglas Gregor7029ce12013-03-19 00:28:20 +0000265void
266GlobalModuleIndex::getKnownModules(SmallVectorImpl<ModuleFile *> &ModuleFiles) {
Douglas Gregore060e572013-01-25 01:03:03 +0000267 ModuleFiles.clear();
268 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
Douglas Gregor603cd862013-03-22 18:50:14 +0000269 if (ModuleFile *MF = Modules[I].File)
270 ModuleFiles.push_back(MF);
Douglas Gregore060e572013-01-25 01:03:03 +0000271 }
272}
273
274void GlobalModuleIndex::getModuleDependencies(
Douglas Gregor7029ce12013-03-19 00:28:20 +0000275 ModuleFile *File,
276 SmallVectorImpl<ModuleFile *> &Dependencies) {
Douglas Gregore060e572013-01-25 01:03:03 +0000277 // Look for information about this module file.
Douglas Gregor7029ce12013-03-19 00:28:20 +0000278 llvm::DenseMap<ModuleFile *, unsigned>::iterator Known
279 = ModulesByFile.find(File);
Douglas Gregore060e572013-01-25 01:03:03 +0000280 if (Known == ModulesByFile.end())
281 return;
282
283 // Record dependencies.
Douglas Gregor7029ce12013-03-19 00:28:20 +0000284 Dependencies.clear();
285 ArrayRef<unsigned> StoredDependencies = Modules[Known->second].Dependencies;
286 for (unsigned I = 0, N = StoredDependencies.size(); I != N; ++I) {
Douglas Gregor603cd862013-03-22 18:50:14 +0000287 if (ModuleFile *MF = Modules[I].File)
Douglas Gregor7029ce12013-03-19 00:28:20 +0000288 Dependencies.push_back(MF);
289 }
Douglas Gregore060e572013-01-25 01:03:03 +0000290}
291
Douglas Gregor7211ac12013-01-25 23:32:03 +0000292bool GlobalModuleIndex::lookupIdentifier(StringRef Name, HitSet &Hits) {
293 Hits.clear();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000294
Douglas Gregore060e572013-01-25 01:03:03 +0000295 // 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) {
Douglas Gregor603cd862013-03-22 18:50:14 +0000310 if (ModuleFile *MF = Modules[ModuleIDs[I]].File)
311 Hits.insert(MF);
Douglas Gregore060e572013-01-25 01:03:03 +0000312 }
313
314 ++NumIdentifierLookupHits;
315 return true;
316}
317
Douglas Gregor603cd862013-03-22 18:50:14 +0000318bool GlobalModuleIndex::loadedModuleFile(ModuleFile *File) {
319 // Look for the module in the global module index based on the module name.
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000320 StringRef Name = File->ModuleName;
Douglas Gregor603cd862013-03-22 18:50:14 +0000321 llvm::StringMap<unsigned>::iterator Known = UnresolvedModules.find(Name);
322 if (Known == UnresolvedModules.end()) {
323 return true;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000324 }
325
Douglas Gregor603cd862013-03-22 18:50:14 +0000326 // 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;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000338 }
339
Douglas Gregor603cd862013-03-22 18:50:14 +0000340 // One way or another, we have resolved this module file.
341 UnresolvedModules.erase(Known);
342 return Failed;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000343}
344
Douglas Gregore060e572013-01-25 01:03:03 +0000345void 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 }
Douglas Gregore060e572013-01-25 01:03:03 +0000352 std::fprintf(stderr, "\n");
353}
354
Yaron Kerencdae9412016-01-29 19:38:18 +0000355LLVM_DUMP_METHOD void GlobalModuleIndex::dump() {
John Thompsona39baf12014-04-17 17:06:13 +0000356 llvm::errs() << "*** Global Module Index Dump:\n";
357 llvm::errs() << "Module files:\n";
John Thompson4f52d442014-04-17 18:17:36 +0000358 for (auto &MI : Modules) {
John Thompsona39baf12014-04-17 17:06:13 +0000359 llvm::errs() << "** " << MI.FileName << "\n";
360 if (MI.File)
361 MI.File->dump();
John Thompsonbcdcc922014-04-16 21:03:41 +0000362 else
John Thompsona39baf12014-04-17 17:06:13 +0000363 llvm::errs() << "\n";
John Thompsonbcdcc922014-04-16 21:03:41 +0000364 }
John Thompsona39baf12014-04-17 17:06:13 +0000365 llvm::errs() << "\n";
John Thompsonbcdcc922014-04-16 21:03:41 +0000366}
367
Douglas Gregore060e572013-01-25 01:03:03 +0000368//----------------------------------------------------------------------------//
Douglas Gregor5e306b12013-01-23 22:38:11 +0000369// Global module index writer.
370//----------------------------------------------------------------------------//
371
372namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000373 /// Provides information about a specific module file.
Douglas Gregor5e306b12013-01-23 22:38:11 +0000374 struct ModuleFileInfo {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000375 /// The numberic ID for this module file.
Douglas Gregor5e306b12013-01-23 22:38:11 +0000376 unsigned ID;
377
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000378 /// The set of modules on which this module depends. Each entry is
Douglas Gregor5e306b12013-01-23 22:38:11 +0000379 /// a module ID.
380 SmallVector<unsigned, 4> Dependencies;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000381 ASTFileSignature Signature;
382 };
383
384 struct ImportedModuleFileInfo {
385 off_t StoredSize;
386 time_t StoredModTime;
387 ASTFileSignature StoredSignature;
388 ImportedModuleFileInfo(off_t Size, time_t ModTime, ASTFileSignature Sig)
389 : StoredSize(Size), StoredModTime(ModTime), StoredSignature(Sig) {}
Douglas Gregor5e306b12013-01-23 22:38:11 +0000390 };
391
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000392 /// Builder that generates the global module index file.
Douglas Gregor5e306b12013-01-23 22:38:11 +0000393 class GlobalModuleIndexBuilder {
394 FileManager &FileMgr;
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000395 const PCHContainerReader &PCHContainerRdr;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000396
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000397 /// Mapping from files to module file information.
Douglas Gregor5e306b12013-01-23 22:38:11 +0000398 typedef llvm::MapVector<const FileEntry *, ModuleFileInfo> ModuleFilesMap;
399
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000400 /// Information about each of the known module files.
Douglas Gregor5e306b12013-01-23 22:38:11 +0000401 ModuleFilesMap ModuleFiles;
402
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000403 /// Mapping from the imported module file to the imported
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000404 /// information.
405 typedef std::multimap<const FileEntry *, ImportedModuleFileInfo>
406 ImportedModuleFilesMap;
407
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000408 /// Information about each importing of a module file.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000409 ImportedModuleFilesMap ImportedModuleFiles;
410
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000411 /// Mapping from identifiers to the list of module file IDs that
Douglas Gregor5e306b12013-01-23 22:38:11 +0000412 /// consider this identifier to be interesting.
413 typedef llvm::StringMap<SmallVector<unsigned, 2> > InterestingIdentifierMap;
414
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000415 /// A mapping from all interesting identifiers to the set of module
Douglas Gregor5e306b12013-01-23 22:38:11 +0000416 /// files in which those identifiers are considered interesting.
417 InterestingIdentifierMap InterestingIdentifiers;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000418
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000419 /// Write the block-info block for the global module index file.
Douglas Gregor5e306b12013-01-23 22:38:11 +0000420 void emitBlockInfoBlock(llvm::BitstreamWriter &Stream);
421
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000422 /// Retrieve the module file information for the given file.
Douglas Gregor5e306b12013-01-23 22:38:11 +0000423 ModuleFileInfo &getModuleFileInfo(const FileEntry *File) {
424 llvm::MapVector<const FileEntry *, ModuleFileInfo>::iterator Known
425 = ModuleFiles.find(File);
426 if (Known != ModuleFiles.end())
427 return Known->second;
428
429 unsigned NewID = ModuleFiles.size();
430 ModuleFileInfo &Info = ModuleFiles[File];
431 Info.ID = NewID;
432 return Info;
433 }
434
435 public:
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000436 explicit GlobalModuleIndexBuilder(
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000437 FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr)
438 : FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr) {}
Douglas Gregor5e306b12013-01-23 22:38:11 +0000439
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000440 /// Load the contents of the given module file into the builder.
Douglas Gregor5e306b12013-01-23 22:38:11 +0000441 ///
442 /// \returns true if an error occurred, false otherwise.
443 bool loadModuleFile(const FileEntry *File);
444
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000445 /// Write the index to the given bitstream.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000446 /// \returns true if an error occurred, false otherwise.
447 bool writeIndex(llvm::BitstreamWriter &Stream);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000448 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000449}
Douglas Gregor5e306b12013-01-23 22:38:11 +0000450
451static void emitBlockID(unsigned ID, const char *Name,
452 llvm::BitstreamWriter &Stream,
453 SmallVectorImpl<uint64_t> &Record) {
454 Record.clear();
455 Record.push_back(ID);
456 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
457
458 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000459 if (!Name || Name[0] == 0) return;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000460 Record.clear();
461 while (*Name)
462 Record.push_back(*Name++);
463 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
464}
465
466static void emitRecordID(unsigned ID, const char *Name,
467 llvm::BitstreamWriter &Stream,
468 SmallVectorImpl<uint64_t> &Record) {
469 Record.clear();
470 Record.push_back(ID);
471 while (*Name)
472 Record.push_back(*Name++);
473 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
474}
475
476void
477GlobalModuleIndexBuilder::emitBlockInfoBlock(llvm::BitstreamWriter &Stream) {
478 SmallVector<uint64_t, 64> Record;
Peter Collingbourned3a6c702016-11-01 01:18:57 +0000479 Stream.EnterBlockInfoBlock();
Douglas Gregor5e306b12013-01-23 22:38:11 +0000480
481#define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record)
482#define RECORD(X) emitRecordID(X, #X, Stream, Record)
483 BLOCK(GLOBAL_INDEX_BLOCK);
Douglas Gregore060e572013-01-25 01:03:03 +0000484 RECORD(INDEX_METADATA);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000485 RECORD(MODULE);
486 RECORD(IDENTIFIER_INDEX);
487#undef RECORD
488#undef BLOCK
489
490 Stream.ExitBlock();
491}
492
Douglas Gregore060e572013-01-25 01:03:03 +0000493namespace {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000494 class InterestingASTIdentifierLookupTrait
495 : public serialization::reader::ASTIdentifierLookupTraitBase {
496
497 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000498 /// The identifier and whether it is "interesting".
Douglas Gregor5e306b12013-01-23 22:38:11 +0000499 typedef std::pair<StringRef, bool> data_type;
500
501 data_type ReadData(const internal_key_type& k,
502 const unsigned char* d,
503 unsigned DataLen) {
504 // The first bit indicates whether this identifier is interesting.
505 // That's all we care about.
Justin Bogner57ba0b22014-03-28 22:03:24 +0000506 using namespace llvm::support;
507 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000508 bool IsInteresting = RawID & 0x01;
509 return std::make_pair(k, IsInteresting);
510 }
511 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000512}
Douglas Gregor5e306b12013-01-23 22:38:11 +0000513
514bool GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
515 // Open the module file.
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000516
Benjamin Kramera8857962014-10-26 22:44:13 +0000517 auto Buffer = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000518 if (!Buffer) {
519 return true;
520 }
521
522 // Initialize the input stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000523 llvm::BitstreamCursor InStream(PCHContainerRdr.ExtractPCH(**Buffer));
Douglas Gregor5e306b12013-01-23 22:38:11 +0000524
525 // Sniff for the signature.
526 if (InStream.Read(8) != 'C' ||
527 InStream.Read(8) != 'P' ||
528 InStream.Read(8) != 'C' ||
529 InStream.Read(8) != 'H') {
530 return true;
531 }
532
533 // Record this module file and assign it a unique ID (if it doesn't have
534 // one already).
535 unsigned ID = getModuleFileInfo(File).ID;
536
537 // Search for the blocks and records we care about.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000538 enum { Other, ControlBlock, ASTBlock, DiagnosticOptionsBlock } State = Other;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000539 bool Done = false;
540 while (!Done) {
Douglas Gregore060e572013-01-25 01:03:03 +0000541 llvm::BitstreamEntry Entry = InStream.advance();
Douglas Gregor5e306b12013-01-23 22:38:11 +0000542 switch (Entry.Kind) {
543 case llvm::BitstreamEntry::Error:
Douglas Gregore060e572013-01-25 01:03:03 +0000544 Done = true;
545 continue;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000546
547 case llvm::BitstreamEntry::Record:
Douglas Gregore060e572013-01-25 01:03:03 +0000548 // In the 'other' state, just skip the record. We don't care.
549 if (State == Other) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000550 InStream.skipRecord(Entry.ID);
551 continue;
552 }
553
554 // Handle potentially-interesting records below.
555 break;
556
557 case llvm::BitstreamEntry::SubBlock:
Douglas Gregore060e572013-01-25 01:03:03 +0000558 if (Entry.ID == CONTROL_BLOCK_ID) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000559 if (InStream.EnterSubBlock(CONTROL_BLOCK_ID))
560 return true;
561
562 // Found the control block.
563 State = ControlBlock;
564 continue;
565 }
566
Douglas Gregore060e572013-01-25 01:03:03 +0000567 if (Entry.ID == AST_BLOCK_ID) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000568 if (InStream.EnterSubBlock(AST_BLOCK_ID))
569 return true;
570
571 // Found the AST block.
572 State = ASTBlock;
573 continue;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000574 }
575
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000576 if (Entry.ID == UNHASHED_CONTROL_BLOCK_ID) {
577 if (InStream.EnterSubBlock(UNHASHED_CONTROL_BLOCK_ID))
578 return true;
579
580 // Found the Diagnostic Options block.
581 State = DiagnosticOptionsBlock;
582 continue;
583 }
584
Douglas Gregor5e306b12013-01-23 22:38:11 +0000585 if (InStream.SkipBlock())
586 return true;
587
588 continue;
589
590 case llvm::BitstreamEntry::EndBlock:
Douglas Gregore060e572013-01-25 01:03:03 +0000591 State = Other;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000592 continue;
593 }
594
595 // Read the given record.
596 SmallVector<uint64_t, 64> Record;
597 StringRef Blob;
598 unsigned Code = InStream.readRecord(Entry.ID, Record, &Blob);
599
600 // Handle module dependencies.
601 if (State == ControlBlock && Code == IMPORTS) {
602 // Load each of the imported PCH files.
603 unsigned Idx = 0, N = Record.size();
604 while (Idx < N) {
605 // Read information about the AST file.
606
607 // Skip the imported kind
608 ++Idx;
609
610 // Skip the import location
611 ++Idx;
612
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000613 // Load stored size/modification time.
Douglas Gregor7029ce12013-03-19 00:28:20 +0000614 off_t StoredSize = (off_t)Record[Idx++];
615 time_t StoredModTime = (time_t)Record[Idx++];
616
Ben Langmuir487ea142014-10-23 18:05:36 +0000617 // Skip the stored signature.
618 // FIXME: we could read the signature out of the import and validate it.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000619 ASTFileSignature StoredSignature = {
620 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
621 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
622 (uint32_t)Record[Idx++]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +0000623
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000624 // Skip the module name (currently this is only used for prebuilt
625 // modules while here we are only dealing with cached).
626 Idx += Record[Idx] + 1;
627
Douglas Gregor5e306b12013-01-23 22:38:11 +0000628 // Retrieve the imported file name.
629 unsigned Length = Record[Idx++];
630 SmallString<128> ImportedFile(Record.begin() + Idx,
631 Record.begin() + Idx + Length);
632 Idx += Length;
633
634 // Find the imported module file.
Douglas Gregordadd85d2013-02-08 21:27:45 +0000635 const FileEntry *DependsOnFile
636 = FileMgr.getFile(ImportedFile, /*openFile=*/false,
637 /*cacheFailure=*/false);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000638
639 if (!DependsOnFile)
Douglas Gregor5e306b12013-01-23 22:38:11 +0000640 return true;
641
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000642 // Save the information in ImportedModuleFileInfo so we can verify after
643 // loading all pcms.
644 ImportedModuleFiles.insert(std::make_pair(
645 DependsOnFile, ImportedModuleFileInfo(StoredSize, StoredModTime,
646 StoredSignature)));
647
Douglas Gregor5e306b12013-01-23 22:38:11 +0000648 // Record the dependency.
649 unsigned DependsOnID = getModuleFileInfo(DependsOnFile).ID;
650 getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
651 }
652
653 continue;
654 }
655
656 // Handle the identifier table
657 if (State == ASTBlock && Code == IDENTIFIER_TABLE && Record[0] > 0) {
Justin Bognerbb094f02014-04-18 19:57:06 +0000658 typedef llvm::OnDiskIterableChainedHashTable<
659 InterestingASTIdentifierLookupTrait> InterestingIdentifierTable;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000660 std::unique_ptr<InterestingIdentifierTable> Table(
661 InterestingIdentifierTable::Create(
662 (const unsigned char *)Blob.data() + Record[0],
Justin Bognerda4e6502014-04-14 16:34:29 +0000663 (const unsigned char *)Blob.data() + sizeof(uint32_t),
Ahmed Charlesb8984322014-03-07 20:03:18 +0000664 (const unsigned char *)Blob.data()));
Douglas Gregor5e306b12013-01-23 22:38:11 +0000665 for (InterestingIdentifierTable::data_iterator D = Table->data_begin(),
666 DEnd = Table->data_end();
667 D != DEnd; ++D) {
668 std::pair<StringRef, bool> Ident = *D;
669 if (Ident.second)
670 InterestingIdentifiers[Ident.first].push_back(ID);
Douglas Gregore060e572013-01-25 01:03:03 +0000671 else
672 (void)InterestingIdentifiers[Ident.first];
Douglas Gregor5e306b12013-01-23 22:38:11 +0000673 }
674 }
675
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000676 // Get Signature.
677 if (State == DiagnosticOptionsBlock && Code == SIGNATURE)
678 getModuleFileInfo(File).Signature = {
679 {{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
680 (uint32_t)Record[3], (uint32_t)Record[4]}}};
681
Douglas Gregor5e306b12013-01-23 22:38:11 +0000682 // We don't care about this record.
683 }
684
685 return false;
686}
687
688namespace {
689
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000690/// Trait used to generate the identifier index as an on-disk hash
Douglas Gregor5e306b12013-01-23 22:38:11 +0000691/// table.
692class IdentifierIndexWriterTrait {
693public:
694 typedef StringRef key_type;
695 typedef StringRef key_type_ref;
696 typedef SmallVector<unsigned, 2> data_type;
697 typedef const SmallVector<unsigned, 2> &data_type_ref;
Justin Bogner25463f12014-04-18 20:27:24 +0000698 typedef unsigned hash_value_type;
699 typedef unsigned offset_type;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000700
Justin Bogner25463f12014-04-18 20:27:24 +0000701 static hash_value_type ComputeHash(key_type_ref Key) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000702 return llvm::djbHash(Key);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000703 }
704
705 std::pair<unsigned,unsigned>
706 EmitKeyDataLength(raw_ostream& Out, key_type_ref Key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +0000707 using namespace llvm::support;
Peter Collingbournee3f65292018-05-18 19:46:24 +0000708 endian::Writer LE(Out, little);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000709 unsigned KeyLen = Key.size();
710 unsigned DataLen = Data.size() * 4;
Justin Bognere1c147c2014-03-28 22:03:19 +0000711 LE.write<uint16_t>(KeyLen);
712 LE.write<uint16_t>(DataLen);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000713 return std::make_pair(KeyLen, DataLen);
714 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000715
Douglas Gregor5e306b12013-01-23 22:38:11 +0000716 void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
717 Out.write(Key.data(), KeyLen);
718 }
719
720 void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
721 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +0000722 using namespace llvm::support;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000723 for (unsigned I = 0, N = Data.size(); I != N; ++I)
Peter Collingbournee3f65292018-05-18 19:46:24 +0000724 endian::write<uint32_t>(Out, Data[I], little);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000725 }
726};
727
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000728}
Douglas Gregor5e306b12013-01-23 22:38:11 +0000729
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000730bool GlobalModuleIndexBuilder::writeIndex(llvm::BitstreamWriter &Stream) {
731 for (auto MapEntry : ImportedModuleFiles) {
732 auto *File = MapEntry.first;
733 ImportedModuleFileInfo &Info = MapEntry.second;
734 if (getModuleFileInfo(File).Signature) {
735 if (getModuleFileInfo(File).Signature != Info.StoredSignature)
736 // Verify Signature.
737 return true;
738 } else if (Info.StoredSize != File->getSize() ||
739 Info.StoredModTime != File->getModificationTime())
740 // Verify Size and ModTime.
741 return true;
742 }
743
Douglas Gregor5e306b12013-01-23 22:38:11 +0000744 using namespace llvm;
Anton Afanasyevd880de22019-03-30 08:42:48 +0000745 llvm::TimeTraceScope TimeScope("Module WriteIndex", StringRef(""));
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000746
Douglas Gregor5e306b12013-01-23 22:38:11 +0000747 // Emit the file header.
748 Stream.Emit((unsigned)'B', 8);
749 Stream.Emit((unsigned)'C', 8);
750 Stream.Emit((unsigned)'G', 8);
751 Stream.Emit((unsigned)'I', 8);
752
753 // Write the block-info block, which describes the records in this bitcode
754 // file.
755 emitBlockInfoBlock(Stream);
756
757 Stream.EnterSubblock(GLOBAL_INDEX_BLOCK_ID, 3);
758
759 // Write the metadata.
760 SmallVector<uint64_t, 2> Record;
761 Record.push_back(CurrentVersion);
Douglas Gregore060e572013-01-25 01:03:03 +0000762 Stream.EmitRecord(INDEX_METADATA, Record);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000763
764 // Write the set of known module files.
765 for (ModuleFilesMap::iterator M = ModuleFiles.begin(),
766 MEnd = ModuleFiles.end();
767 M != MEnd; ++M) {
768 Record.clear();
769 Record.push_back(M->second.ID);
770 Record.push_back(M->first->getSize());
771 Record.push_back(M->first->getModificationTime());
772
773 // File name
774 StringRef Name(M->first->getName());
775 Record.push_back(Name.size());
776 Record.append(Name.begin(), Name.end());
777
778 // Dependencies
779 Record.push_back(M->second.Dependencies.size());
780 Record.append(M->second.Dependencies.begin(), M->second.Dependencies.end());
781 Stream.EmitRecord(MODULE, Record);
782 }
783
784 // Write the identifier -> module file mapping.
785 {
Justin Bognerbb094f02014-04-18 19:57:06 +0000786 llvm::OnDiskChainedHashTableGenerator<IdentifierIndexWriterTrait> Generator;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000787 IdentifierIndexWriterTrait Trait;
788
789 // Populate the hash table.
790 for (InterestingIdentifierMap::iterator I = InterestingIdentifiers.begin(),
791 IEnd = InterestingIdentifiers.end();
792 I != IEnd; ++I) {
793 Generator.insert(I->first(), I->second, Trait);
794 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000795
Douglas Gregor5e306b12013-01-23 22:38:11 +0000796 // Create the on-disk hash table in a buffer.
797 SmallString<4096> IdentifierTable;
798 uint32_t BucketOffset;
799 {
Justin Bognere1c147c2014-03-28 22:03:19 +0000800 using namespace llvm::support;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000801 llvm::raw_svector_ostream Out(IdentifierTable);
802 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +0000803 endian::write<uint32_t>(Out, 0, little);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000804 BucketOffset = Generator.Emit(Out, Trait);
805 }
806
807 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +0000808 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor5e306b12013-01-23 22:38:11 +0000809 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_INDEX));
810 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
811 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +0000812 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor5e306b12013-01-23 22:38:11 +0000813
814 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +0000815 uint64_t Record[] = {IDENTIFIER_INDEX, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +0000816 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000817 }
818
Douglas Gregor5e306b12013-01-23 22:38:11 +0000819 Stream.ExitBlock();
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000820 return false;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000821}
822
823GlobalModuleIndex::ErrorCode
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000824GlobalModuleIndex::writeIndex(FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000825 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000826 StringRef Path) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000827 llvm::SmallString<128> IndexPath;
828 IndexPath += Path;
829 llvm::sys::path::append(IndexPath, IndexFileName);
830
831 // Coordinate building the global index file with other processes that might
832 // try to do the same.
833 llvm::LockFileManager Locked(IndexPath);
834 switch (Locked) {
835 case llvm::LockFileManager::LFS_Error:
836 return EC_IOError;
837
838 case llvm::LockFileManager::LFS_Owned:
839 // We're responsible for building the index ourselves. Do so below.
840 break;
841
842 case llvm::LockFileManager::LFS_Shared:
843 // Someone else is responsible for building the index. We don't care
844 // when they finish, so we're done.
845 return EC_Building;
846 }
847
848 // The module index builder.
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000849 GlobalModuleIndexBuilder Builder(FileMgr, PCHContainerRdr);
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000850
Douglas Gregor5e306b12013-01-23 22:38:11 +0000851 // Load each of the module files.
Rafael Espindolac0809172014-06-12 14:02:15 +0000852 std::error_code EC;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000853 for (llvm::sys::fs::directory_iterator D(Path, EC), DEnd;
854 D != DEnd && !EC;
855 D.increment(EC)) {
856 // If this isn't a module file, we don't care.
857 if (llvm::sys::path::extension(D->path()) != ".pcm") {
858 // ... unless it's a .pcm.lock file, which indicates that someone is
859 // in the process of rebuilding a module. They'll rebuild the index
860 // at the end of that translation unit, so we don't have to.
861 if (llvm::sys::path::extension(D->path()) == ".pcm.lock")
862 return EC_Building;
863
864 continue;
865 }
866
867 // If we can't find the module file, skip it.
868 const FileEntry *ModuleFile = FileMgr.getFile(D->path());
869 if (!ModuleFile)
870 continue;
871
872 // Load this module file.
873 if (Builder.loadModuleFile(ModuleFile))
874 return EC_IOError;
875 }
876
877 // The output buffer, into which the global index will be written.
878 SmallVector<char, 16> OutputBuffer;
879 {
880 llvm::BitstreamWriter OutputStream(OutputBuffer);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000881 if (Builder.writeIndex(OutputStream))
882 return EC_IOError;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000883 }
884
885 // Write the global index file to a temporary file.
886 llvm::SmallString<128> IndexTmpPath;
887 int TmpFD;
Rafael Espindola18627112013-07-05 21:13:58 +0000888 if (llvm::sys::fs::createUniqueFile(IndexPath + "-%%%%%%%%", TmpFD,
889 IndexTmpPath))
Douglas Gregor5e306b12013-01-23 22:38:11 +0000890 return EC_IOError;
891
892 // Open the temporary global index file for output.
NAKAMURA Takumie00c9862013-01-24 08:20:11 +0000893 llvm::raw_fd_ostream Out(TmpFD, true);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000894 if (Out.has_error())
895 return EC_IOError;
896
897 // Write the index.
898 Out.write(OutputBuffer.data(), OutputBuffer.size());
899 Out.close();
900 if (Out.has_error())
901 return EC_IOError;
902
903 // Remove the old index file. It isn't relevant any more.
Yaron Keren92e1b622015-03-18 10:17:07 +0000904 llvm::sys::fs::remove(IndexPath);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000905
906 // Rename the newly-written index file to the proper name.
Yaron Keren92e1b622015-03-18 10:17:07 +0000907 if (llvm::sys::fs::rename(IndexTmpPath, IndexPath)) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000908 // Rename failed; just remove the
Yaron Keren92e1b622015-03-18 10:17:07 +0000909 llvm::sys::fs::remove(IndexTmpPath);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000910 return EC_IOError;
911 }
912
913 // We're done.
914 return EC_None;
915}
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000916
917namespace {
918 class GlobalIndexIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000919 /// The current position within the identifier lookup table.
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000920 IdentifierIndexTable::key_iterator Current;
921
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000922 /// The end position within the identifier lookup table.
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000923 IdentifierIndexTable::key_iterator End;
924
925 public:
926 explicit GlobalIndexIdentifierIterator(IdentifierIndexTable &Idx) {
927 Current = Idx.key_begin();
928 End = Idx.key_end();
929 }
930
Craig Topper3e89dfe2014-03-13 02:13:41 +0000931 StringRef Next() override {
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000932 if (Current == End)
933 return StringRef();
934
935 StringRef Result = *Current;
936 ++Current;
937 return Result;
938 }
939 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000940}
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000941
942IdentifierIterator *GlobalModuleIndex::createIdentifierIterator() const {
943 IdentifierIndexTable &Table =
944 *static_cast<IdentifierIndexTable *>(IdentifierIndex);
945 return new GlobalIndexIdentifierIterator(Table);
946}