blob: 9f878b630d432bc776808b7a95eb40b35c31330d [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 Kremenek274b2082008-11-12 21:37:15 +000028using namespace clang;
29
Ted Kremenek7b78b7c2009-01-19 23:13:15 +000030#define DISK_TOKEN_SIZE (1+1+2+4+4)
Ted Kremenek268ee702008-12-12 18:34:08 +000031
Ted Kremenek0c6a77b2008-12-03 00:38:03 +000032//===----------------------------------------------------------------------===//
33// Utility methods for reading from the mmap'ed PTH file.
34//===----------------------------------------------------------------------===//
35
Chris Lattner5ff43172009-01-22 19:48:26 +000036static inline uint16_t ReadUnalignedLE16(const unsigned char *&Data) {
Ted Kremenekd8c02922009-02-10 22:16:22 +000037 uint16_t V = ((uint16_t)Data[0]) |
Chris Lattnerda9d61c2009-01-18 01:57:14 +000038 ((uint16_t)Data[1] << 8);
39 Data += 2;
40 return V;
41}
42
Ted Kremenekd8c02922009-02-10 22:16:22 +000043static inline uint32_t ReadUnalignedLE32(const unsigned char *&Data) {
44 uint32_t V = ((uint32_t)Data[0]) |
45 ((uint32_t)Data[1] << 8) |
46 ((uint32_t)Data[2] << 16) |
47 ((uint32_t)Data[3] << 24);
48 Data += 4;
49 return V;
50}
51
Chris Lattner5ff43172009-01-22 19:48:26 +000052static inline uint32_t ReadLE32(const unsigned char *&Data) {
Chris Lattnerfbc33382009-01-23 00:13:28 +000053 // Hosts that directly support little-endian 32-bit loads can just
54 // use them. Big-endian hosts need a bswap.
Chris Lattnerf15674c2009-01-18 02:19:16 +000055 uint32_t V = *((uint32_t*)Data);
Chris Lattner6f78c3b2009-01-22 23:50:07 +000056 if (llvm::sys::isBigEndianHost())
57 V = llvm::ByteSwap_32(V);
Chris Lattnerda9d61c2009-01-18 01:57:14 +000058 Data += 4;
59 return V;
60}
61
Ted Kremenek7e3a0042009-02-11 21:29:16 +000062// Bernstein hash function:
63// This is basically copy-and-paste from StringMap. This likely won't
64// stay here, which is why I didn't both to expose this function from
65// String Map.
66static unsigned BernsteinHash(const char* x) {
67 unsigned int R = 0;
68 for ( ; *x != '\0' ; ++x) R = R * 33 + *x;
69 return R + (R >> 5);
70}
71
72static unsigned BernsteinHash(const char* x, unsigned n) {
73 unsigned int R = 0;
74 for (unsigned i = 0 ; i < n ; ++i, ++x) R = R * 33 + *x;
75 return R + (R >> 5);
76}
Chris Lattnerda9d61c2009-01-18 01:57:14 +000077
Ted Kremeneke5680f32008-12-23 01:30:52 +000078//===----------------------------------------------------------------------===//
79// PTHLexer methods.
80//===----------------------------------------------------------------------===//
81
Chris Lattnerda9d61c2009-01-18 01:57:14 +000082PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D,
Ted Kremenek277faca2009-01-27 00:01:05 +000083 const unsigned char *ppcond, PTHManager &PM)
Chris Lattner2b2453a2009-01-17 06:22:33 +000084 : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(0),
Ted Kremenek277faca2009-01-27 00:01:05 +000085 PPCond(ppcond), CurPPCondPtr(ppcond), PTHMgr(PM) {
Chris Lattner2b2453a2009-01-17 06:22:33 +000086
87 FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID);
Ted Kremenek5f074262009-01-09 22:05:30 +000088}
Ted Kremeneke5680f32008-12-23 01:30:52 +000089
90void PTHLexer::Lex(Token& Tok) {
91LexNextToken:
Ted Kremeneke5680f32008-12-23 01:30:52 +000092
Ted Kremenek866bdf72008-12-23 02:30:15 +000093 //===--------------------------------------==//
94 // Read the raw token data.
95 //===--------------------------------------==//
96
97 // Shadow CurPtr into an automatic variable.
Chris Lattneraff6ef82009-01-21 07:21:56 +000098 const unsigned char *CurPtrShadow = CurPtr;
Ted Kremenek866bdf72008-12-23 02:30:15 +000099
Chris Lattner1b5285e2009-01-18 02:10:31 +0000100 // Read in the data for the token.
Chris Lattner5ff43172009-01-22 19:48:26 +0000101 unsigned Word0 = ReadLE32(CurPtrShadow);
102 uint32_t IdentifierID = ReadLE32(CurPtrShadow);
103 uint32_t FileOffset = ReadLE32(CurPtrShadow);
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000104
105 tok::TokenKind TKind = (tok::TokenKind) (Word0 & 0xFF);
106 Token::TokenFlags TFlags = (Token::TokenFlags) ((Word0 >> 8) & 0xFF);
Chris Lattneraff6ef82009-01-21 07:21:56 +0000107 uint32_t Len = Word0 >> 16;
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000108
Chris Lattneraff6ef82009-01-21 07:21:56 +0000109 CurPtr = CurPtrShadow;
Ted Kremenek866bdf72008-12-23 02:30:15 +0000110
111 //===--------------------------------------==//
112 // Construct the token itself.
113 //===--------------------------------------==//
114
115 Tok.startToken();
Chris Lattner898a0bb2009-01-18 02:34:01 +0000116 Tok.setKind(TKind);
117 Tok.setFlag(TFlags);
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000118 assert(!LexingRawMode);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000119 Tok.setLocation(FileStartLoc.getFileLocWithOffset(FileOffset));
Ted Kremenek866bdf72008-12-23 02:30:15 +0000120 Tok.setLength(Len);
121
Chris Lattnerd0a69692009-01-21 07:50:06 +0000122 // Handle identifiers.
Ted Kremenek277faca2009-01-27 00:01:05 +0000123 if (Tok.isLiteral()) {
124 Tok.setLiteralData((const char*) (PTHMgr.SpellingBase + IdentifierID));
125 }
126 else if (IdentifierID) {
Chris Lattnerd0a69692009-01-21 07:50:06 +0000127 MIOpt.ReadToken();
128 IdentifierInfo *II = PTHMgr.GetIdentifierInfo(IdentifierID-1);
Chris Lattner863c4862009-01-23 18:35:48 +0000129
Chris Lattnerd0a69692009-01-21 07:50:06 +0000130 Tok.setIdentifierInfo(II);
Chris Lattner863c4862009-01-23 18:35:48 +0000131
132 // Change the kind of this identifier to the appropriate token kind, e.g.
133 // turning "for" into a keyword.
134 Tok.setKind(II->getTokenID());
135
Chris Lattnerd0a69692009-01-21 07:50:06 +0000136 if (II->isHandleIdentifierCase())
137 PP->HandleIdentifier(Tok);
138 return;
139 }
140
Ted Kremenek866bdf72008-12-23 02:30:15 +0000141 //===--------------------------------------==//
142 // Process the token.
143 //===--------------------------------------==//
Ted Kremenek5f074262009-01-09 22:05:30 +0000144#if 0
145 SourceManager& SM = PP->getSourceManager();
146 llvm::cerr << SM.getFileEntryForID(FileID)->getName()
147 << ':' << SM.getLogicalLineNumber(Tok.getLocation())
148 << ':' << SM.getLogicalColumnNumber(Tok.getLocation())
149 << '\n';
150#endif
Ted Kremeneke5680f32008-12-23 01:30:52 +0000151
Chris Lattner898a0bb2009-01-18 02:34:01 +0000152 if (TKind == tok::eof) {
Ted Kremeneke5680f32008-12-23 01:30:52 +0000153 // Save the end-of-file token.
154 EofToken = Tok;
155
156 Preprocessor *PPCache = PP;
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000157
158 assert(!ParsingPreprocessorDirective);
159 assert(!LexingRawMode);
160
161 // FIXME: Issue diagnostics similar to Lexer.
162 if (PP->HandleEndOfFile(Tok, false))
Ted Kremeneke5680f32008-12-23 01:30:52 +0000163 return;
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000164
Ted Kremeneke5680f32008-12-23 01:30:52 +0000165 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
166 return PPCache->Lex(Tok);
167 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000168
Chris Lattner898a0bb2009-01-18 02:34:01 +0000169 if (TKind == tok::hash && Tok.isAtStartOfLine()) {
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000170 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
171 assert(!LexingRawMode);
172 PP->HandleDirective(Tok);
173
174 if (PP->isCurrentLexer(this))
175 goto LexNextToken;
176
177 return PP->Lex(Tok);
178 }
179
Chris Lattner898a0bb2009-01-18 02:34:01 +0000180 if (TKind == tok::eom) {
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000181 assert(ParsingPreprocessorDirective);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000182 ParsingPreprocessorDirective = false;
183 return;
184 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000185
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000186 MIOpt.ReadToken();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000187}
188
189// FIXME: We can just grab the last token instead of storing a copy
190// into EofToken.
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000191void PTHLexer::getEOF(Token& Tok) {
Ted Kremenekdefb7092009-01-09 00:36:11 +0000192 assert(EofToken.is(tok::eof));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000193 Tok = EofToken;
194}
195
196void PTHLexer::DiscardToEndOfLine() {
197 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
198 "Must be in a preprocessing directive!");
199
200 // We assume that if the preprocessor wishes to discard to the end of
201 // the line that it also means to end the current preprocessor directive.
202 ParsingPreprocessorDirective = false;
203
204 // Skip tokens by only peeking at their token kind and the flags.
205 // We don't need to actually reconstruct full tokens from the token buffer.
206 // This saves some copies and it also reduces IdentifierInfo* lookup.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000207 const unsigned char* p = CurPtr;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000208 while (1) {
209 // Read the token kind. Are we at the end of the file?
210 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
211 if (x == tok::eof) break;
212
213 // Read the token flags. Are we at the start of the next line?
214 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
215 if (y & Token::StartOfLine) break;
216
217 // Skip to the next token.
218 p += DISK_TOKEN_SIZE;
219 }
220
221 CurPtr = p;
222}
223
Ted Kremenek268ee702008-12-12 18:34:08 +0000224/// SkipBlock - Used by Preprocessor to skip the current conditional block.
225bool PTHLexer::SkipBlock() {
226 assert(CurPPCondPtr && "No cached PP conditional information.");
227 assert(LastHashTokPtr && "No known '#' token.");
228
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000229 const unsigned char* HashEntryI = 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000230 uint32_t Offset;
231 uint32_t TableIdx;
232
233 do {
Ted Kremenek41a26602008-12-12 22:05:38 +0000234 // Read the token offset from the side-table.
Chris Lattner5ff43172009-01-22 19:48:26 +0000235 Offset = ReadLE32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000236
237 // Read the target table index from the side-table.
Chris Lattner5ff43172009-01-22 19:48:26 +0000238 TableIdx = ReadLE32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000239
240 // Compute the actual memory address of the '#' token data for this entry.
241 HashEntryI = TokBuf + Offset;
242
243 // Optmization: "Sibling jumping". #if...#else...#endif blocks can
244 // contain nested blocks. In the side-table we can jump over these
245 // nested blocks instead of doing a linear search if the next "sibling"
246 // entry is not at a location greater than LastHashTokPtr.
247 if (HashEntryI < LastHashTokPtr && TableIdx) {
248 // In the side-table we are still at an entry for a '#' token that
249 // is earlier than the last one we saw. Check if the location we would
250 // stride gets us closer.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000251 const unsigned char* NextPPCondPtr =
252 PPCond + TableIdx*(sizeof(uint32_t)*2);
Ted Kremenek41a26602008-12-12 22:05:38 +0000253 assert(NextPPCondPtr >= CurPPCondPtr);
254 // Read where we should jump to.
Chris Lattner5ff43172009-01-22 19:48:26 +0000255 uint32_t TmpOffset = ReadLE32(NextPPCondPtr);
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000256 const unsigned char* HashEntryJ = TokBuf + TmpOffset;
Ted Kremenek41a26602008-12-12 22:05:38 +0000257
258 if (HashEntryJ <= LastHashTokPtr) {
259 // Jump directly to the next entry in the side table.
260 HashEntryI = HashEntryJ;
261 Offset = TmpOffset;
Chris Lattner5ff43172009-01-22 19:48:26 +0000262 TableIdx = ReadLE32(NextPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000263 CurPPCondPtr = NextPPCondPtr;
264 }
265 }
Ted Kremenek268ee702008-12-12 18:34:08 +0000266 }
Ted Kremenek41a26602008-12-12 22:05:38 +0000267 while (HashEntryI < LastHashTokPtr);
268 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
Ted Kremenek268ee702008-12-12 18:34:08 +0000269 assert(TableIdx && "No jumping from #endifs.");
270
271 // Update our side-table iterator.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000272 const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
Ted Kremenek268ee702008-12-12 18:34:08 +0000273 assert(NextPPCondPtr >= CurPPCondPtr);
274 CurPPCondPtr = NextPPCondPtr;
275
276 // Read where we should jump to.
Chris Lattner5ff43172009-01-22 19:48:26 +0000277 HashEntryI = TokBuf + ReadLE32(NextPPCondPtr);
278 uint32_t NextIdx = ReadLE32(NextPPCondPtr);
Ted Kremenek268ee702008-12-12 18:34:08 +0000279
280 // By construction NextIdx will be zero if this is a #endif. This is useful
281 // to know to obviate lexing another token.
282 bool isEndif = NextIdx == 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000283
284 // This case can occur when we see something like this:
285 //
286 // #if ...
287 // /* a comment or nothing */
288 // #elif
289 //
290 // If we are skipping the first #if block it will be the case that CurPtr
291 // already points 'elif'. Just return.
292
Ted Kremenek41a26602008-12-12 22:05:38 +0000293 if (CurPtr > HashEntryI) {
294 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
Ted Kremenek268ee702008-12-12 18:34:08 +0000295 // Did we reach a #endif? If so, go ahead and consume that token as well.
296 if (isEndif)
Ted Kremeneke5680f32008-12-23 01:30:52 +0000297 CurPtr += DISK_TOKEN_SIZE*2;
Ted Kremenek268ee702008-12-12 18:34:08 +0000298 else
Ted Kremenek41a26602008-12-12 22:05:38 +0000299 LastHashTokPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000300
301 return isEndif;
302 }
303
304 // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
Ted Kremenek41a26602008-12-12 22:05:38 +0000305 CurPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000306
307 // Update the location of the last observed '#'. This is useful if we
308 // are skipping multiple blocks.
309 LastHashTokPtr = CurPtr;
Ted Kremenek268ee702008-12-12 18:34:08 +0000310
Ted Kremeneke5680f32008-12-23 01:30:52 +0000311 // Skip the '#' token.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000312 assert(((tok::TokenKind)*CurPtr) == tok::hash);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000313 CurPtr += DISK_TOKEN_SIZE;
314
Ted Kremenek268ee702008-12-12 18:34:08 +0000315 // Did we reach a #endif? If so, go ahead and consume that token as well.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000316 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
Ted Kremenek268ee702008-12-12 18:34:08 +0000317
318 return isEndif;
319}
320
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000321SourceLocation PTHLexer::getSourceLocation() {
Chris Lattner1b5285e2009-01-18 02:10:31 +0000322 // getSourceLocation is not on the hot path. It is used to get the location
323 // of the next token when transitioning back to this lexer when done
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000324 // handling a #included file. Just read the necessary data from the token
325 // data buffer to construct the SourceLocation object.
326 // NOTE: This is a virtual function; hence it is defined out-of-line.
Ted Kremenekb248d532009-01-21 22:41:38 +0000327 const unsigned char *OffsetPtr = CurPtr + (DISK_TOKEN_SIZE - 4);
Chris Lattner5ff43172009-01-22 19:48:26 +0000328 uint32_t Offset = ReadLE32(OffsetPtr);
Chris Lattner1b5285e2009-01-18 02:10:31 +0000329 return FileStartLoc.getFileLocWithOffset(Offset);
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000330}
331
Ted Kremenek5f074262009-01-09 22:05:30 +0000332//===----------------------------------------------------------------------===//
Ted Kremenekd8c02922009-02-10 22:16:22 +0000333// OnDiskChainedHashTable
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000334//===----------------------------------------------------------------------===//
335
Ted Kremenekd8c02922009-02-10 22:16:22 +0000336template<typename Info>
337class OnDiskChainedHashTable {
338 const unsigned NumBuckets;
339 const unsigned NumEntries;
340 const unsigned char* const Buckets;
341 const unsigned char* const Base;
342public:
343 typedef typename Info::internal_key_type internal_key_type;
344 typedef typename Info::external_key_type external_key_type;
345 typedef typename Info::data_type data_type;
346
347 OnDiskChainedHashTable(unsigned numBuckets, unsigned numEntries,
348 const unsigned char* buckets,
349 const unsigned char* base)
350 : NumBuckets(numBuckets), NumEntries(numEntries),
351 Buckets(buckets), Base(base) {
352 assert((reinterpret_cast<uintptr_t>(buckets) & 0x3) == 0 &&
353 "'buckets' must have a 4-byte alignment");
354 }
355
356
357 bool isEmpty() const { return NumEntries == 0; }
358
359 class iterator {
360 const unsigned char* const data;
361 const unsigned len;
362 public:
363 iterator() : data(0), len(0) {}
364 iterator(const unsigned char* d, unsigned l) : data(d), len(l) {}
365
366 data_type operator*() const { return Info::ReadData(data, len); }
367 bool operator==(const iterator& X) const { return X.data == data; }
368 bool operator!=(const iterator& X) const { return X.data != data; }
369 };
370
371 iterator find(const external_key_type& eKey) {
372 const internal_key_type& iKey = Info::GetInternalKey(eKey);
373 unsigned key_hash = Info::ComputeHash(iKey);
374
375 // Each bucket is just a 32-bit offset into the PTH file.
376 unsigned idx = key_hash & (NumBuckets - 1);
377 const unsigned char* Bucket = Buckets + sizeof(uint32_t)*idx;
378
379 unsigned offset = ReadLE32(Bucket);
380 if (offset == 0) return iterator(); // Empty bucket.
381 const unsigned char* Items = Base + offset;
382
383 // 'Items' starts with a 16-bit unsigned integer representing the
384 // number of items in this bucket.
385 unsigned len = ReadUnalignedLE16(Items);
386
387 for (unsigned i = 0; i < len; ++i) {
388 // Read the hash.
389 uint32_t item_hash = ReadUnalignedLE32(Items);
390
391 // Determine the length of the key and the data.
392 const std::pair<unsigned, unsigned>& L = Info::ReadKeyDataLength(Items);
393 unsigned item_len = L.first + L.second;
394
395 // Compare the hashes. If they are not the same, skip the entry entirely.
396 if (item_hash != key_hash) {
397 Items += item_len;
398 continue;
399 }
400
401 // Read the key.
402 const internal_key_type& X =
403 Info::ReadKey((const unsigned char* const) Items, L.first);
404
405 // If the key doesn't match just skip reading the value.
406 if (!Info::EqualKey(X, iKey)) {
407 Items += item_len;
408 continue;
409 }
410
411 // The key matches!
412 return iterator(Items + L.first, L.second);
413 }
414
415 return iterator();
416 }
417
418 iterator end() const { return iterator(); }
419
420
421 static OnDiskChainedHashTable* Create(const unsigned char* buckets,
422 const unsigned char* const base) {
423
424 assert(buckets > base);
425 assert((reinterpret_cast<uintptr_t>(buckets) & 0x3) == 0 &&
426 "buckets should be 4-byte aligned.");
427
428 unsigned numBuckets = ReadLE32(buckets);
429 unsigned numEntries = ReadLE32(buckets);
430 return new OnDiskChainedHashTable<Info>(numBuckets, numEntries, buckets,
431 base);
432 }
433};
434
435//===----------------------------------------------------------------------===//
436// PTH file lookup: map from strings to file data.
437//===----------------------------------------------------------------------===//
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000438
439/// PTHFileLookup - This internal data structure is used by the PTHManager
440/// to map from FileEntry objects managed by FileManager to offsets within
441/// the PTH file.
442namespace {
Ted Kremenekd8c02922009-02-10 22:16:22 +0000443class VISIBILITY_HIDDEN PTHFileData {
444 const uint32_t TokenOff;
445 const uint32_t PPCondOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000446public:
Ted Kremenekd8c02922009-02-10 22:16:22 +0000447 PTHFileData(uint32_t tokenOff, uint32_t ppCondOff)
448 : TokenOff(tokenOff), PPCondOff(ppCondOff) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000449
Ted Kremenekd8c02922009-02-10 22:16:22 +0000450 uint32_t getTokenOffset() const { return TokenOff; }
451 uint32_t getPPCondOffset() const { return PPCondOff; }
452};
453
454class VISIBILITY_HIDDEN PTHFileLookupTrait {
455public:
456 typedef PTHFileData data_type;
457 typedef const FileEntry* external_key_type;
458 typedef const char* internal_key_type;
459
460 static bool EqualKey(const char* a, const char* b) {
461 return strcmp(a, b) == 0;
462 }
Chris Lattner1b5285e2009-01-18 02:10:31 +0000463
Ted Kremenekd8c02922009-02-10 22:16:22 +0000464 static unsigned ComputeHash(const char* x) {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000465 return BernsteinHash(x);
Ted Kremenekd8c02922009-02-10 22:16:22 +0000466 }
467
468 static const char* GetInternalKey(const FileEntry* FE) {
469 return FE->getName();
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000470 }
471
Ted Kremenekd8c02922009-02-10 22:16:22 +0000472 static std::pair<unsigned, unsigned>
473 ReadKeyDataLength(const unsigned char*& d) {
474 return std::make_pair((unsigned) ReadUnalignedLE16(d), 8U);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000475 }
476
Ted Kremenekd8c02922009-02-10 22:16:22 +0000477 static const char* ReadKey(const unsigned char* d, unsigned) {
478 return (const char*) d;
479 }
480
481 static PTHFileData ReadData(const unsigned char* d, unsigned) {
482 uint32_t x = ::ReadUnalignedLE32(d);
483 uint32_t y = ::ReadUnalignedLE32(d);
484 return PTHFileData(x, y);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000485 }
486};
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000487
488class VISIBILITY_HIDDEN PTHStringLookupTrait {
489public:
490 typedef uint32_t
491 data_type;
492
493 typedef const std::pair<const char*, unsigned>
494 external_key_type;
495
496 typedef external_key_type internal_key_type;
497
498 static bool EqualKey(const internal_key_type& a,
499 const internal_key_type& b) {
500 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
501 : false;
502 }
503
504 static unsigned ComputeHash(const internal_key_type& a) {
505 return BernsteinHash(a.first, a.second);
506 }
507
508 // This hopefully will just get inlined and removed by the optimizer.
509 static const internal_key_type&
510 GetInternalKey(const external_key_type& x) { return x; }
511
512 static std::pair<unsigned, unsigned>
513 ReadKeyDataLength(const unsigned char*& d) {
514 return std::make_pair((unsigned) ReadUnalignedLE16(d), sizeof(uint32_t));
515 }
516
517 static std::pair<const char*, unsigned>
518 ReadKey(const unsigned char* d, unsigned n) {
519 assert(n >= 2 && d[n-1] == '\0');
520 return std::make_pair((const char*) d, n-1);
521 }
522
523 static uint32_t ReadData(const unsigned char* d, unsigned) {
524 return ::ReadUnalignedLE32(d);
525 }
526};
527
Ted Kremenekd8c02922009-02-10 22:16:22 +0000528} // end anonymous namespace
529
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000530typedef OnDiskChainedHashTable<PTHFileLookupTrait> PTHFileLookup;
531typedef OnDiskChainedHashTable<PTHStringLookupTrait> PTHStringIdLookup;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000532
533//===----------------------------------------------------------------------===//
534// PTHManager methods.
535//===----------------------------------------------------------------------===//
536
537PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000538 const unsigned char* idDataTable,
539 IdentifierInfo** perIDCache,
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000540 void* stringIdLookup, unsigned numIds,
Ted Kremenek277faca2009-01-27 00:01:05 +0000541 const unsigned char* spellingBase)
Ted Kremenek6183e482008-12-03 01:16:39 +0000542: Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000543 IdDataTable(idDataTable), StringIdLookup(stringIdLookup),
Ted Kremenek277faca2009-01-27 00:01:05 +0000544 NumIds(numIds), PP(0), SpellingBase(spellingBase) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000545
546PTHManager::~PTHManager() {
547 delete Buf;
548 delete (PTHFileLookup*) FileLookup;
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000549 delete (PTHStringIdLookup*) StringIdLookup;
Ted Kremenek0e50b6e2008-12-04 22:47:11 +0000550 free(PerIDCache);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000551}
552
Ted Kremenek26555b12009-01-28 21:02:43 +0000553static void InvalidPTH(Diagnostic *Diags, const char* Msg = 0) {
554 if (!Diags) return;
555 if (!Msg) Msg = "Invalid or corrupted PTH file";
556 unsigned DiagID = Diags->getCustomDiagID(Diagnostic::Note, Msg);
557 Diags->Report(FullSourceLoc(), DiagID);
558}
559
Ted Kremenek8a6aec62009-01-28 20:49:33 +0000560PTHManager* PTHManager::Create(const std::string& file, Diagnostic* Diags) {
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000561 // Memory map the PTH file.
562 llvm::OwningPtr<llvm::MemoryBuffer>
563 File(llvm::MemoryBuffer::getFile(file.c_str()));
564
Ted Kremenek8a6aec62009-01-28 20:49:33 +0000565 if (!File) {
566 if (Diags) {
567 unsigned DiagID = Diags->getCustomDiagID(Diagnostic::Note,
568 "PTH file %0 could not be read");
569 Diags->Report(FullSourceLoc(), DiagID) << file;
570 }
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000571
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000572 return 0;
Ted Kremenek8a6aec62009-01-28 20:49:33 +0000573 }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000574
575 // Get the buffer ranges and check if there are at least three 32-bit
576 // words at the end of the file.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000577 const unsigned char* BufBeg = (unsigned char*)File->getBufferStart();
578 const unsigned char* BufEnd = (unsigned char*)File->getBufferEnd();
Ted Kremeneke1b64982009-01-26 21:43:14 +0000579
580 // Check the prologue of the file.
Ted Kremenek4adc71a2009-01-26 22:16:12 +0000581 if ((BufEnd - BufBeg) < (signed) (sizeof("cfe-pth") + 3 + 4) ||
Ted Kremenek26555b12009-01-28 21:02:43 +0000582 memcmp(BufBeg, "cfe-pth", sizeof("cfe-pth") - 1) != 0) {
583 InvalidPTH(Diags);
Ted Kremeneke1b64982009-01-26 21:43:14 +0000584 return 0;
Ted Kremenek26555b12009-01-28 21:02:43 +0000585 }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000586
Ted Kremenek67d15052009-01-26 21:50:21 +0000587 // Read the PTH version.
Ted Kremeneke1b64982009-01-26 21:43:14 +0000588 const unsigned char *p = BufBeg + (sizeof("cfe-pth") - 1);
Ted Kremenek67d15052009-01-26 21:50:21 +0000589 unsigned Version = ReadLE32(p);
590
Ted Kremenek26555b12009-01-28 21:02:43 +0000591 if (Version != PTHManager::Version) {
592 InvalidPTH(Diags,
593 Version < PTHManager::Version
594 ? "PTH file uses an older PTH format that is no longer supported"
595 : "PTH file uses a newer PTH format that cannot be read");
Ted Kremenek67d15052009-01-26 21:50:21 +0000596 return 0;
Ted Kremenek26555b12009-01-28 21:02:43 +0000597 }
Ted Kremenek67d15052009-01-26 21:50:21 +0000598
599 // Compute the address of the index table at the end of the PTH file.
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000600 const unsigned char *PrologueOffset = p;
Ted Kremeneke1b64982009-01-26 21:43:14 +0000601
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000602 if (PrologueOffset >= BufEnd) {
Ted Kremenek26555b12009-01-28 21:02:43 +0000603 InvalidPTH(Diags);
Ted Kremeneke1b64982009-01-26 21:43:14 +0000604 return 0;
Ted Kremenek26555b12009-01-28 21:02:43 +0000605 }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000606
607 // Construct the file lookup table. This will be used for mapping from
608 // FileEntry*'s to cached tokens.
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000609 const unsigned char* FileTableOffset = PrologueOffset + sizeof(uint32_t)*2;
Chris Lattner5ff43172009-01-22 19:48:26 +0000610 const unsigned char* FileTable = BufBeg + ReadLE32(FileTableOffset);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000611
612 if (!(FileTable > BufBeg && FileTable < BufEnd)) {
Ted Kremenek26555b12009-01-28 21:02:43 +0000613 InvalidPTH(Diags);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000614 return 0; // FIXME: Proper error diagnostic?
615 }
616
Ted Kremenekd8c02922009-02-10 22:16:22 +0000617 llvm::OwningPtr<PTHFileLookup> FL(PTHFileLookup::Create(FileTable, BufBeg));
Ted Kremenek26555b12009-01-28 21:02:43 +0000618 if (FL->isEmpty()) {
619 InvalidPTH(Diags, "PTH file contains no cached source data");
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000620 return 0;
Ted Kremenek26555b12009-01-28 21:02:43 +0000621 }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000622
623 // Get the location of the table mapping from persistent ids to the
624 // data needed to reconstruct identifiers.
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000625 const unsigned char* IDTableOffset = PrologueOffset + sizeof(uint32_t)*0;
Chris Lattner5ff43172009-01-22 19:48:26 +0000626 const unsigned char* IData = BufBeg + ReadLE32(IDTableOffset);
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000627
628 if (!(IData >= BufBeg && IData < BufEnd)) {
Ted Kremenek26555b12009-01-28 21:02:43 +0000629 InvalidPTH(Diags);
630 return 0;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000631 }
632
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000633 // Get the location of the hashtable mapping between strings and
634 // persistent IDs.
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000635 const unsigned char* StringIdTableOffset = PrologueOffset + sizeof(uint32_t)*1;
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000636 const unsigned char* StringIdTable = BufBeg + ReadLE32(StringIdTableOffset);
637 if (!(StringIdTable >= BufBeg && StringIdTable < BufEnd)) {
Ted Kremenek26555b12009-01-28 21:02:43 +0000638 InvalidPTH(Diags);
639 return 0;
Ted Kremenek72b1b152009-01-15 18:47:46 +0000640 }
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000641
642 llvm::OwningPtr<PTHStringIdLookup> SL(PTHStringIdLookup::Create(StringIdTable,
643 BufBeg));
644 if (SL->isEmpty()) {
645 InvalidPTH(Diags, "PTH file contains no identifiers.");
646 return 0;
647 }
Ted Kremenek72b1b152009-01-15 18:47:46 +0000648
Ted Kremenek277faca2009-01-27 00:01:05 +0000649 // Get the location of the spelling cache.
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000650 const unsigned char* spellingBaseOffset = PrologueOffset + sizeof(uint32_t)*3;
Ted Kremenek277faca2009-01-27 00:01:05 +0000651 const unsigned char* spellingBase = BufBeg + ReadLE32(spellingBaseOffset);
652 if (!(spellingBase >= BufBeg && spellingBase < BufEnd)) {
Ted Kremenek26555b12009-01-28 21:02:43 +0000653 InvalidPTH(Diags);
Ted Kremenek277faca2009-01-27 00:01:05 +0000654 return 0;
655 }
656
Ted Kremenek6183e482008-12-03 01:16:39 +0000657 // Get the number of IdentifierInfos and pre-allocate the identifier cache.
Chris Lattner5ff43172009-01-22 19:48:26 +0000658 uint32_t NumIds = ReadLE32(IData);
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000659
Ted Kremenek6183e482008-12-03 01:16:39 +0000660 // Pre-allocate the peristent ID -> IdentifierInfo* cache. We use calloc()
661 // so that we in the best case only zero out memory once when the OS returns
662 // us new pages.
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000663 IdentifierInfo** PerIDCache = 0;
Ted Kremenek6183e482008-12-03 01:16:39 +0000664
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000665 if (NumIds) {
666 PerIDCache = (IdentifierInfo**)calloc(NumIds, sizeof(*PerIDCache));
667 if (!PerIDCache) {
Ted Kremenek26555b12009-01-28 21:02:43 +0000668 InvalidPTH(Diags, "Could not allocate memory for processing PTH file");
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000669 return 0;
670 }
Ted Kremenek6183e482008-12-03 01:16:39 +0000671 }
Ted Kremenekcdd8f212009-01-21 07:34:28 +0000672
Ted Kremenek72b1b152009-01-15 18:47:46 +0000673 // Create the new PTHManager.
674 return new PTHManager(File.take(), FL.take(), IData, PerIDCache,
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000675 SL.take(), NumIds, spellingBase);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000676}
Chris Lattner77ecb3a2009-01-18 02:57:21 +0000677IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) {
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000678 // Look in the PTH file for the string data for the IdentifierInfo object.
Chris Lattner77ecb3a2009-01-18 02:57:21 +0000679 const unsigned char* TableEntry = IdDataTable + sizeof(uint32_t)*PersistentID;
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000680 const unsigned char* IDData =
Chris Lattner5ff43172009-01-22 19:48:26 +0000681 (const unsigned char*)Buf->getBufferStart() + ReadLE32(TableEntry);
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000682 assert(IDData < (const unsigned char*)Buf->getBufferEnd());
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000683
Ted Kremenek72b1b152009-01-15 18:47:46 +0000684 // Allocate the object.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000685 std::pair<IdentifierInfo,const unsigned char*> *Mem =
686 Alloc.Allocate<std::pair<IdentifierInfo,const unsigned char*> >();
Ted Kremenek72b1b152009-01-15 18:47:46 +0000687
688 Mem->second = IDData;
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000689 assert(IDData[0] != '\0');
Ted Kremenekea9c26b2009-01-20 23:28:34 +0000690 IdentifierInfo *II = new ((void*) Mem) IdentifierInfo();
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000691
Ted Kremenek72b1b152009-01-15 18:47:46 +0000692 // Store the new IdentifierInfo in the cache.
Chris Lattner77ecb3a2009-01-18 02:57:21 +0000693 PerIDCache[PersistentID] = II;
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000694 assert(II->getName() && II->getName()[0] != '\0');
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000695 return II;
696}
697
Ted Kremenek72b1b152009-01-15 18:47:46 +0000698IdentifierInfo* PTHManager::get(const char *NameStart, const char *NameEnd) {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000699 PTHStringIdLookup& SL = *((PTHStringIdLookup*)StringIdLookup);
700 // Double check our assumption that the last character isn't '\0'.
701 assert(NameStart[NameEnd-NameStart-1] != '\0');
702 PTHStringIdLookup::iterator I = SL.find(std::make_pair(NameStart,
703 NameEnd - NameStart));
704 if (I == SL.end()) // No identifier found?
705 return 0;
Ted Kremenek72b1b152009-01-15 18:47:46 +0000706
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000707 // Match found. Return the identifier!
708 assert(*I > 0);
709 return GetIdentifierInfo(*I-1);
710}
Ted Kremenek72b1b152009-01-15 18:47:46 +0000711
Chris Lattnerf056d922009-01-17 08:06:50 +0000712PTHLexer *PTHManager::CreateLexer(FileID FID) {
713 const FileEntry *FE = PP->getSourceManager().getFileEntryForID(FID);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000714 if (!FE)
715 return 0;
716
717 // Lookup the FileEntry object in our file lookup data structure. It will
718 // return a variant that indicates whether or not there is an offset within
719 // the PTH file that contains cached tokens.
Ted Kremenekd8c02922009-02-10 22:16:22 +0000720 PTHFileLookup& PFL = *((PTHFileLookup*)FileLookup);
721 PTHFileLookup::iterator I = PFL.find(FE);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000722
Ted Kremenekd8c02922009-02-10 22:16:22 +0000723 if (I == PFL.end()) // No tokens available?
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000724 return 0;
725
Ted Kremenekd8c02922009-02-10 22:16:22 +0000726 const PTHFileData& FileData = *I;
727
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000728 const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart();
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000729 // Compute the offset of the token data within the buffer.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000730 const unsigned char* data = BufStart + FileData.getTokenOffset();
Ted Kremenek268ee702008-12-12 18:34:08 +0000731
732 // Get the location of pp-conditional table.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000733 const unsigned char* ppcond = BufStart + FileData.getPPCondOffset();
Chris Lattner5ff43172009-01-22 19:48:26 +0000734 uint32_t Len = ReadLE32(ppcond);
Chris Lattner1b5285e2009-01-18 02:10:31 +0000735 if (Len == 0) ppcond = 0;
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000736
Ted Kremenek72b1b152009-01-15 18:47:46 +0000737 assert(PP && "No preprocessor set yet!");
Ted Kremenek277faca2009-01-27 00:01:05 +0000738 return new PTHLexer(*PP, FID, data, ppcond, *this);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000739}