CacheTokens.cpp 21 KB

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