CacheTokens.cpp 20 KB

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