CacheTokens.cpp 22 KB

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