CacheTokens.cpp 21 KB

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