CacheTokens.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. //===--- CacheTokens.cpp - Caching of lexer tokens for PTH support --------===//
  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 provides a possible implementation of PTH support for Clang that is
  11. // based on caching lexed tokens and identifiers.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Frontend/Utils.h"
  15. #include "clang/Basic/Diagnostic.h"
  16. #include "clang/Basic/FileManager.h"
  17. #include "clang/Basic/FileSystemStatCache.h"
  18. #include "clang/Basic/IdentifierTable.h"
  19. #include "clang/Basic/SourceManager.h"
  20. #include "clang/Lex/Lexer.h"
  21. #include "clang/Lex/Preprocessor.h"
  22. #include "llvm/ADT/StringExtras.h"
  23. #include "llvm/ADT/StringMap.h"
  24. #include "llvm/Support/EndianStream.h"
  25. #include "llvm/Support/FileSystem.h"
  26. #include "llvm/Support/MemoryBuffer.h"
  27. #include "llvm/Support/OnDiskHashTable.h"
  28. #include "llvm/Support/Path.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. // FIXME: put this somewhere else?
  31. #ifndef S_ISDIR
  32. #define S_ISDIR(x) (((x)&_S_IFDIR)!=0)
  33. #endif
  34. using namespace clang;
  35. //===----------------------------------------------------------------------===//
  36. // PTH-specific stuff.
  37. //===----------------------------------------------------------------------===//
  38. typedef uint32_t Offset;
  39. namespace {
  40. class PTHEntry {
  41. Offset TokenData, PPCondData;
  42. public:
  43. PTHEntry() {}
  44. PTHEntry(Offset td, Offset ppcd)
  45. : TokenData(td), PPCondData(ppcd) {}
  46. Offset getTokenOffset() const { return TokenData; }
  47. Offset getPPCondTableOffset() const { return PPCondData; }
  48. };
  49. class PTHEntryKeyVariant {
  50. union { const FileEntry* FE; const char* Path; };
  51. enum { IsFE = 0x1, IsDE = 0x2, IsNoExist = 0x0 } Kind;
  52. FileData *Data;
  53. public:
  54. PTHEntryKeyVariant(const FileEntry *fe) : FE(fe), Kind(IsFE), Data(nullptr) {}
  55. PTHEntryKeyVariant(FileData *Data, const char *path)
  56. : Path(path), Kind(IsDE), Data(new FileData(*Data)) {}
  57. explicit PTHEntryKeyVariant(const char *path)
  58. : Path(path), Kind(IsNoExist), Data(nullptr) {}
  59. bool isFile() const { return Kind == IsFE; }
  60. StringRef getString() const {
  61. return Kind == IsFE ? FE->getName() : Path;
  62. }
  63. unsigned getKind() const { return (unsigned) Kind; }
  64. void EmitData(raw_ostream& Out) {
  65. using namespace llvm::support;
  66. endian::Writer<little> LE(Out);
  67. switch (Kind) {
  68. case IsFE: {
  69. // Emit stat information.
  70. llvm::sys::fs::UniqueID UID = FE->getUniqueID();
  71. LE.write<uint64_t>(UID.getFile());
  72. LE.write<uint64_t>(UID.getDevice());
  73. LE.write<uint64_t>(FE->getModificationTime());
  74. LE.write<uint64_t>(FE->getSize());
  75. } break;
  76. case IsDE:
  77. // Emit stat information.
  78. LE.write<uint64_t>(Data->UniqueID.getFile());
  79. LE.write<uint64_t>(Data->UniqueID.getDevice());
  80. LE.write<uint64_t>(Data->ModTime);
  81. LE.write<uint64_t>(Data->Size);
  82. delete Data;
  83. break;
  84. default:
  85. break;
  86. }
  87. }
  88. unsigned getRepresentationLength() const {
  89. return Kind == IsNoExist ? 0 : 4 + 4 + 2 + 8 + 8;
  90. }
  91. };
  92. class FileEntryPTHEntryInfo {
  93. public:
  94. typedef PTHEntryKeyVariant key_type;
  95. typedef key_type key_type_ref;
  96. typedef PTHEntry data_type;
  97. typedef const PTHEntry& data_type_ref;
  98. typedef unsigned hash_value_type;
  99. typedef unsigned offset_type;
  100. static hash_value_type ComputeHash(PTHEntryKeyVariant V) {
  101. return llvm::HashString(V.getString());
  102. }
  103. static std::pair<unsigned,unsigned>
  104. EmitKeyDataLength(raw_ostream& Out, PTHEntryKeyVariant V,
  105. const PTHEntry& E) {
  106. using namespace llvm::support;
  107. endian::Writer<little> LE(Out);
  108. unsigned n = V.getString().size() + 1 + 1;
  109. LE.write<uint16_t>(n);
  110. unsigned m = V.getRepresentationLength() + (V.isFile() ? 4 + 4 : 0);
  111. LE.write<uint8_t>(m);
  112. return std::make_pair(n, m);
  113. }
  114. static void EmitKey(raw_ostream& Out, PTHEntryKeyVariant V, unsigned n){
  115. using namespace llvm::support;
  116. // Emit the entry kind.
  117. endian::Writer<little>(Out).write<uint8_t>((unsigned)V.getKind());
  118. // Emit the string.
  119. Out.write(V.getString().data(), n - 1);
  120. }
  121. static void EmitData(raw_ostream& Out, PTHEntryKeyVariant V,
  122. const PTHEntry& E, unsigned) {
  123. using namespace llvm::support;
  124. endian::Writer<little> LE(Out);
  125. // For file entries emit the offsets into the PTH file for token data
  126. // and the preprocessor blocks table.
  127. if (V.isFile()) {
  128. LE.write<uint32_t>(E.getTokenOffset());
  129. LE.write<uint32_t>(E.getPPCondTableOffset());
  130. }
  131. // Emit any other data associated with the key (i.e., stat information).
  132. V.EmitData(Out);
  133. }
  134. };
  135. class OffsetOpt {
  136. bool valid;
  137. Offset off;
  138. public:
  139. OffsetOpt() : valid(false) {}
  140. bool hasOffset() const { return valid; }
  141. Offset getOffset() const { assert(valid); return off; }
  142. void setOffset(Offset o) { off = o; valid = true; }
  143. };
  144. } // end anonymous namespace
  145. typedef llvm::OnDiskChainedHashTableGenerator<FileEntryPTHEntryInfo> PTHMap;
  146. namespace {
  147. class PTHWriter {
  148. typedef llvm::DenseMap<const IdentifierInfo*,uint32_t> IDMap;
  149. typedef llvm::StringMap<OffsetOpt, llvm::BumpPtrAllocator> CachedStrsTy;
  150. IDMap IM;
  151. llvm::raw_fd_ostream& Out;
  152. Preprocessor& PP;
  153. uint32_t idcount;
  154. PTHMap PM;
  155. CachedStrsTy CachedStrs;
  156. Offset CurStrOffset;
  157. std::vector<llvm::StringMapEntry<OffsetOpt>*> StrEntries;
  158. //// Get the persistent id for the given IdentifierInfo*.
  159. uint32_t ResolveID(const IdentifierInfo* II);
  160. /// Emit a token to the PTH file.
  161. void EmitToken(const Token& T);
  162. void Emit8(uint32_t V) {
  163. using namespace llvm::support;
  164. endian::Writer<little>(Out).write<uint8_t>(V);
  165. }
  166. void Emit16(uint32_t V) {
  167. using namespace llvm::support;
  168. endian::Writer<little>(Out).write<uint16_t>(V);
  169. }
  170. void Emit32(uint32_t V) {
  171. using namespace llvm::support;
  172. endian::Writer<little>(Out).write<uint32_t>(V);
  173. }
  174. void EmitBuf(const char *Ptr, unsigned NumBytes) {
  175. Out.write(Ptr, NumBytes);
  176. }
  177. void EmitString(StringRef V) {
  178. using namespace llvm::support;
  179. endian::Writer<little>(Out).write<uint16_t>(V.size());
  180. EmitBuf(V.data(), V.size());
  181. }
  182. /// EmitIdentifierTable - Emits two tables to the PTH file. The first is
  183. /// a hashtable mapping from identifier strings to persistent IDs.
  184. /// The second is a straight table mapping from persistent IDs to string data
  185. /// (the keys of the first table).
  186. std::pair<Offset, Offset> EmitIdentifierTable();
  187. /// EmitFileTable - Emit a table mapping from file name strings to PTH
  188. /// token data.
  189. Offset EmitFileTable() { return PM.Emit(Out); }
  190. PTHEntry LexTokens(Lexer& L);
  191. Offset EmitCachedSpellings();
  192. public:
  193. PTHWriter(llvm::raw_fd_ostream& out, Preprocessor& pp)
  194. : Out(out), PP(pp), idcount(0), CurStrOffset(0) {}
  195. PTHMap &getPM() { return PM; }
  196. void GeneratePTH(const std::string &MainFile);
  197. };
  198. } // end anonymous namespace
  199. uint32_t PTHWriter::ResolveID(const IdentifierInfo* II) {
  200. // Null IdentifierInfo's map to the persistent ID 0.
  201. if (!II)
  202. return 0;
  203. IDMap::iterator I = IM.find(II);
  204. if (I != IM.end())
  205. return I->second; // We've already added 1.
  206. IM[II] = ++idcount; // Pre-increment since '0' is reserved for NULL.
  207. return idcount;
  208. }
  209. void PTHWriter::EmitToken(const Token& T) {
  210. // Emit the token kind, flags, and length.
  211. Emit32(((uint32_t) T.getKind()) | ((((uint32_t) T.getFlags())) << 8)|
  212. (((uint32_t) T.getLength()) << 16));
  213. if (!T.isLiteral()) {
  214. Emit32(ResolveID(T.getIdentifierInfo()));
  215. } else {
  216. // We cache *un-cleaned* spellings. This gives us 100% fidelity with the
  217. // source code.
  218. StringRef s(T.getLiteralData(), T.getLength());
  219. // Get the string entry.
  220. auto &E = *CachedStrs.insert(std::make_pair(s, OffsetOpt())).first;
  221. // If this is a new string entry, bump the PTH offset.
  222. if (!E.second.hasOffset()) {
  223. E.second.setOffset(CurStrOffset);
  224. StrEntries.push_back(&E);
  225. CurStrOffset += s.size() + 1;
  226. }
  227. // Emit the relative offset into the PTH file for the spelling string.
  228. Emit32(E.second.getOffset());
  229. }
  230. // Emit the offset into the original source file of this token so that we
  231. // can reconstruct its SourceLocation.
  232. Emit32(PP.getSourceManager().getFileOffset(T.getLocation()));
  233. }
  234. PTHEntry PTHWriter::LexTokens(Lexer& L) {
  235. // Pad 0's so that we emit tokens to a 4-byte alignment.
  236. // This speed up reading them back in.
  237. using namespace llvm::support;
  238. endian::Writer<little> LE(Out);
  239. uint32_t TokenOff = Out.tell();
  240. for (uint64_t N = llvm::OffsetToAlignment(TokenOff, 4); N; --N, ++TokenOff)
  241. LE.write<uint8_t>(0);
  242. // Keep track of matching '#if' ... '#endif'.
  243. typedef std::vector<std::pair<Offset, unsigned> > PPCondTable;
  244. PPCondTable PPCond;
  245. std::vector<unsigned> PPStartCond;
  246. bool ParsingPreprocessorDirective = false;
  247. Token Tok;
  248. do {
  249. L.LexFromRawLexer(Tok);
  250. NextToken:
  251. if ((Tok.isAtStartOfLine() || Tok.is(tok::eof)) &&
  252. ParsingPreprocessorDirective) {
  253. // Insert an eod token into the token cache. It has the same
  254. // position as the next token that is not on the same line as the
  255. // preprocessor directive. Observe that we continue processing
  256. // 'Tok' when we exit this branch.
  257. Token Tmp = Tok;
  258. Tmp.setKind(tok::eod);
  259. Tmp.clearFlag(Token::StartOfLine);
  260. Tmp.setIdentifierInfo(nullptr);
  261. EmitToken(Tmp);
  262. ParsingPreprocessorDirective = false;
  263. }
  264. if (Tok.is(tok::raw_identifier)) {
  265. PP.LookUpIdentifierInfo(Tok);
  266. EmitToken(Tok);
  267. continue;
  268. }
  269. if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
  270. // Special processing for #include. Store the '#' token and lex
  271. // the next token.
  272. assert(!ParsingPreprocessorDirective);
  273. Offset HashOff = (Offset) Out.tell();
  274. // Get the next token.
  275. Token NextTok;
  276. L.LexFromRawLexer(NextTok);
  277. // If we see the start of line, then we had a null directive "#". In
  278. // this case, discard both tokens.
  279. if (NextTok.isAtStartOfLine())
  280. goto NextToken;
  281. // The token is the start of a directive. Emit it.
  282. EmitToken(Tok);
  283. Tok = NextTok;
  284. // Did we see 'include'/'import'/'include_next'?
  285. if (Tok.isNot(tok::raw_identifier)) {
  286. EmitToken(Tok);
  287. continue;
  288. }
  289. IdentifierInfo* II = PP.LookUpIdentifierInfo(Tok);
  290. tok::PPKeywordKind K = II->getPPKeywordID();
  291. ParsingPreprocessorDirective = true;
  292. switch (K) {
  293. case tok::pp_not_keyword:
  294. // Invalid directives "#foo" can occur in #if 0 blocks etc, just pass
  295. // them through.
  296. default:
  297. break;
  298. case tok::pp_include:
  299. case tok::pp_import:
  300. case tok::pp_include_next: {
  301. // Save the 'include' token.
  302. EmitToken(Tok);
  303. // Lex the next token as an include string.
  304. L.setParsingPreprocessorDirective(true);
  305. L.LexIncludeFilename(Tok);
  306. L.setParsingPreprocessorDirective(false);
  307. assert(!Tok.isAtStartOfLine());
  308. if (Tok.is(tok::raw_identifier))
  309. PP.LookUpIdentifierInfo(Tok);
  310. break;
  311. }
  312. case tok::pp_if:
  313. case tok::pp_ifdef:
  314. case tok::pp_ifndef: {
  315. // Add an entry for '#if' and friends. We initially set the target
  316. // index to 0. This will get backpatched when we hit #endif.
  317. PPStartCond.push_back(PPCond.size());
  318. PPCond.push_back(std::make_pair(HashOff, 0U));
  319. break;
  320. }
  321. case tok::pp_endif: {
  322. // Add an entry for '#endif'. We set the target table index to itself.
  323. // This will later be set to zero when emitting to the PTH file. We
  324. // use 0 for uninitialized indices because that is easier to debug.
  325. unsigned index = PPCond.size();
  326. // Backpatch the opening '#if' entry.
  327. assert(!PPStartCond.empty());
  328. assert(PPCond.size() > PPStartCond.back());
  329. assert(PPCond[PPStartCond.back()].second == 0);
  330. PPCond[PPStartCond.back()].second = index;
  331. PPStartCond.pop_back();
  332. // Add the new entry to PPCond.
  333. PPCond.push_back(std::make_pair(HashOff, index));
  334. EmitToken(Tok);
  335. // Some files have gibberish on the same line as '#endif'.
  336. // Discard these tokens.
  337. do
  338. L.LexFromRawLexer(Tok);
  339. while (Tok.isNot(tok::eof) && !Tok.isAtStartOfLine());
  340. // We have the next token in hand.
  341. // Don't immediately lex the next one.
  342. goto NextToken;
  343. }
  344. case tok::pp_elif:
  345. case tok::pp_else: {
  346. // Add an entry for #elif or #else.
  347. // This serves as both a closing and opening of a conditional block.
  348. // This means that its entry will get backpatched later.
  349. unsigned index = PPCond.size();
  350. // Backpatch the previous '#if' entry.
  351. assert(!PPStartCond.empty());
  352. assert(PPCond.size() > PPStartCond.back());
  353. assert(PPCond[PPStartCond.back()].second == 0);
  354. PPCond[PPStartCond.back()].second = index;
  355. PPStartCond.pop_back();
  356. // Now add '#elif' as a new block opening.
  357. PPCond.push_back(std::make_pair(HashOff, 0U));
  358. PPStartCond.push_back(index);
  359. break;
  360. }
  361. }
  362. }
  363. EmitToken(Tok);
  364. }
  365. while (Tok.isNot(tok::eof));
  366. assert(PPStartCond.empty() && "Error: imblanced preprocessor conditionals.");
  367. // Next write out PPCond.
  368. Offset PPCondOff = (Offset) Out.tell();
  369. // Write out the size of PPCond so that clients can identifer empty tables.
  370. Emit32(PPCond.size());
  371. for (unsigned i = 0, e = PPCond.size(); i!=e; ++i) {
  372. Emit32(PPCond[i].first - TokenOff);
  373. uint32_t x = PPCond[i].second;
  374. assert(x != 0 && "PPCond entry not backpatched.");
  375. // Emit zero for #endifs. This allows us to do checking when
  376. // we read the PTH file back in.
  377. Emit32(x == i ? 0 : x);
  378. }
  379. return PTHEntry(TokenOff, PPCondOff);
  380. }
  381. Offset PTHWriter::EmitCachedSpellings() {
  382. // Write each cached strings to the PTH file.
  383. Offset SpellingsOff = Out.tell();
  384. for (std::vector<llvm::StringMapEntry<OffsetOpt>*>::iterator
  385. I = StrEntries.begin(), E = StrEntries.end(); I!=E; ++I)
  386. EmitBuf((*I)->getKeyData(), (*I)->getKeyLength()+1 /*nul included*/);
  387. return SpellingsOff;
  388. }
  389. void PTHWriter::GeneratePTH(const std::string &MainFile) {
  390. // Generate the prologue.
  391. Out << "cfe-pth" << '\0';
  392. Emit32(PTHManager::Version);
  393. // Leave 4 words for the prologue.
  394. Offset PrologueOffset = Out.tell();
  395. for (unsigned i = 0; i < 4; ++i)
  396. Emit32(0);
  397. // Write the name of the MainFile.
  398. if (!MainFile.empty()) {
  399. EmitString(MainFile);
  400. } else {
  401. // String with 0 bytes.
  402. Emit16(0);
  403. }
  404. Emit8(0);
  405. // Iterate over all the files in SourceManager. Create a lexer
  406. // for each file and cache the tokens.
  407. SourceManager &SM = PP.getSourceManager();
  408. const LangOptions &LOpts = PP.getLangOpts();
  409. for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
  410. E = SM.fileinfo_end(); I != E; ++I) {
  411. const SrcMgr::ContentCache &C = *I->second;
  412. const FileEntry *FE = C.OrigEntry;
  413. // FIXME: Handle files with non-absolute paths.
  414. if (llvm::sys::path::is_relative(FE->getName()))
  415. continue;
  416. const llvm::MemoryBuffer *B = C.getBuffer(PP.getDiagnostics(), SM);
  417. if (!B) continue;
  418. FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
  419. const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
  420. Lexer L(FID, FromFile, SM, LOpts);
  421. PM.insert(FE, LexTokens(L));
  422. }
  423. // Write out the identifier table.
  424. const std::pair<Offset,Offset> &IdTableOff = EmitIdentifierTable();
  425. // Write out the cached strings table.
  426. Offset SpellingOff = EmitCachedSpellings();
  427. // Write out the file table.
  428. Offset FileTableOff = EmitFileTable();
  429. // Finally, write the prologue.
  430. Out.seek(PrologueOffset);
  431. Emit32(IdTableOff.first);
  432. Emit32(IdTableOff.second);
  433. Emit32(FileTableOff);
  434. Emit32(SpellingOff);
  435. }
  436. namespace {
  437. /// StatListener - A simple "interpose" object used to monitor stat calls
  438. /// invoked by FileManager while processing the original sources used
  439. /// as input to PTH generation. StatListener populates the PTHWriter's
  440. /// file map with stat information for directories as well as negative stats.
  441. /// Stat information for files are populated elsewhere.
  442. class StatListener : public FileSystemStatCache {
  443. PTHMap &PM;
  444. public:
  445. StatListener(PTHMap &pm) : PM(pm) {}
  446. ~StatListener() override {}
  447. LookupResult getStat(const char *Path, FileData &Data, bool isFile,
  448. std::unique_ptr<vfs::File> *F,
  449. vfs::FileSystem &FS) override {
  450. LookupResult Result = statChained(Path, Data, isFile, F, FS);
  451. if (Result == CacheMissing) // Failed 'stat'.
  452. PM.insert(PTHEntryKeyVariant(Path), PTHEntry());
  453. else if (Data.IsDirectory) {
  454. // Only cache directories with absolute paths.
  455. if (llvm::sys::path::is_relative(Path))
  456. return Result;
  457. PM.insert(PTHEntryKeyVariant(&Data, Path), PTHEntry());
  458. }
  459. return Result;
  460. }
  461. };
  462. } // end anonymous namespace
  463. void clang::CacheTokens(Preprocessor &PP, llvm::raw_fd_ostream* OS) {
  464. // Get the name of the main file.
  465. const SourceManager &SrcMgr = PP.getSourceManager();
  466. const FileEntry *MainFile = SrcMgr.getFileEntryForID(SrcMgr.getMainFileID());
  467. SmallString<128> MainFilePath(MainFile->getName());
  468. llvm::sys::fs::make_absolute(MainFilePath);
  469. // Create the PTHWriter.
  470. PTHWriter PW(*OS, PP);
  471. // Install the 'stat' system call listener in the FileManager.
  472. auto StatCacheOwner = llvm::make_unique<StatListener>(PW.getPM());
  473. StatListener *StatCache = StatCacheOwner.get();
  474. PP.getFileManager().addStatCache(std::move(StatCacheOwner),
  475. /*AtBeginning=*/true);
  476. // Lex through the entire file. This will populate SourceManager with
  477. // all of the header information.
  478. Token Tok;
  479. PP.EnterMainSourceFile();
  480. do { PP.Lex(Tok); } while (Tok.isNot(tok::eof));
  481. // Generate the PTH file.
  482. PP.getFileManager().removeStatCache(StatCache);
  483. PW.GeneratePTH(MainFilePath.str());
  484. }
  485. //===----------------------------------------------------------------------===//
  486. namespace {
  487. class PTHIdKey {
  488. public:
  489. const IdentifierInfo* II;
  490. uint32_t FileOffset;
  491. };
  492. class PTHIdentifierTableTrait {
  493. public:
  494. typedef PTHIdKey* key_type;
  495. typedef key_type key_type_ref;
  496. typedef uint32_t data_type;
  497. typedef data_type data_type_ref;
  498. typedef unsigned hash_value_type;
  499. typedef unsigned offset_type;
  500. static hash_value_type ComputeHash(PTHIdKey* key) {
  501. return llvm::HashString(key->II->getName());
  502. }
  503. static std::pair<unsigned,unsigned>
  504. EmitKeyDataLength(raw_ostream& Out, const PTHIdKey* key, uint32_t) {
  505. using namespace llvm::support;
  506. unsigned n = key->II->getLength() + 1;
  507. endian::Writer<little>(Out).write<uint16_t>(n);
  508. return std::make_pair(n, sizeof(uint32_t));
  509. }
  510. static void EmitKey(raw_ostream& Out, PTHIdKey* key, unsigned n) {
  511. // Record the location of the key data. This is used when generating
  512. // the mapping from persistent IDs to strings.
  513. key->FileOffset = Out.tell();
  514. Out.write(key->II->getNameStart(), n);
  515. }
  516. static void EmitData(raw_ostream& Out, PTHIdKey*, uint32_t pID,
  517. unsigned) {
  518. using namespace llvm::support;
  519. endian::Writer<little>(Out).write<uint32_t>(pID);
  520. }
  521. };
  522. } // end anonymous namespace
  523. /// EmitIdentifierTable - Emits two tables to the PTH file. The first is
  524. /// a hashtable mapping from identifier strings to persistent IDs. The second
  525. /// is a straight table mapping from persistent IDs to string data (the
  526. /// keys of the first table).
  527. ///
  528. std::pair<Offset,Offset> PTHWriter::EmitIdentifierTable() {
  529. // Build two maps:
  530. // (1) an inverse map from persistent IDs -> (IdentifierInfo*,Offset)
  531. // (2) a map from (IdentifierInfo*, Offset)* -> persistent IDs
  532. // Note that we use 'calloc', so all the bytes are 0.
  533. PTHIdKey *IIDMap = (PTHIdKey*)calloc(idcount, sizeof(PTHIdKey));
  534. // Create the hashtable.
  535. llvm::OnDiskChainedHashTableGenerator<PTHIdentifierTableTrait> IIOffMap;
  536. // Generate mapping from persistent IDs -> IdentifierInfo*.
  537. for (IDMap::iterator I = IM.begin(), E = IM.end(); I != E; ++I) {
  538. // Decrement by 1 because we are using a vector for the lookup and
  539. // 0 is reserved for NULL.
  540. assert(I->second > 0);
  541. assert(I->second-1 < idcount);
  542. unsigned idx = I->second-1;
  543. // Store the mapping from persistent ID to IdentifierInfo*
  544. IIDMap[idx].II = I->first;
  545. // Store the reverse mapping in a hashtable.
  546. IIOffMap.insert(&IIDMap[idx], I->second);
  547. }
  548. // Write out the inverse map first. This causes the PCIDKey entries to
  549. // record PTH file offsets for the string data. This is used to write
  550. // the second table.
  551. Offset StringTableOffset = IIOffMap.Emit(Out);
  552. // Now emit the table mapping from persistent IDs to PTH file offsets.
  553. Offset IDOff = Out.tell();
  554. Emit32(idcount); // Emit the number of identifiers.
  555. for (unsigned i = 0 ; i < idcount; ++i)
  556. Emit32(IIDMap[i].FileOffset);
  557. // Finally, release the inverse map.
  558. free(IIDMap);
  559. return std::make_pair(IDOff, StringTableOffset);
  560. }