blob: e547ce551b92e7810791966faeda752f71fd7500 [file] [log] [blame]
Ted Kremenek274b2082008-11-12 21:37:15 +00001//===--- 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
Ted Kremenek0c6a77b2008-12-03 00:38:03 +000014#include "clang/Basic/TokenKinds.h"
15#include "clang/Basic/FileManager.h"
16#include "clang/Basic/IdentifierTable.h"
Ted Kremenek274b2082008-11-12 21:37:15 +000017#include "clang/Lex/PTHLexer.h"
18#include "clang/Lex/Preprocessor.h"
Ted Kremenek0c6a77b2008-12-03 00:38:03 +000019#include "clang/Lex/PTHManager.h"
20#include "clang/Lex/Token.h"
21#include "clang/Lex/Preprocessor.h"
Ted Kremenek0c6a77b2008-12-03 00:38:03 +000022#include "llvm/ADT/StringMap.h"
23#include "llvm/ADT/OwningPtr.h"
Chris Lattner6f78c3b2009-01-22 23:50:07 +000024#include "llvm/Support/Compiler.h"
25#include "llvm/Support/MathExtras.h"
26#include "llvm/Support/MemoryBuffer.h"
27#include "llvm/System/Host.h"
Ted Kremenek337edcd2009-02-12 03:26:59 +000028#include <sys/stat.h>
Ted Kremenek274b2082008-11-12 21:37:15 +000029using namespace clang;
30
Ted Kremenek7b78b7c2009-01-19 23:13:15 +000031#define DISK_TOKEN_SIZE (1+1+2+4+4)
Ted Kremenek268ee702008-12-12 18:34:08 +000032
Ted Kremenek0c6a77b2008-12-03 00:38:03 +000033//===----------------------------------------------------------------------===//
34// Utility methods for reading from the mmap'ed PTH file.
35//===----------------------------------------------------------------------===//
36
Chris Lattner5ff43172009-01-22 19:48:26 +000037static inline uint16_t ReadUnalignedLE16(const unsigned char *&Data) {
Ted Kremenekd8c02922009-02-10 22:16:22 +000038 uint16_t V = ((uint16_t)Data[0]) |
Chris Lattnerda9d61c2009-01-18 01:57:14 +000039 ((uint16_t)Data[1] << 8);
40 Data += 2;
41 return V;
42}
43
Ted Kremenekd8c02922009-02-10 22:16:22 +000044static inline uint32_t ReadUnalignedLE32(const unsigned char *&Data) {
45 uint32_t V = ((uint32_t)Data[0]) |
46 ((uint32_t)Data[1] << 8) |
47 ((uint32_t)Data[2] << 16) |
48 ((uint32_t)Data[3] << 24);
49 Data += 4;
50 return V;
51}
52
Ted Kremenek337edcd2009-02-12 03:26:59 +000053static inline uint64_t ReadUnalignedLE64(const unsigned char *&Data) {
54 uint64_t V = ((uint64_t)Data[0]) |
55 ((uint64_t)Data[1] << 8) |
56 ((uint64_t)Data[2] << 16) |
57 ((uint64_t)Data[3] << 24) |
Ted Kremenekd69ab872009-02-12 03:39:55 +000058 ((uint64_t)Data[4] << 32) |
59 ((uint64_t)Data[5] << 40) |
60 ((uint64_t)Data[6] << 48) |
61 ((uint64_t)Data[7] << 56);
Ted Kremenek337edcd2009-02-12 03:26:59 +000062 Data += 8;
63 return V;
64}
65
Chris Lattner5ff43172009-01-22 19:48:26 +000066static inline uint32_t ReadLE32(const unsigned char *&Data) {
Chris Lattnerfbc33382009-01-23 00:13:28 +000067 // Hosts that directly support little-endian 32-bit loads can just
68 // use them. Big-endian hosts need a bswap.
Chris Lattnerf15674c2009-01-18 02:19:16 +000069 uint32_t V = *((uint32_t*)Data);
Chris Lattner6f78c3b2009-01-22 23:50:07 +000070 if (llvm::sys::isBigEndianHost())
71 V = llvm::ByteSwap_32(V);
Chris Lattnerda9d61c2009-01-18 01:57:14 +000072 Data += 4;
73 return V;
74}
75
Ted Kremenek7e3a0042009-02-11 21:29:16 +000076// Bernstein hash function:
77// This is basically copy-and-paste from StringMap. This likely won't
78// stay here, which is why I didn't both to expose this function from
79// String Map.
80static unsigned BernsteinHash(const char* x) {
81 unsigned int R = 0;
82 for ( ; *x != '\0' ; ++x) R = R * 33 + *x;
83 return R + (R >> 5);
84}
85
86static unsigned BernsteinHash(const char* x, unsigned n) {
87 unsigned int R = 0;
88 for (unsigned i = 0 ; i < n ; ++i, ++x) R = R * 33 + *x;
89 return R + (R >> 5);
90}
Chris Lattnerda9d61c2009-01-18 01:57:14 +000091
Ted Kremeneke5680f32008-12-23 01:30:52 +000092//===----------------------------------------------------------------------===//
93// PTHLexer methods.
94//===----------------------------------------------------------------------===//
95
Chris Lattnerda9d61c2009-01-18 01:57:14 +000096PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D,
Ted Kremenek277faca2009-01-27 00:01:05 +000097 const unsigned char *ppcond, PTHManager &PM)
Chris Lattner2b2453a2009-01-17 06:22:33 +000098 : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(0),
Ted Kremenek277faca2009-01-27 00:01:05 +000099 PPCond(ppcond), CurPPCondPtr(ppcond), PTHMgr(PM) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000100
101 FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID);
Ted Kremenek5f074262009-01-09 22:05:30 +0000102}
Ted Kremeneke5680f32008-12-23 01:30:52 +0000103
104void PTHLexer::Lex(Token& Tok) {
105LexNextToken:
Ted Kremeneke5680f32008-12-23 01:30:52 +0000106
Ted Kremenek866bdf72008-12-23 02:30:15 +0000107 //===--------------------------------------==//
108 // Read the raw token data.
109 //===--------------------------------------==//
110
111 // Shadow CurPtr into an automatic variable.
Chris Lattneraff6ef82009-01-21 07:21:56 +0000112 const unsigned char *CurPtrShadow = CurPtr;
Ted Kremenek866bdf72008-12-23 02:30:15 +0000113
Chris Lattner1b5285e2009-01-18 02:10:31 +0000114 // Read in the data for the token.
Chris Lattner5ff43172009-01-22 19:48:26 +0000115 unsigned Word0 = ReadLE32(CurPtrShadow);
116 uint32_t IdentifierID = ReadLE32(CurPtrShadow);
117 uint32_t FileOffset = ReadLE32(CurPtrShadow);
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000118
119 tok::TokenKind TKind = (tok::TokenKind) (Word0 & 0xFF);
120 Token::TokenFlags TFlags = (Token::TokenFlags) ((Word0 >> 8) & 0xFF);
Chris Lattneraff6ef82009-01-21 07:21:56 +0000121 uint32_t Len = Word0 >> 16;
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000122
Chris Lattneraff6ef82009-01-21 07:21:56 +0000123 CurPtr = CurPtrShadow;
Ted Kremenek866bdf72008-12-23 02:30:15 +0000124
125 //===--------------------------------------==//
126 // Construct the token itself.
127 //===--------------------------------------==//
128
129 Tok.startToken();
Chris Lattner898a0bb2009-01-18 02:34:01 +0000130 Tok.setKind(TKind);
131 Tok.setFlag(TFlags);
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000132 assert(!LexingRawMode);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000133 Tok.setLocation(FileStartLoc.getFileLocWithOffset(FileOffset));
Ted Kremenek866bdf72008-12-23 02:30:15 +0000134 Tok.setLength(Len);
135
Chris Lattnerd0a69692009-01-21 07:50:06 +0000136 // Handle identifiers.
Ted Kremenek277faca2009-01-27 00:01:05 +0000137 if (Tok.isLiteral()) {
138 Tok.setLiteralData((const char*) (PTHMgr.SpellingBase + IdentifierID));
139 }
140 else if (IdentifierID) {
Chris Lattnerd0a69692009-01-21 07:50:06 +0000141 MIOpt.ReadToken();
142 IdentifierInfo *II = PTHMgr.GetIdentifierInfo(IdentifierID-1);
Chris Lattner863c4862009-01-23 18:35:48 +0000143
Chris Lattnerd0a69692009-01-21 07:50:06 +0000144 Tok.setIdentifierInfo(II);
Chris Lattner863c4862009-01-23 18:35:48 +0000145
146 // Change the kind of this identifier to the appropriate token kind, e.g.
147 // turning "for" into a keyword.
148 Tok.setKind(II->getTokenID());
149
Chris Lattnerd0a69692009-01-21 07:50:06 +0000150 if (II->isHandleIdentifierCase())
151 PP->HandleIdentifier(Tok);
152 return;
153 }
154
Ted Kremenek866bdf72008-12-23 02:30:15 +0000155 //===--------------------------------------==//
156 // Process the token.
157 //===--------------------------------------==//
Ted Kremenek5f074262009-01-09 22:05:30 +0000158#if 0
159 SourceManager& SM = PP->getSourceManager();
160 llvm::cerr << SM.getFileEntryForID(FileID)->getName()
161 << ':' << SM.getLogicalLineNumber(Tok.getLocation())
162 << ':' << SM.getLogicalColumnNumber(Tok.getLocation())
163 << '\n';
164#endif
Ted Kremeneke5680f32008-12-23 01:30:52 +0000165
Chris Lattner898a0bb2009-01-18 02:34:01 +0000166 if (TKind == tok::eof) {
Ted Kremeneke5680f32008-12-23 01:30:52 +0000167 // Save the end-of-file token.
168 EofToken = Tok;
169
170 Preprocessor *PPCache = PP;
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000171
172 assert(!ParsingPreprocessorDirective);
173 assert(!LexingRawMode);
174
175 // FIXME: Issue diagnostics similar to Lexer.
176 if (PP->HandleEndOfFile(Tok, false))
Ted Kremeneke5680f32008-12-23 01:30:52 +0000177 return;
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000178
Ted Kremeneke5680f32008-12-23 01:30:52 +0000179 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
180 return PPCache->Lex(Tok);
181 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000182
Chris Lattner898a0bb2009-01-18 02:34:01 +0000183 if (TKind == tok::hash && Tok.isAtStartOfLine()) {
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000184 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
185 assert(!LexingRawMode);
186 PP->HandleDirective(Tok);
187
188 if (PP->isCurrentLexer(this))
189 goto LexNextToken;
190
191 return PP->Lex(Tok);
192 }
193
Chris Lattner898a0bb2009-01-18 02:34:01 +0000194 if (TKind == tok::eom) {
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000195 assert(ParsingPreprocessorDirective);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000196 ParsingPreprocessorDirective = false;
197 return;
198 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000199
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000200 MIOpt.ReadToken();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000201}
202
203// FIXME: We can just grab the last token instead of storing a copy
204// into EofToken.
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000205void PTHLexer::getEOF(Token& Tok) {
Ted Kremenekdefb7092009-01-09 00:36:11 +0000206 assert(EofToken.is(tok::eof));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000207 Tok = EofToken;
208}
209
210void PTHLexer::DiscardToEndOfLine() {
211 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
212 "Must be in a preprocessing directive!");
213
214 // We assume that if the preprocessor wishes to discard to the end of
215 // the line that it also means to end the current preprocessor directive.
216 ParsingPreprocessorDirective = false;
217
218 // Skip tokens by only peeking at their token kind and the flags.
219 // We don't need to actually reconstruct full tokens from the token buffer.
220 // This saves some copies and it also reduces IdentifierInfo* lookup.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000221 const unsigned char* p = CurPtr;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000222 while (1) {
223 // Read the token kind. Are we at the end of the file?
224 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
225 if (x == tok::eof) break;
226
227 // Read the token flags. Are we at the start of the next line?
228 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
229 if (y & Token::StartOfLine) break;
230
231 // Skip to the next token.
232 p += DISK_TOKEN_SIZE;
233 }
234
235 CurPtr = p;
236}
237
Ted Kremenek268ee702008-12-12 18:34:08 +0000238/// SkipBlock - Used by Preprocessor to skip the current conditional block.
239bool PTHLexer::SkipBlock() {
240 assert(CurPPCondPtr && "No cached PP conditional information.");
241 assert(LastHashTokPtr && "No known '#' token.");
242
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000243 const unsigned char* HashEntryI = 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000244 uint32_t Offset;
245 uint32_t TableIdx;
246
247 do {
Ted Kremenek41a26602008-12-12 22:05:38 +0000248 // Read the token offset from the side-table.
Chris Lattner5ff43172009-01-22 19:48:26 +0000249 Offset = ReadLE32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000250
251 // Read the target table index from the side-table.
Chris Lattner5ff43172009-01-22 19:48:26 +0000252 TableIdx = ReadLE32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000253
254 // Compute the actual memory address of the '#' token data for this entry.
255 HashEntryI = TokBuf + Offset;
256
257 // Optmization: "Sibling jumping". #if...#else...#endif blocks can
258 // contain nested blocks. In the side-table we can jump over these
259 // nested blocks instead of doing a linear search if the next "sibling"
260 // entry is not at a location greater than LastHashTokPtr.
261 if (HashEntryI < LastHashTokPtr && TableIdx) {
262 // In the side-table we are still at an entry for a '#' token that
263 // is earlier than the last one we saw. Check if the location we would
264 // stride gets us closer.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000265 const unsigned char* NextPPCondPtr =
266 PPCond + TableIdx*(sizeof(uint32_t)*2);
Ted Kremenek41a26602008-12-12 22:05:38 +0000267 assert(NextPPCondPtr >= CurPPCondPtr);
268 // Read where we should jump to.
Chris Lattner5ff43172009-01-22 19:48:26 +0000269 uint32_t TmpOffset = ReadLE32(NextPPCondPtr);
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000270 const unsigned char* HashEntryJ = TokBuf + TmpOffset;
Ted Kremenek41a26602008-12-12 22:05:38 +0000271
272 if (HashEntryJ <= LastHashTokPtr) {
273 // Jump directly to the next entry in the side table.
274 HashEntryI = HashEntryJ;
275 Offset = TmpOffset;
Chris Lattner5ff43172009-01-22 19:48:26 +0000276 TableIdx = ReadLE32(NextPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000277 CurPPCondPtr = NextPPCondPtr;
278 }
279 }
Ted Kremenek268ee702008-12-12 18:34:08 +0000280 }
Ted Kremenek41a26602008-12-12 22:05:38 +0000281 while (HashEntryI < LastHashTokPtr);
282 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
Ted Kremenek268ee702008-12-12 18:34:08 +0000283 assert(TableIdx && "No jumping from #endifs.");
284
285 // Update our side-table iterator.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000286 const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
Ted Kremenek268ee702008-12-12 18:34:08 +0000287 assert(NextPPCondPtr >= CurPPCondPtr);
288 CurPPCondPtr = NextPPCondPtr;
289
290 // Read where we should jump to.
Chris Lattner5ff43172009-01-22 19:48:26 +0000291 HashEntryI = TokBuf + ReadLE32(NextPPCondPtr);
292 uint32_t NextIdx = ReadLE32(NextPPCondPtr);
Ted Kremenek268ee702008-12-12 18:34:08 +0000293
294 // By construction NextIdx will be zero if this is a #endif. This is useful
295 // to know to obviate lexing another token.
296 bool isEndif = NextIdx == 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000297
298 // This case can occur when we see something like this:
299 //
300 // #if ...
301 // /* a comment or nothing */
302 // #elif
303 //
304 // If we are skipping the first #if block it will be the case that CurPtr
305 // already points 'elif'. Just return.
306
Ted Kremenek41a26602008-12-12 22:05:38 +0000307 if (CurPtr > HashEntryI) {
308 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
Ted Kremenek268ee702008-12-12 18:34:08 +0000309 // Did we reach a #endif? If so, go ahead and consume that token as well.
310 if (isEndif)
Ted Kremeneke5680f32008-12-23 01:30:52 +0000311 CurPtr += DISK_TOKEN_SIZE*2;
Ted Kremenek268ee702008-12-12 18:34:08 +0000312 else
Ted Kremenek41a26602008-12-12 22:05:38 +0000313 LastHashTokPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000314
315 return isEndif;
316 }
317
318 // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
Ted Kremenek41a26602008-12-12 22:05:38 +0000319 CurPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000320
321 // Update the location of the last observed '#'. This is useful if we
322 // are skipping multiple blocks.
323 LastHashTokPtr = CurPtr;
Ted Kremenek268ee702008-12-12 18:34:08 +0000324
Ted Kremeneke5680f32008-12-23 01:30:52 +0000325 // Skip the '#' token.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000326 assert(((tok::TokenKind)*CurPtr) == tok::hash);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000327 CurPtr += DISK_TOKEN_SIZE;
328
Ted Kremenek268ee702008-12-12 18:34:08 +0000329 // Did we reach a #endif? If so, go ahead and consume that token as well.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000330 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
Ted Kremenek268ee702008-12-12 18:34:08 +0000331
332 return isEndif;
333}
334
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000335SourceLocation PTHLexer::getSourceLocation() {
Chris Lattner1b5285e2009-01-18 02:10:31 +0000336 // getSourceLocation is not on the hot path. It is used to get the location
337 // of the next token when transitioning back to this lexer when done
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000338 // handling a #included file. Just read the necessary data from the token
339 // data buffer to construct the SourceLocation object.
340 // NOTE: This is a virtual function; hence it is defined out-of-line.
Ted Kremenekb248d532009-01-21 22:41:38 +0000341 const unsigned char *OffsetPtr = CurPtr + (DISK_TOKEN_SIZE - 4);
Chris Lattner5ff43172009-01-22 19:48:26 +0000342 uint32_t Offset = ReadLE32(OffsetPtr);
Chris Lattner1b5285e2009-01-18 02:10:31 +0000343 return FileStartLoc.getFileLocWithOffset(Offset);
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000344}
345
Ted Kremenek5f074262009-01-09 22:05:30 +0000346//===----------------------------------------------------------------------===//
Ted Kremenekd8c02922009-02-10 22:16:22 +0000347// OnDiskChainedHashTable
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000348//===----------------------------------------------------------------------===//
349
Ted Kremenekd8c02922009-02-10 22:16:22 +0000350template<typename Info>
351class OnDiskChainedHashTable {
352 const unsigned NumBuckets;
353 const unsigned NumEntries;
354 const unsigned char* const Buckets;
355 const unsigned char* const Base;
356public:
357 typedef typename Info::internal_key_type internal_key_type;
358 typedef typename Info::external_key_type external_key_type;
359 typedef typename Info::data_type data_type;
360
361 OnDiskChainedHashTable(unsigned numBuckets, unsigned numEntries,
362 const unsigned char* buckets,
363 const unsigned char* base)
364 : NumBuckets(numBuckets), NumEntries(numEntries),
365 Buckets(buckets), Base(base) {
366 assert((reinterpret_cast<uintptr_t>(buckets) & 0x3) == 0 &&
367 "'buckets' must have a 4-byte alignment");
368 }
369
Ted Kremenek337edcd2009-02-12 03:26:59 +0000370 unsigned getNumBuckets() const { return NumBuckets; }
371 unsigned getNumEntries() const { return NumEntries; }
Eli Friedman03a28072009-02-13 01:02:29 +0000372 const unsigned char* getBase() const { return Base; }
373 const unsigned char* getBuckets() const { return Buckets; }
Ted Kremenek337edcd2009-02-12 03:26:59 +0000374
Ted Kremenekd8c02922009-02-10 22:16:22 +0000375 bool isEmpty() const { return NumEntries == 0; }
376
377 class iterator {
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000378 internal_key_type key;
Ted Kremenekd8c02922009-02-10 22:16:22 +0000379 const unsigned char* const data;
380 const unsigned len;
381 public:
382 iterator() : data(0), len(0) {}
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000383 iterator(const internal_key_type k, const unsigned char* d, unsigned l)
384 : key(k), data(d), len(l) {}
Ted Kremenekd8c02922009-02-10 22:16:22 +0000385
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000386 data_type operator*() const { return Info::ReadData(key, data, len); }
Ted Kremenekd8c02922009-02-10 22:16:22 +0000387 bool operator==(const iterator& X) const { return X.data == data; }
388 bool operator!=(const iterator& X) const { return X.data != data; }
389 };
390
391 iterator find(const external_key_type& eKey) {
392 const internal_key_type& iKey = Info::GetInternalKey(eKey);
393 unsigned key_hash = Info::ComputeHash(iKey);
394
395 // Each bucket is just a 32-bit offset into the PTH file.
396 unsigned idx = key_hash & (NumBuckets - 1);
397 const unsigned char* Bucket = Buckets + sizeof(uint32_t)*idx;
398
399 unsigned offset = ReadLE32(Bucket);
400 if (offset == 0) return iterator(); // Empty bucket.
401 const unsigned char* Items = Base + offset;
402
403 // 'Items' starts with a 16-bit unsigned integer representing the
404 // number of items in this bucket.
405 unsigned len = ReadUnalignedLE16(Items);
406
407 for (unsigned i = 0; i < len; ++i) {
408 // Read the hash.
409 uint32_t item_hash = ReadUnalignedLE32(Items);
410
411 // Determine the length of the key and the data.
412 const std::pair<unsigned, unsigned>& L = Info::ReadKeyDataLength(Items);
413 unsigned item_len = L.first + L.second;
414
415 // Compare the hashes. If they are not the same, skip the entry entirely.
416 if (item_hash != key_hash) {
417 Items += item_len;
418 continue;
419 }
420
421 // Read the key.
422 const internal_key_type& X =
423 Info::ReadKey((const unsigned char* const) Items, L.first);
424
425 // If the key doesn't match just skip reading the value.
426 if (!Info::EqualKey(X, iKey)) {
427 Items += item_len;
428 continue;
429 }
430
431 // The key matches!
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000432 return iterator(X, Items + L.first, L.second);
Ted Kremenekd8c02922009-02-10 22:16:22 +0000433 }
434
435 return iterator();
436 }
437
438 iterator end() const { return iterator(); }
439
440
441 static OnDiskChainedHashTable* Create(const unsigned char* buckets,
442 const unsigned char* const base) {
443
444 assert(buckets > base);
445 assert((reinterpret_cast<uintptr_t>(buckets) & 0x3) == 0 &&
446 "buckets should be 4-byte aligned.");
447
448 unsigned numBuckets = ReadLE32(buckets);
449 unsigned numEntries = ReadLE32(buckets);
450 return new OnDiskChainedHashTable<Info>(numBuckets, numEntries, buckets,
451 base);
452 }
453};
454
455//===----------------------------------------------------------------------===//
456// PTH file lookup: map from strings to file data.
457//===----------------------------------------------------------------------===//
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000458
459/// PTHFileLookup - This internal data structure is used by the PTHManager
460/// to map from FileEntry objects managed by FileManager to offsets within
461/// the PTH file.
462namespace {
Ted Kremenekd8c02922009-02-10 22:16:22 +0000463class VISIBILITY_HIDDEN PTHFileData {
464 const uint32_t TokenOff;
465 const uint32_t PPCondOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000466public:
Ted Kremenekd8c02922009-02-10 22:16:22 +0000467 PTHFileData(uint32_t tokenOff, uint32_t ppCondOff)
468 : TokenOff(tokenOff), PPCondOff(ppCondOff) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000469
Ted Kremenekd8c02922009-02-10 22:16:22 +0000470 uint32_t getTokenOffset() const { return TokenOff; }
471 uint32_t getPPCondOffset() const { return PPCondOff; }
472};
473
Ted Kremenek337edcd2009-02-12 03:26:59 +0000474
475class VISIBILITY_HIDDEN PTHFileLookupCommonTrait {
Ted Kremenekd8c02922009-02-10 22:16:22 +0000476public:
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000477 typedef std::pair<unsigned char, const char*> internal_key_type;
478
479 static unsigned ComputeHash(internal_key_type x) {
480 return BernsteinHash(x.second);
Ted Kremenekd8c02922009-02-10 22:16:22 +0000481 }
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000482
Ted Kremenekd8c02922009-02-10 22:16:22 +0000483 static std::pair<unsigned, unsigned>
484 ReadKeyDataLength(const unsigned char*& d) {
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000485 unsigned keyLen = (unsigned) ReadUnalignedLE16(d);
486 unsigned dataLen = (unsigned) *(d++);
487 return std::make_pair(keyLen, dataLen);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000488 }
489
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000490 static internal_key_type ReadKey(const unsigned char* d, unsigned) {
491 unsigned char k = *(d++); // Read the entry kind.
492 return std::make_pair(k, (const char*) d);
Ted Kremenekd8c02922009-02-10 22:16:22 +0000493 }
Ted Kremenek337edcd2009-02-12 03:26:59 +0000494};
495
496class VISIBILITY_HIDDEN PTHFileLookupTrait : public PTHFileLookupCommonTrait {
497public:
498 typedef const FileEntry* external_key_type;
499 typedef PTHFileData data_type;
500
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000501 static internal_key_type GetInternalKey(const FileEntry* FE) {
502 return std::make_pair((unsigned char) 0x1, FE->getName());
Ted Kremenek337edcd2009-02-12 03:26:59 +0000503 }
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000504
505 static bool EqualKey(internal_key_type a, internal_key_type b) {
506 return a.first == b.first && strcmp(a.second, b.second) == 0;
507 }
Ted Kremenekd8c02922009-02-10 22:16:22 +0000508
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000509 static PTHFileData ReadData(const internal_key_type& k,
510 const unsigned char* d, unsigned) {
511 assert(k.first == 0x1 && "Only file lookups can match!");
Ted Kremenekd8c02922009-02-10 22:16:22 +0000512 uint32_t x = ::ReadUnalignedLE32(d);
513 uint32_t y = ::ReadUnalignedLE32(d);
514 return PTHFileData(x, y);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000515 }
516};
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000517
518class VISIBILITY_HIDDEN PTHStringLookupTrait {
519public:
520 typedef uint32_t
521 data_type;
522
523 typedef const std::pair<const char*, unsigned>
524 external_key_type;
525
526 typedef external_key_type internal_key_type;
527
528 static bool EqualKey(const internal_key_type& a,
529 const internal_key_type& b) {
530 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
531 : false;
532 }
533
534 static unsigned ComputeHash(const internal_key_type& a) {
535 return BernsteinHash(a.first, a.second);
536 }
537
538 // This hopefully will just get inlined and removed by the optimizer.
539 static const internal_key_type&
540 GetInternalKey(const external_key_type& x) { return x; }
541
542 static std::pair<unsigned, unsigned>
543 ReadKeyDataLength(const unsigned char*& d) {
544 return std::make_pair((unsigned) ReadUnalignedLE16(d), sizeof(uint32_t));
545 }
546
547 static std::pair<const char*, unsigned>
548 ReadKey(const unsigned char* d, unsigned n) {
549 assert(n >= 2 && d[n-1] == '\0');
550 return std::make_pair((const char*) d, n-1);
551 }
552
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000553 static uint32_t ReadData(const internal_key_type& k, const unsigned char* d,
554 unsigned) {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000555 return ::ReadUnalignedLE32(d);
556 }
557};
558
Ted Kremenekd8c02922009-02-10 22:16:22 +0000559} // end anonymous namespace
560
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000561typedef OnDiskChainedHashTable<PTHFileLookupTrait> PTHFileLookup;
562typedef OnDiskChainedHashTable<PTHStringLookupTrait> PTHStringIdLookup;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000563
564//===----------------------------------------------------------------------===//
565// PTHManager methods.
566//===----------------------------------------------------------------------===//
567
568PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000569 const unsigned char* idDataTable,
570 IdentifierInfo** perIDCache,
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000571 void* stringIdLookup, unsigned numIds,
Ted Kremenek68228632009-03-19 22:19:30 +0000572 const unsigned char* spellingBase,
573 const char* originalSourceFile)
Ted Kremenek6183e482008-12-03 01:16:39 +0000574: Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000575 IdDataTable(idDataTable), StringIdLookup(stringIdLookup),
Ted Kremenek68228632009-03-19 22:19:30 +0000576 NumIds(numIds), PP(0), SpellingBase(spellingBase),
577 OriginalSourceFile(originalSourceFile) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000578
579PTHManager::~PTHManager() {
580 delete Buf;
581 delete (PTHFileLookup*) FileLookup;
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000582 delete (PTHStringIdLookup*) StringIdLookup;
Ted Kremenek0e50b6e2008-12-04 22:47:11 +0000583 free(PerIDCache);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000584}
585
Ted Kremenek26555b12009-01-28 21:02:43 +0000586static void InvalidPTH(Diagnostic *Diags, const char* Msg = 0) {
587 if (!Diags) return;
588 if (!Msg) Msg = "Invalid or corrupted PTH file";
Ted Kremenek395c59c2009-02-19 22:13:40 +0000589 unsigned DiagID = Diags->getCustomDiagID(Diagnostic::Warning, Msg);
Ted Kremenek26555b12009-01-28 21:02:43 +0000590 Diags->Report(FullSourceLoc(), DiagID);
591}
592
Ted Kremenek8a6aec62009-01-28 20:49:33 +0000593PTHManager* PTHManager::Create(const std::string& file, Diagnostic* Diags) {
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000594 // Memory map the PTH file.
595 llvm::OwningPtr<llvm::MemoryBuffer>
596 File(llvm::MemoryBuffer::getFile(file.c_str()));
597
Ted Kremenek8a6aec62009-01-28 20:49:33 +0000598 if (!File) {
599 if (Diags) {
Ted Kremenek640f5522009-02-19 22:14:49 +0000600 unsigned DiagID = Diags->getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8a6aec62009-01-28 20:49:33 +0000601 "PTH file %0 could not be read");
602 Diags->Report(FullSourceLoc(), DiagID) << file;
603 }
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000604
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000605 return 0;
Ted Kremenek8a6aec62009-01-28 20:49:33 +0000606 }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000607
608 // Get the buffer ranges and check if there are at least three 32-bit
609 // words at the end of the file.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000610 const unsigned char* BufBeg = (unsigned char*)File->getBufferStart();
611 const unsigned char* BufEnd = (unsigned char*)File->getBufferEnd();
Ted Kremeneke1b64982009-01-26 21:43:14 +0000612
613 // Check the prologue of the file.
Ted Kremenek4adc71a2009-01-26 22:16:12 +0000614 if ((BufEnd - BufBeg) < (signed) (sizeof("cfe-pth") + 3 + 4) ||
Ted Kremenek26555b12009-01-28 21:02:43 +0000615 memcmp(BufBeg, "cfe-pth", sizeof("cfe-pth") - 1) != 0) {
616 InvalidPTH(Diags);
Ted Kremeneke1b64982009-01-26 21:43:14 +0000617 return 0;
Ted Kremenek26555b12009-01-28 21:02:43 +0000618 }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000619
Ted Kremenek67d15052009-01-26 21:50:21 +0000620 // Read the PTH version.
Ted Kremeneke1b64982009-01-26 21:43:14 +0000621 const unsigned char *p = BufBeg + (sizeof("cfe-pth") - 1);
Ted Kremenek67d15052009-01-26 21:50:21 +0000622 unsigned Version = ReadLE32(p);
623
Ted Kremenek26555b12009-01-28 21:02:43 +0000624 if (Version != PTHManager::Version) {
625 InvalidPTH(Diags,
626 Version < PTHManager::Version
627 ? "PTH file uses an older PTH format that is no longer supported"
628 : "PTH file uses a newer PTH format that cannot be read");
Ted Kremenek67d15052009-01-26 21:50:21 +0000629 return 0;
Ted Kremenek26555b12009-01-28 21:02:43 +0000630 }
Ted Kremenek67d15052009-01-26 21:50:21 +0000631
632 // Compute the address of the index table at the end of the PTH file.
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000633 const unsigned char *PrologueOffset = p;
Ted Kremeneke1b64982009-01-26 21:43:14 +0000634
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000635 if (PrologueOffset >= BufEnd) {
Ted Kremenek26555b12009-01-28 21:02:43 +0000636 InvalidPTH(Diags);
Ted Kremeneke1b64982009-01-26 21:43:14 +0000637 return 0;
Ted Kremenek26555b12009-01-28 21:02:43 +0000638 }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000639
640 // Construct the file lookup table. This will be used for mapping from
641 // FileEntry*'s to cached tokens.
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000642 const unsigned char* FileTableOffset = PrologueOffset + sizeof(uint32_t)*2;
Chris Lattner5ff43172009-01-22 19:48:26 +0000643 const unsigned char* FileTable = BufBeg + ReadLE32(FileTableOffset);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000644
645 if (!(FileTable > BufBeg && FileTable < BufEnd)) {
Ted Kremenek26555b12009-01-28 21:02:43 +0000646 InvalidPTH(Diags);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000647 return 0; // FIXME: Proper error diagnostic?
648 }
649
Ted Kremenekd8c02922009-02-10 22:16:22 +0000650 llvm::OwningPtr<PTHFileLookup> FL(PTHFileLookup::Create(FileTable, BufBeg));
Ted Kremenek1d201972009-03-20 17:54:25 +0000651
652 // Warn if the PTH file is empty. We still want to create a PTHManager
653 // as the PTH could be used with -include-pth.
654 if (FL->isEmpty())
Ted Kremenek26555b12009-01-28 21:02:43 +0000655 InvalidPTH(Diags, "PTH file contains no cached source data");
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000656
657 // Get the location of the table mapping from persistent ids to the
658 // data needed to reconstruct identifiers.
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000659 const unsigned char* IDTableOffset = PrologueOffset + sizeof(uint32_t)*0;
Chris Lattner5ff43172009-01-22 19:48:26 +0000660 const unsigned char* IData = BufBeg + ReadLE32(IDTableOffset);
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000661
662 if (!(IData >= BufBeg && IData < BufEnd)) {
Ted Kremenek26555b12009-01-28 21:02:43 +0000663 InvalidPTH(Diags);
664 return 0;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000665 }
666
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000667 // Get the location of the hashtable mapping between strings and
668 // persistent IDs.
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000669 const unsigned char* StringIdTableOffset = PrologueOffset + sizeof(uint32_t)*1;
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000670 const unsigned char* StringIdTable = BufBeg + ReadLE32(StringIdTableOffset);
671 if (!(StringIdTable >= BufBeg && StringIdTable < BufEnd)) {
Ted Kremenek26555b12009-01-28 21:02:43 +0000672 InvalidPTH(Diags);
673 return 0;
Ted Kremenek72b1b152009-01-15 18:47:46 +0000674 }
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000675
676 llvm::OwningPtr<PTHStringIdLookup> SL(PTHStringIdLookup::Create(StringIdTable,
677 BufBeg));
Ted Kremenek783bb742009-03-21 00:25:09 +0000678
679 // Issue a warning about the PTH file containing no identifiers.
680 if (!FL->isEmpty() && SL->isEmpty()) {
681 InvalidPTH(Diags, "PTH file contains no identifiers.");
682 }
683
Ted Kremenek277faca2009-01-27 00:01:05 +0000684 // Get the location of the spelling cache.
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000685 const unsigned char* spellingBaseOffset = PrologueOffset + sizeof(uint32_t)*3;
Ted Kremenek277faca2009-01-27 00:01:05 +0000686 const unsigned char* spellingBase = BufBeg + ReadLE32(spellingBaseOffset);
687 if (!(spellingBase >= BufBeg && spellingBase < BufEnd)) {
Ted Kremenek26555b12009-01-28 21:02:43 +0000688 InvalidPTH(Diags);
Ted Kremenek277faca2009-01-27 00:01:05 +0000689 return 0;
690 }
691
Ted Kremenek6183e482008-12-03 01:16:39 +0000692 // Get the number of IdentifierInfos and pre-allocate the identifier cache.
Chris Lattner5ff43172009-01-22 19:48:26 +0000693 uint32_t NumIds = ReadLE32(IData);
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000694
Ted Kremenek6183e482008-12-03 01:16:39 +0000695 // Pre-allocate the peristent ID -> IdentifierInfo* cache. We use calloc()
696 // so that we in the best case only zero out memory once when the OS returns
697 // us new pages.
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000698 IdentifierInfo** PerIDCache = 0;
Ted Kremenek6183e482008-12-03 01:16:39 +0000699
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000700 if (NumIds) {
701 PerIDCache = (IdentifierInfo**)calloc(NumIds, sizeof(*PerIDCache));
702 if (!PerIDCache) {
Ted Kremenek26555b12009-01-28 21:02:43 +0000703 InvalidPTH(Diags, "Could not allocate memory for processing PTH file");
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000704 return 0;
705 }
Ted Kremenek6183e482008-12-03 01:16:39 +0000706 }
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000707
Ted Kremenek68228632009-03-19 22:19:30 +0000708 // Compute the address of the original source file.
709 const unsigned char* originalSourceBase = PrologueOffset + sizeof(uint32_t)*4;
710 unsigned len = ReadUnalignedLE16(originalSourceBase);
711 if (!len) originalSourceBase = 0;
712
Ted Kremenek72b1b152009-01-15 18:47:46 +0000713 // Create the new PTHManager.
714 return new PTHManager(File.take(), FL.take(), IData, PerIDCache,
Ted Kremenek68228632009-03-19 22:19:30 +0000715 SL.take(), NumIds, spellingBase,
716 (const char*) originalSourceBase);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000717}
Ted Kremenek68228632009-03-19 22:19:30 +0000718
Chris Lattner77ecb3a2009-01-18 02:57:21 +0000719IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) {
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000720 // Look in the PTH file for the string data for the IdentifierInfo object.
Chris Lattner77ecb3a2009-01-18 02:57:21 +0000721 const unsigned char* TableEntry = IdDataTable + sizeof(uint32_t)*PersistentID;
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000722 const unsigned char* IDData =
Chris Lattner5ff43172009-01-22 19:48:26 +0000723 (const unsigned char*)Buf->getBufferStart() + ReadLE32(TableEntry);
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000724 assert(IDData < (const unsigned char*)Buf->getBufferEnd());
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000725
Ted Kremenek72b1b152009-01-15 18:47:46 +0000726 // Allocate the object.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000727 std::pair<IdentifierInfo,const unsigned char*> *Mem =
728 Alloc.Allocate<std::pair<IdentifierInfo,const unsigned char*> >();
Ted Kremenek72b1b152009-01-15 18:47:46 +0000729
730 Mem->second = IDData;
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000731 assert(IDData[0] != '\0');
Ted Kremenekea9c26b2009-01-20 23:28:34 +0000732 IdentifierInfo *II = new ((void*) Mem) IdentifierInfo();
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000733
Ted Kremenek72b1b152009-01-15 18:47:46 +0000734 // Store the new IdentifierInfo in the cache.
Chris Lattner77ecb3a2009-01-18 02:57:21 +0000735 PerIDCache[PersistentID] = II;
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000736 assert(II->getName() && II->getName()[0] != '\0');
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000737 return II;
738}
739
Ted Kremenek72b1b152009-01-15 18:47:46 +0000740IdentifierInfo* PTHManager::get(const char *NameStart, const char *NameEnd) {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000741 PTHStringIdLookup& SL = *((PTHStringIdLookup*)StringIdLookup);
742 // Double check our assumption that the last character isn't '\0'.
Daniel Dunbar82320e92009-02-12 19:31:53 +0000743 assert(NameEnd==NameStart || NameStart[NameEnd-NameStart-1] != '\0');
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000744 PTHStringIdLookup::iterator I = SL.find(std::make_pair(NameStart,
745 NameEnd - NameStart));
746 if (I == SL.end()) // No identifier found?
747 return 0;
Ted Kremenek72b1b152009-01-15 18:47:46 +0000748
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000749 // Match found. Return the identifier!
750 assert(*I > 0);
751 return GetIdentifierInfo(*I-1);
752}
Ted Kremenek72b1b152009-01-15 18:47:46 +0000753
Chris Lattnerf056d922009-01-17 08:06:50 +0000754PTHLexer *PTHManager::CreateLexer(FileID FID) {
755 const FileEntry *FE = PP->getSourceManager().getFileEntryForID(FID);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000756 if (!FE)
757 return 0;
758
759 // Lookup the FileEntry object in our file lookup data structure. It will
760 // return a variant that indicates whether or not there is an offset within
761 // the PTH file that contains cached tokens.
Ted Kremenekd8c02922009-02-10 22:16:22 +0000762 PTHFileLookup& PFL = *((PTHFileLookup*)FileLookup);
763 PTHFileLookup::iterator I = PFL.find(FE);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000764
Ted Kremenekd8c02922009-02-10 22:16:22 +0000765 if (I == PFL.end()) // No tokens available?
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000766 return 0;
767
Ted Kremenekd8c02922009-02-10 22:16:22 +0000768 const PTHFileData& FileData = *I;
769
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000770 const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart();
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000771 // Compute the offset of the token data within the buffer.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000772 const unsigned char* data = BufStart + FileData.getTokenOffset();
Ted Kremenek268ee702008-12-12 18:34:08 +0000773
774 // Get the location of pp-conditional table.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000775 const unsigned char* ppcond = BufStart + FileData.getPPCondOffset();
Chris Lattner5ff43172009-01-22 19:48:26 +0000776 uint32_t Len = ReadLE32(ppcond);
Chris Lattner1b5285e2009-01-18 02:10:31 +0000777 if (Len == 0) ppcond = 0;
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000778
Ted Kremenek72b1b152009-01-15 18:47:46 +0000779 assert(PP && "No preprocessor set yet!");
Ted Kremenek277faca2009-01-27 00:01:05 +0000780 return new PTHLexer(*PP, FID, data, ppcond, *this);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000781}
Ted Kremenek337edcd2009-02-12 03:26:59 +0000782
783//===----------------------------------------------------------------------===//
784// 'stat' caching.
785//===----------------------------------------------------------------------===//
786
787namespace {
788class VISIBILITY_HIDDEN PTHStatData {
789public:
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000790 const bool hasStat;
Ted Kremenek337edcd2009-02-12 03:26:59 +0000791 const ino_t ino;
792 const dev_t dev;
793 const mode_t mode;
794 const time_t mtime;
795 const off_t size;
796
797 PTHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000798 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
799
800 PTHStatData()
801 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
Ted Kremenek337edcd2009-02-12 03:26:59 +0000802};
803
804class VISIBILITY_HIDDEN PTHStatLookupTrait : public PTHFileLookupCommonTrait {
805public:
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000806 typedef const char* external_key_type; // const char*
Ted Kremenek337edcd2009-02-12 03:26:59 +0000807 typedef PTHStatData data_type;
808
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000809 static internal_key_type GetInternalKey(const char *path) {
810 // The key 'kind' doesn't matter here because it is ignored in EqualKey.
811 return std::make_pair((unsigned char) 0x0, path);
812 }
813
814 static bool EqualKey(internal_key_type a, internal_key_type b) {
815 // When doing 'stat' lookups we don't care about the kind of 'a' and 'b',
816 // just the paths.
817 return strcmp(a.second, b.second) == 0;
818 }
Ted Kremenek337edcd2009-02-12 03:26:59 +0000819
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000820 static data_type ReadData(const internal_key_type& k, const unsigned char* d,
821 unsigned) {
Ted Kremenekad6ce5c2009-02-13 22:07:44 +0000822
823 if (k.first /* File or Directory */) {
824 if (k.first == 0x1 /* File */) d += 4 * 2; // Skip the first 2 words.
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000825 ino_t ino = (ino_t) ReadUnalignedLE32(d);
826 dev_t dev = (dev_t) ReadUnalignedLE32(d);
827 mode_t mode = (mode_t) ReadUnalignedLE16(d);
828 time_t mtime = (time_t) ReadUnalignedLE64(d);
829 return data_type(ino, dev, mode, mtime, (off_t) ReadUnalignedLE64(d));
830 }
Ted Kremenekad6ce5c2009-02-13 22:07:44 +0000831
832 // Negative stat. Don't read anything.
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000833 return data_type();
Ted Kremenek337edcd2009-02-12 03:26:59 +0000834 }
835};
Ted Kremenek337edcd2009-02-12 03:26:59 +0000836
837class VISIBILITY_HIDDEN PTHStatCache : public StatSysCallCache {
838 typedef OnDiskChainedHashTable<PTHStatLookupTrait> CacheTy;
839 CacheTy Cache;
840
841public:
842 PTHStatCache(PTHFileLookup &FL) :
843 Cache(FL.getNumBuckets(), FL.getNumEntries(), FL.getBuckets(),
844 FL.getBase()) {}
845
846 ~PTHStatCache() {}
847
848 int stat(const char *path, struct stat *buf) {
849 // Do the lookup for the file's data in the PTH file.
850 CacheTy::iterator I = Cache.find(path);
851
852 // If we don't get a hit in the PTH file just forward to 'stat'.
853 if (I == Cache.end()) return ::stat(path, buf);
854
855 const PTHStatData& Data = *I;
Ted Kremenekad6ce5c2009-02-13 22:07:44 +0000856
857 if (!Data.hasStat)
858 return 1;
859
Ted Kremenek337edcd2009-02-12 03:26:59 +0000860 buf->st_ino = Data.ino;
861 buf->st_dev = Data.dev;
862 buf->st_mtime = Data.mtime;
863 buf->st_mode = Data.mode;
864 buf->st_size = Data.size;
865 return 0;
866 }
867};
Ted Kremenekd5785692009-02-23 23:27:54 +0000868} // end anonymous namespace
Ted Kremenek337edcd2009-02-12 03:26:59 +0000869
870StatSysCallCache *PTHManager::createStatCache() {
Ted Kremenek5f747d12009-02-12 03:45:39 +0000871 return new PTHStatCache(*((PTHFileLookup*) FileLookup));
Ted Kremenek337edcd2009-02-12 03:26:59 +0000872}