PTHLexer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. //===- PTHLexer.cpp - Lex from a token stream -----------------------------===//
  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 file implements the PTHLexer interface.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Lex/PTHLexer.h"
  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/Basic/TokenKinds.h"
  20. #include "clang/Lex/LexDiagnostic.h"
  21. #include "clang/Lex/PTHManager.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "clang/Lex/Token.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/Support/DJB.h"
  27. #include "llvm/Support/Endian.h"
  28. #include "llvm/Support/ErrorOr.h"
  29. #include "llvm/Support/FileSystem.h"
  30. #include "llvm/Support/MemoryBuffer.h"
  31. #include "llvm/Support/OnDiskHashTable.h"
  32. #include <cassert>
  33. #include <cstdint>
  34. #include <cstdlib>
  35. #include <cstring>
  36. #include <ctime>
  37. #include <memory>
  38. #include <utility>
  39. using namespace clang;
  40. static const unsigned StoredTokenSize = 1 + 1 + 2 + 4 + 4;
  41. //===----------------------------------------------------------------------===//
  42. // PTHLexer methods.
  43. //===----------------------------------------------------------------------===//
  44. PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D,
  45. const unsigned char *ppcond, PTHManager &PM)
  46. : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), PPCond(ppcond),
  47. CurPPCondPtr(ppcond), PTHMgr(PM) {
  48. FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID);
  49. }
  50. bool PTHLexer::Lex(Token& Tok) {
  51. //===--------------------------------------==//
  52. // Read the raw token data.
  53. //===--------------------------------------==//
  54. using namespace llvm::support;
  55. // Shadow CurPtr into an automatic variable.
  56. const unsigned char *CurPtrShadow = CurPtr;
  57. // Read in the data for the token.
  58. unsigned Word0 = endian::readNext<uint32_t, little, aligned>(CurPtrShadow);
  59. uint32_t IdentifierID =
  60. endian::readNext<uint32_t, little, aligned>(CurPtrShadow);
  61. uint32_t FileOffset =
  62. endian::readNext<uint32_t, little, aligned>(CurPtrShadow);
  63. tok::TokenKind TKind = (tok::TokenKind) (Word0 & 0xFF);
  64. Token::TokenFlags TFlags = (Token::TokenFlags) ((Word0 >> 8) & 0xFF);
  65. uint32_t Len = Word0 >> 16;
  66. CurPtr = CurPtrShadow;
  67. //===--------------------------------------==//
  68. // Construct the token itself.
  69. //===--------------------------------------==//
  70. Tok.startToken();
  71. Tok.setKind(TKind);
  72. Tok.setFlag(TFlags);
  73. assert(!LexingRawMode);
  74. Tok.setLocation(FileStartLoc.getLocWithOffset(FileOffset));
  75. Tok.setLength(Len);
  76. // Handle identifiers.
  77. if (Tok.isLiteral()) {
  78. Tok.setLiteralData((const char*) (PTHMgr.SpellingBase + IdentifierID));
  79. }
  80. else if (IdentifierID) {
  81. MIOpt.ReadToken();
  82. IdentifierInfo *II = PTHMgr.GetIdentifierInfo(IdentifierID-1);
  83. Tok.setIdentifierInfo(II);
  84. // Change the kind of this identifier to the appropriate token kind, e.g.
  85. // turning "for" into a keyword.
  86. Tok.setKind(II->getTokenID());
  87. if (II->isHandleIdentifierCase())
  88. return PP->HandleIdentifier(Tok);
  89. return true;
  90. }
  91. //===--------------------------------------==//
  92. // Process the token.
  93. //===--------------------------------------==//
  94. if (TKind == tok::eof) {
  95. // Save the end-of-file token.
  96. EofToken = Tok;
  97. assert(!ParsingPreprocessorDirective);
  98. assert(!LexingRawMode);
  99. return LexEndOfFile(Tok);
  100. }
  101. if (TKind == tok::hash && Tok.isAtStartOfLine()) {
  102. LastHashTokPtr = CurPtr - StoredTokenSize;
  103. assert(!LexingRawMode);
  104. PP->HandleDirective(Tok);
  105. return false;
  106. }
  107. if (TKind == tok::eod) {
  108. assert(ParsingPreprocessorDirective);
  109. ParsingPreprocessorDirective = false;
  110. return true;
  111. }
  112. MIOpt.ReadToken();
  113. return true;
  114. }
  115. bool PTHLexer::LexEndOfFile(Token &Result) {
  116. // If we hit the end of the file while parsing a preprocessor directive,
  117. // end the preprocessor directive first. The next token returned will
  118. // then be the end of file.
  119. if (ParsingPreprocessorDirective) {
  120. ParsingPreprocessorDirective = false; // Done parsing the "line".
  121. return true; // Have a token.
  122. }
  123. assert(!LexingRawMode);
  124. // If we are in a #if directive, emit an error.
  125. while (!ConditionalStack.empty()) {
  126. if (PP->getCodeCompletionFileLoc() != FileStartLoc)
  127. PP->Diag(ConditionalStack.back().IfLoc,
  128. diag::err_pp_unterminated_conditional);
  129. ConditionalStack.pop_back();
  130. }
  131. // Finally, let the preprocessor handle this.
  132. return PP->HandleEndOfFile(Result);
  133. }
  134. // FIXME: We can just grab the last token instead of storing a copy
  135. // into EofToken.
  136. void PTHLexer::getEOF(Token& Tok) {
  137. assert(EofToken.is(tok::eof));
  138. Tok = EofToken;
  139. }
  140. void PTHLexer::DiscardToEndOfLine() {
  141. assert(ParsingPreprocessorDirective && ParsingFilename == false &&
  142. "Must be in a preprocessing directive!");
  143. // We assume that if the preprocessor wishes to discard to the end of
  144. // the line that it also means to end the current preprocessor directive.
  145. ParsingPreprocessorDirective = false;
  146. // Skip tokens by only peeking at their token kind and the flags.
  147. // We don't need to actually reconstruct full tokens from the token buffer.
  148. // This saves some copies and it also reduces IdentifierInfo* lookup.
  149. const unsigned char* p = CurPtr;
  150. while (true) {
  151. // Read the token kind. Are we at the end of the file?
  152. tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
  153. if (x == tok::eof) break;
  154. // Read the token flags. Are we at the start of the next line?
  155. Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
  156. if (y & Token::StartOfLine) break;
  157. // Skip to the next token.
  158. p += StoredTokenSize;
  159. }
  160. CurPtr = p;
  161. }
  162. /// SkipBlock - Used by Preprocessor to skip the current conditional block.
  163. bool PTHLexer::SkipBlock() {
  164. using namespace llvm::support;
  165. assert(CurPPCondPtr && "No cached PP conditional information.");
  166. assert(LastHashTokPtr && "No known '#' token.");
  167. const unsigned char *HashEntryI = nullptr;
  168. uint32_t TableIdx;
  169. do {
  170. // Read the token offset from the side-table.
  171. uint32_t Offset = endian::readNext<uint32_t, little, aligned>(CurPPCondPtr);
  172. // Read the target table index from the side-table.
  173. TableIdx = endian::readNext<uint32_t, little, aligned>(CurPPCondPtr);
  174. // Compute the actual memory address of the '#' token data for this entry.
  175. HashEntryI = TokBuf + Offset;
  176. // Optimization: "Sibling jumping". #if...#else...#endif blocks can
  177. // contain nested blocks. In the side-table we can jump over these
  178. // nested blocks instead of doing a linear search if the next "sibling"
  179. // entry is not at a location greater than LastHashTokPtr.
  180. if (HashEntryI < LastHashTokPtr && TableIdx) {
  181. // In the side-table we are still at an entry for a '#' token that
  182. // is earlier than the last one we saw. Check if the location we would
  183. // stride gets us closer.
  184. const unsigned char* NextPPCondPtr =
  185. PPCond + TableIdx*(sizeof(uint32_t)*2);
  186. assert(NextPPCondPtr >= CurPPCondPtr);
  187. // Read where we should jump to.
  188. const unsigned char *HashEntryJ =
  189. TokBuf + endian::readNext<uint32_t, little, aligned>(NextPPCondPtr);
  190. if (HashEntryJ <= LastHashTokPtr) {
  191. // Jump directly to the next entry in the side table.
  192. HashEntryI = HashEntryJ;
  193. TableIdx = endian::readNext<uint32_t, little, aligned>(NextPPCondPtr);
  194. CurPPCondPtr = NextPPCondPtr;
  195. }
  196. }
  197. }
  198. while (HashEntryI < LastHashTokPtr);
  199. assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
  200. assert(TableIdx && "No jumping from #endifs.");
  201. // Update our side-table iterator.
  202. const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
  203. assert(NextPPCondPtr >= CurPPCondPtr);
  204. CurPPCondPtr = NextPPCondPtr;
  205. // Read where we should jump to.
  206. HashEntryI =
  207. TokBuf + endian::readNext<uint32_t, little, aligned>(NextPPCondPtr);
  208. uint32_t NextIdx = endian::readNext<uint32_t, little, aligned>(NextPPCondPtr);
  209. // By construction NextIdx will be zero if this is a #endif. This is useful
  210. // to know to obviate lexing another token.
  211. bool isEndif = NextIdx == 0;
  212. // This case can occur when we see something like this:
  213. //
  214. // #if ...
  215. // /* a comment or nothing */
  216. // #elif
  217. //
  218. // If we are skipping the first #if block it will be the case that CurPtr
  219. // already points 'elif'. Just return.
  220. if (CurPtr > HashEntryI) {
  221. assert(CurPtr == HashEntryI + StoredTokenSize);
  222. // Did we reach a #endif? If so, go ahead and consume that token as well.
  223. if (isEndif)
  224. CurPtr += StoredTokenSize * 2;
  225. else
  226. LastHashTokPtr = HashEntryI;
  227. return isEndif;
  228. }
  229. // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
  230. CurPtr = HashEntryI;
  231. // Update the location of the last observed '#'. This is useful if we
  232. // are skipping multiple blocks.
  233. LastHashTokPtr = CurPtr;
  234. // Skip the '#' token.
  235. assert(((tok::TokenKind)*CurPtr) == tok::hash);
  236. CurPtr += StoredTokenSize;
  237. // Did we reach a #endif? If so, go ahead and consume that token as well.
  238. if (isEndif) {
  239. CurPtr += StoredTokenSize * 2;
  240. }
  241. return isEndif;
  242. }
  243. SourceLocation PTHLexer::getSourceLocation() {
  244. // getSourceLocation is not on the hot path. It is used to get the location
  245. // of the next token when transitioning back to this lexer when done
  246. // handling a #included file. Just read the necessary data from the token
  247. // data buffer to construct the SourceLocation object.
  248. // NOTE: This is a virtual function; hence it is defined out-of-line.
  249. using namespace llvm::support;
  250. const unsigned char *OffsetPtr = CurPtr + (StoredTokenSize - 4);
  251. uint32_t Offset = endian::readNext<uint32_t, little, aligned>(OffsetPtr);
  252. return FileStartLoc.getLocWithOffset(Offset);
  253. }
  254. //===----------------------------------------------------------------------===//
  255. // PTH file lookup: map from strings to file data.
  256. //===----------------------------------------------------------------------===//
  257. /// PTHFileLookup - This internal data structure is used by the PTHManager
  258. /// to map from FileEntry objects managed by FileManager to offsets within
  259. /// the PTH file.
  260. namespace {
  261. class PTHFileData {
  262. const uint32_t TokenOff;
  263. const uint32_t PPCondOff;
  264. public:
  265. PTHFileData(uint32_t tokenOff, uint32_t ppCondOff)
  266. : TokenOff(tokenOff), PPCondOff(ppCondOff) {}
  267. uint32_t getTokenOffset() const { return TokenOff; }
  268. uint32_t getPPCondOffset() const { return PPCondOff; }
  269. };
  270. class PTHFileLookupCommonTrait {
  271. public:
  272. using internal_key_type = std::pair<unsigned char, StringRef>;
  273. using hash_value_type = unsigned;
  274. using offset_type = unsigned;
  275. static hash_value_type ComputeHash(internal_key_type x) {
  276. return llvm::djbHash(x.second);
  277. }
  278. static std::pair<unsigned, unsigned>
  279. ReadKeyDataLength(const unsigned char*& d) {
  280. using namespace llvm::support;
  281. unsigned keyLen =
  282. (unsigned)endian::readNext<uint16_t, little, unaligned>(d);
  283. unsigned dataLen = (unsigned) *(d++);
  284. return std::make_pair(keyLen, dataLen);
  285. }
  286. static internal_key_type ReadKey(const unsigned char* d, unsigned) {
  287. unsigned char k = *(d++); // Read the entry kind.
  288. return std::make_pair(k, (const char*) d);
  289. }
  290. };
  291. } // namespace
  292. class PTHManager::PTHFileLookupTrait : public PTHFileLookupCommonTrait {
  293. public:
  294. using external_key_type = const FileEntry *;
  295. using data_type = PTHFileData;
  296. static internal_key_type GetInternalKey(const FileEntry* FE) {
  297. return std::make_pair((unsigned char) 0x1, FE->getName());
  298. }
  299. static bool EqualKey(internal_key_type a, internal_key_type b) {
  300. return a.first == b.first && a.second == b.second;
  301. }
  302. static PTHFileData ReadData(const internal_key_type& k,
  303. const unsigned char* d, unsigned) {
  304. using namespace llvm::support;
  305. assert(k.first == 0x1 && "Only file lookups can match!");
  306. uint32_t x = endian::readNext<uint32_t, little, unaligned>(d);
  307. uint32_t y = endian::readNext<uint32_t, little, unaligned>(d);
  308. return PTHFileData(x, y);
  309. }
  310. };
  311. class PTHManager::PTHStringLookupTrait {
  312. public:
  313. using data_type = uint32_t;
  314. using external_key_type = const std::pair<const char *, unsigned>;
  315. using internal_key_type = external_key_type;
  316. using hash_value_type = uint32_t;
  317. using offset_type = unsigned;
  318. static bool EqualKey(const internal_key_type& a,
  319. const internal_key_type& b) {
  320. return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
  321. : false;
  322. }
  323. static hash_value_type ComputeHash(const internal_key_type& a) {
  324. return llvm::djbHash(StringRef(a.first, a.second));
  325. }
  326. // This hopefully will just get inlined and removed by the optimizer.
  327. static const internal_key_type&
  328. GetInternalKey(const external_key_type& x) { return x; }
  329. static std::pair<unsigned, unsigned>
  330. ReadKeyDataLength(const unsigned char*& d) {
  331. using namespace llvm::support;
  332. return std::make_pair(
  333. (unsigned)endian::readNext<uint16_t, little, unaligned>(d),
  334. sizeof(uint32_t));
  335. }
  336. static std::pair<const char*, unsigned>
  337. ReadKey(const unsigned char* d, unsigned n) {
  338. assert(n >= 2 && d[n-1] == '\0');
  339. return std::make_pair((const char*) d, n-1);
  340. }
  341. static uint32_t ReadData(const internal_key_type& k, const unsigned char* d,
  342. unsigned) {
  343. using namespace llvm::support;
  344. return endian::readNext<uint32_t, little, unaligned>(d);
  345. }
  346. };
  347. //===----------------------------------------------------------------------===//
  348. // PTHManager methods.
  349. //===----------------------------------------------------------------------===//
  350. PTHManager::PTHManager(
  351. std::unique_ptr<const llvm::MemoryBuffer> buf,
  352. std::unique_ptr<PTHFileLookup> fileLookup, const unsigned char *idDataTable,
  353. std::unique_ptr<IdentifierInfo *[], llvm::FreeDeleter> perIDCache,
  354. std::unique_ptr<PTHStringIdLookup> stringIdLookup, unsigned numIds,
  355. const unsigned char *spellingBase, const char *originalSourceFile)
  356. : Buf(std::move(buf)), PerIDCache(std::move(perIDCache)),
  357. FileLookup(std::move(fileLookup)), IdDataTable(idDataTable),
  358. StringIdLookup(std::move(stringIdLookup)), NumIds(numIds),
  359. SpellingBase(spellingBase), OriginalSourceFile(originalSourceFile) {}
  360. PTHManager::~PTHManager() = default;
  361. static void InvalidPTH(DiagnosticsEngine &Diags, const char *Msg) {
  362. Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0")) << Msg;
  363. }
  364. PTHManager *PTHManager::Create(StringRef file, DiagnosticsEngine &Diags) {
  365. // Memory map the PTH file.
  366. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileOrErr =
  367. llvm::MemoryBuffer::getFile(file);
  368. if (!FileOrErr) {
  369. // FIXME: Add ec.message() to this diag.
  370. Diags.Report(diag::err_invalid_pth_file) << file;
  371. return nullptr;
  372. }
  373. std::unique_ptr<llvm::MemoryBuffer> File = std::move(FileOrErr.get());
  374. using namespace llvm::support;
  375. // Get the buffer ranges and check if there are at least three 32-bit
  376. // words at the end of the file.
  377. const unsigned char *BufBeg = (const unsigned char*)File->getBufferStart();
  378. const unsigned char *BufEnd = (const unsigned char*)File->getBufferEnd();
  379. // Check the prologue of the file.
  380. if ((BufEnd - BufBeg) < (signed)(sizeof("cfe-pth") + 4 + 4) ||
  381. memcmp(BufBeg, "cfe-pth", sizeof("cfe-pth")) != 0) {
  382. Diags.Report(diag::err_invalid_pth_file) << file;
  383. return nullptr;
  384. }
  385. // Read the PTH version.
  386. const unsigned char *p = BufBeg + (sizeof("cfe-pth"));
  387. unsigned Version = endian::readNext<uint32_t, little, aligned>(p);
  388. if (Version < PTHManager::Version) {
  389. InvalidPTH(Diags,
  390. Version < PTHManager::Version
  391. ? "PTH file uses an older PTH format that is no longer supported"
  392. : "PTH file uses a newer PTH format that cannot be read");
  393. return nullptr;
  394. }
  395. // Compute the address of the index table at the end of the PTH file.
  396. const unsigned char *PrologueOffset = p;
  397. if (PrologueOffset >= BufEnd) {
  398. Diags.Report(diag::err_invalid_pth_file) << file;
  399. return nullptr;
  400. }
  401. // Construct the file lookup table. This will be used for mapping from
  402. // FileEntry*'s to cached tokens.
  403. const unsigned char* FileTableOffset = PrologueOffset + sizeof(uint32_t)*2;
  404. const unsigned char *FileTable =
  405. BufBeg + endian::readNext<uint32_t, little, aligned>(FileTableOffset);
  406. if (!(FileTable > BufBeg && FileTable < BufEnd)) {
  407. Diags.Report(diag::err_invalid_pth_file) << file;
  408. return nullptr; // FIXME: Proper error diagnostic?
  409. }
  410. std::unique_ptr<PTHFileLookup> FL(PTHFileLookup::Create(FileTable, BufBeg));
  411. // Warn if the PTH file is empty. We still want to create a PTHManager
  412. // as the PTH could be used with -include-pth.
  413. if (FL->isEmpty())
  414. InvalidPTH(Diags, "PTH file contains no cached source data");
  415. // Get the location of the table mapping from persistent ids to the
  416. // data needed to reconstruct identifiers.
  417. const unsigned char* IDTableOffset = PrologueOffset + sizeof(uint32_t)*0;
  418. const unsigned char *IData =
  419. BufBeg + endian::readNext<uint32_t, little, aligned>(IDTableOffset);
  420. if (!(IData >= BufBeg && IData < BufEnd)) {
  421. Diags.Report(diag::err_invalid_pth_file) << file;
  422. return nullptr;
  423. }
  424. // Get the location of the hashtable mapping between strings and
  425. // persistent IDs.
  426. const unsigned char* StringIdTableOffset = PrologueOffset + sizeof(uint32_t)*1;
  427. const unsigned char *StringIdTable =
  428. BufBeg + endian::readNext<uint32_t, little, aligned>(StringIdTableOffset);
  429. if (!(StringIdTable >= BufBeg && StringIdTable < BufEnd)) {
  430. Diags.Report(diag::err_invalid_pth_file) << file;
  431. return nullptr;
  432. }
  433. std::unique_ptr<PTHStringIdLookup> SL(
  434. PTHStringIdLookup::Create(StringIdTable, BufBeg));
  435. // Get the location of the spelling cache.
  436. const unsigned char* spellingBaseOffset = PrologueOffset + sizeof(uint32_t)*3;
  437. const unsigned char *spellingBase =
  438. BufBeg + endian::readNext<uint32_t, little, aligned>(spellingBaseOffset);
  439. if (!(spellingBase >= BufBeg && spellingBase < BufEnd)) {
  440. Diags.Report(diag::err_invalid_pth_file) << file;
  441. return nullptr;
  442. }
  443. // Get the number of IdentifierInfos and pre-allocate the identifier cache.
  444. uint32_t NumIds = endian::readNext<uint32_t, little, aligned>(IData);
  445. // Pre-allocate the persistent ID -> IdentifierInfo* cache. We use calloc()
  446. // so that we in the best case only zero out memory once when the OS returns
  447. // us new pages.
  448. std::unique_ptr<IdentifierInfo *[], llvm::FreeDeleter> PerIDCache;
  449. if (NumIds) {
  450. PerIDCache.reset((IdentifierInfo **)calloc(NumIds, sizeof(PerIDCache[0])));
  451. if (!PerIDCache) {
  452. InvalidPTH(Diags, "Could not allocate memory for processing PTH file");
  453. return nullptr;
  454. }
  455. }
  456. // Compute the address of the original source file.
  457. const unsigned char* originalSourceBase = PrologueOffset + sizeof(uint32_t)*4;
  458. unsigned len =
  459. endian::readNext<uint16_t, little, unaligned>(originalSourceBase);
  460. if (!len) originalSourceBase = nullptr;
  461. // Create the new PTHManager.
  462. return new PTHManager(std::move(File), std::move(FL), IData,
  463. std::move(PerIDCache), std::move(SL), NumIds,
  464. spellingBase, (const char *)originalSourceBase);
  465. }
  466. IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) {
  467. using namespace llvm::support;
  468. // Look in the PTH file for the string data for the IdentifierInfo object.
  469. const unsigned char* TableEntry = IdDataTable + sizeof(uint32_t)*PersistentID;
  470. const unsigned char *IDData =
  471. (const unsigned char *)Buf->getBufferStart() +
  472. endian::readNext<uint32_t, little, aligned>(TableEntry);
  473. assert(IDData < (const unsigned char*)Buf->getBufferEnd());
  474. // Allocate the object.
  475. std::pair<IdentifierInfo,const unsigned char*> *Mem =
  476. Alloc.Allocate<std::pair<IdentifierInfo, const unsigned char *>>();
  477. Mem->second = IDData;
  478. assert(IDData[0] != '\0');
  479. IdentifierInfo *II = new ((void*) Mem) IdentifierInfo();
  480. // Store the new IdentifierInfo in the cache.
  481. PerIDCache[PersistentID] = II;
  482. assert(II->getNameStart() && II->getNameStart()[0] != '\0');
  483. return II;
  484. }
  485. IdentifierInfo* PTHManager::get(StringRef Name) {
  486. // Double check our assumption that the last character isn't '\0'.
  487. assert(Name.empty() || Name.back() != '\0');
  488. PTHStringIdLookup::iterator I =
  489. StringIdLookup->find(std::make_pair(Name.data(), Name.size()));
  490. if (I == StringIdLookup->end()) // No identifier found?
  491. return nullptr;
  492. // Match found. Return the identifier!
  493. assert(*I > 0);
  494. return GetIdentifierInfo(*I-1);
  495. }
  496. PTHLexer *PTHManager::CreateLexer(FileID FID) {
  497. const FileEntry *FE = PP->getSourceManager().getFileEntryForID(FID);
  498. if (!FE)
  499. return nullptr;
  500. using namespace llvm::support;
  501. // Lookup the FileEntry object in our file lookup data structure. It will
  502. // return a variant that indicates whether or not there is an offset within
  503. // the PTH file that contains cached tokens.
  504. PTHFileLookup::iterator I = FileLookup->find(FE);
  505. if (I == FileLookup->end()) // No tokens available?
  506. return nullptr;
  507. const PTHFileData& FileData = *I;
  508. const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart();
  509. // Compute the offset of the token data within the buffer.
  510. const unsigned char* data = BufStart + FileData.getTokenOffset();
  511. // Get the location of pp-conditional table.
  512. const unsigned char* ppcond = BufStart + FileData.getPPCondOffset();
  513. uint32_t Len = endian::readNext<uint32_t, little, aligned>(ppcond);
  514. if (Len == 0) ppcond = nullptr;
  515. assert(PP && "No preprocessor set yet!");
  516. return new PTHLexer(*PP, FID, data, ppcond, *this);
  517. }
  518. //===----------------------------------------------------------------------===//
  519. // 'stat' caching.
  520. //===----------------------------------------------------------------------===//
  521. namespace {
  522. class PTHStatData {
  523. public:
  524. uint64_t Size;
  525. time_t ModTime;
  526. llvm::sys::fs::UniqueID UniqueID;
  527. const bool HasData = false;
  528. bool IsDirectory;
  529. PTHStatData() = default;
  530. PTHStatData(uint64_t Size, time_t ModTime, llvm::sys::fs::UniqueID UniqueID,
  531. bool IsDirectory)
  532. : Size(Size), ModTime(ModTime), UniqueID(UniqueID), HasData(true),
  533. IsDirectory(IsDirectory) {}
  534. };
  535. class PTHStatLookupTrait : public PTHFileLookupCommonTrait {
  536. public:
  537. using external_key_type = StringRef; // const char*
  538. using data_type = PTHStatData;
  539. static internal_key_type GetInternalKey(StringRef path) {
  540. // The key 'kind' doesn't matter here because it is ignored in EqualKey.
  541. return std::make_pair((unsigned char) 0x0, path);
  542. }
  543. static bool EqualKey(internal_key_type a, internal_key_type b) {
  544. // When doing 'stat' lookups we don't care about the kind of 'a' and 'b',
  545. // just the paths.
  546. return a.second == b.second;
  547. }
  548. static data_type ReadData(const internal_key_type& k, const unsigned char* d,
  549. unsigned) {
  550. if (k.first /* File or Directory */) {
  551. bool IsDirectory = true;
  552. if (k.first == 0x1 /* File */) {
  553. IsDirectory = false;
  554. d += 4 * 2; // Skip the first 2 words.
  555. }
  556. using namespace llvm::support;
  557. uint64_t File = endian::readNext<uint64_t, little, unaligned>(d);
  558. uint64_t Device = endian::readNext<uint64_t, little, unaligned>(d);
  559. llvm::sys::fs::UniqueID UniqueID(Device, File);
  560. time_t ModTime = endian::readNext<uint64_t, little, unaligned>(d);
  561. uint64_t Size = endian::readNext<uint64_t, little, unaligned>(d);
  562. return data_type(Size, ModTime, UniqueID, IsDirectory);
  563. }
  564. // Negative stat. Don't read anything.
  565. return data_type();
  566. }
  567. };
  568. } // namespace
  569. namespace clang {
  570. class PTHStatCache : public FileSystemStatCache {
  571. using CacheTy = llvm::OnDiskChainedHashTable<PTHStatLookupTrait>;
  572. CacheTy Cache;
  573. public:
  574. PTHStatCache(PTHManager::PTHFileLookup &FL)
  575. : Cache(FL.getNumBuckets(), FL.getNumEntries(), FL.getBuckets(),
  576. FL.getBase()) {}
  577. LookupResult getStat(StringRef Path, FileData &Data, bool isFile,
  578. std::unique_ptr<llvm::vfs::File> *F,
  579. llvm::vfs::FileSystem &FS) override {
  580. // Do the lookup for the file's data in the PTH file.
  581. CacheTy::iterator I = Cache.find(Path);
  582. // If we don't get a hit in the PTH file just forward to 'stat'.
  583. if (I == Cache.end())
  584. return statChained(Path, Data, isFile, F, FS);
  585. const PTHStatData &D = *I;
  586. if (!D.HasData)
  587. return CacheMissing;
  588. Data.Name = Path;
  589. Data.Size = D.Size;
  590. Data.ModTime = D.ModTime;
  591. Data.UniqueID = D.UniqueID;
  592. Data.IsDirectory = D.IsDirectory;
  593. Data.IsNamedPipe = false;
  594. Data.InPCH = true;
  595. return CacheExists;
  596. }
  597. };
  598. } // namespace clang
  599. std::unique_ptr<FileSystemStatCache> PTHManager::createStatCache() {
  600. return llvm::make_unique<PTHStatCache>(*FileLookup);
  601. }