blob: 4231f2a915f5c331b8599e31605ec1228a62dd31 [file] [log] [blame]
Ted Kremenekca820862008-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 Kremenek325cd302008-12-03 00:38:03 +000014#include "clang/Basic/TokenKinds.h"
15#include "clang/Basic/FileManager.h"
16#include "clang/Basic/IdentifierTable.h"
Ted Kremenekca820862008-11-12 21:37:15 +000017#include "clang/Lex/PTHLexer.h"
18#include "clang/Lex/Preprocessor.h"
Ted Kremenek325cd302008-12-03 00:38:03 +000019#include "clang/Lex/PTHManager.h"
20#include "clang/Lex/Token.h"
21#include "clang/Lex/Preprocessor.h"
Ted Kremenek325cd302008-12-03 00:38:03 +000022#include "llvm/ADT/StringMap.h"
23#include "llvm/ADT/OwningPtr.h"
Chris Lattner6b0f1c72009-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 Kremenekca820862008-11-12 21:37:15 +000028using namespace clang;
29
Ted Kremenekb8344ef2009-01-19 23:13:15 +000030#define DISK_TOKEN_SIZE (1+1+2+4+4)
Ted Kremenekc07091c2008-12-12 18:34:08 +000031
Ted Kremenek325cd302008-12-03 00:38:03 +000032//===----------------------------------------------------------------------===//
33// Utility methods for reading from the mmap'ed PTH file.
34//===----------------------------------------------------------------------===//
35
Chris Lattner673a2862009-01-22 19:48:26 +000036static inline uint16_t ReadUnalignedLE16(const unsigned char *&Data) {
Ted Kremenekab6c4882009-02-10 22:16:22 +000037 uint16_t V = ((uint16_t)Data[0]) |
Chris Lattnerefb35342009-01-18 01:57:14 +000038 ((uint16_t)Data[1] << 8);
39 Data += 2;
40 return V;
41}
42
Ted Kremenekab6c4882009-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 Lattner673a2862009-01-22 19:48:26 +000052static inline uint32_t ReadLE32(const unsigned char *&Data) {
Chris Lattner007c4dc2009-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 Lattner5bffcaf2009-01-18 02:19:16 +000055 uint32_t V = *((uint32_t*)Data);
Chris Lattner6b0f1c72009-01-22 23:50:07 +000056 if (llvm::sys::isBigEndianHost())
57 V = llvm::ByteSwap_32(V);
Chris Lattnerefb35342009-01-18 01:57:14 +000058 Data += 4;
59 return V;
60}
61
62
Ted Kremenek9ab79bf2008-12-23 01:30:52 +000063//===----------------------------------------------------------------------===//
64// PTHLexer methods.
65//===----------------------------------------------------------------------===//
66
Chris Lattnerefb35342009-01-18 01:57:14 +000067PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D,
Ted Kremenek562db7f2009-01-27 00:01:05 +000068 const unsigned char *ppcond, PTHManager &PM)
Chris Lattnerf4f776a2009-01-17 06:22:33 +000069 : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(0),
Ted Kremenek562db7f2009-01-27 00:01:05 +000070 PPCond(ppcond), CurPPCondPtr(ppcond), PTHMgr(PM) {
Chris Lattnerf4f776a2009-01-17 06:22:33 +000071
72 FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID);
Ted Kremenekd310fde2009-01-09 22:05:30 +000073}
Ted Kremenek9ab79bf2008-12-23 01:30:52 +000074
75void PTHLexer::Lex(Token& Tok) {
76LexNextToken:
Ted Kremenek9ab79bf2008-12-23 01:30:52 +000077
Ted Kremenek08d3ff32008-12-23 02:30:15 +000078 //===--------------------------------------==//
79 // Read the raw token data.
80 //===--------------------------------------==//
81
82 // Shadow CurPtr into an automatic variable.
Chris Lattnerddf3b792009-01-21 07:21:56 +000083 const unsigned char *CurPtrShadow = CurPtr;
Ted Kremenek08d3ff32008-12-23 02:30:15 +000084
Chris Lattner0a6ec5d2009-01-18 02:10:31 +000085 // Read in the data for the token.
Chris Lattner673a2862009-01-22 19:48:26 +000086 unsigned Word0 = ReadLE32(CurPtrShadow);
87 uint32_t IdentifierID = ReadLE32(CurPtrShadow);
88 uint32_t FileOffset = ReadLE32(CurPtrShadow);
Ted Kremenekb8344ef2009-01-19 23:13:15 +000089
90 tok::TokenKind TKind = (tok::TokenKind) (Word0 & 0xFF);
91 Token::TokenFlags TFlags = (Token::TokenFlags) ((Word0 >> 8) & 0xFF);
Chris Lattnerddf3b792009-01-21 07:21:56 +000092 uint32_t Len = Word0 >> 16;
Ted Kremenekb8344ef2009-01-19 23:13:15 +000093
Chris Lattnerddf3b792009-01-21 07:21:56 +000094 CurPtr = CurPtrShadow;
Ted Kremenek08d3ff32008-12-23 02:30:15 +000095
96 //===--------------------------------------==//
97 // Construct the token itself.
98 //===--------------------------------------==//
99
100 Tok.startToken();
Chris Lattnerce8670e2009-01-18 02:34:01 +0000101 Tok.setKind(TKind);
102 Tok.setFlag(TFlags);
Ted Kremenekd94668d2008-12-23 19:24:24 +0000103 assert(!LexingRawMode);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000104 Tok.setLocation(FileStartLoc.getFileLocWithOffset(FileOffset));
Ted Kremenek08d3ff32008-12-23 02:30:15 +0000105 Tok.setLength(Len);
106
Chris Lattner8b2aa222009-01-21 07:50:06 +0000107 // Handle identifiers.
Ted Kremenek562db7f2009-01-27 00:01:05 +0000108 if (Tok.isLiteral()) {
109 Tok.setLiteralData((const char*) (PTHMgr.SpellingBase + IdentifierID));
110 }
111 else if (IdentifierID) {
Chris Lattner8b2aa222009-01-21 07:50:06 +0000112 MIOpt.ReadToken();
113 IdentifierInfo *II = PTHMgr.GetIdentifierInfo(IdentifierID-1);
Chris Lattner9ac3dd92009-01-23 18:35:48 +0000114
Chris Lattner8b2aa222009-01-21 07:50:06 +0000115 Tok.setIdentifierInfo(II);
Chris Lattner9ac3dd92009-01-23 18:35:48 +0000116
117 // Change the kind of this identifier to the appropriate token kind, e.g.
118 // turning "for" into a keyword.
119 Tok.setKind(II->getTokenID());
120
Chris Lattner8b2aa222009-01-21 07:50:06 +0000121 if (II->isHandleIdentifierCase())
122 PP->HandleIdentifier(Tok);
123 return;
124 }
125
Ted Kremenek08d3ff32008-12-23 02:30:15 +0000126 //===--------------------------------------==//
127 // Process the token.
128 //===--------------------------------------==//
Ted Kremenekd310fde2009-01-09 22:05:30 +0000129#if 0
130 SourceManager& SM = PP->getSourceManager();
131 llvm::cerr << SM.getFileEntryForID(FileID)->getName()
132 << ':' << SM.getLogicalLineNumber(Tok.getLocation())
133 << ':' << SM.getLogicalColumnNumber(Tok.getLocation())
134 << '\n';
135#endif
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000136
Chris Lattnerce8670e2009-01-18 02:34:01 +0000137 if (TKind == tok::eof) {
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000138 // Save the end-of-file token.
139 EofToken = Tok;
140
141 Preprocessor *PPCache = PP;
Ted Kremenekd94668d2008-12-23 19:24:24 +0000142
143 assert(!ParsingPreprocessorDirective);
144 assert(!LexingRawMode);
145
146 // FIXME: Issue diagnostics similar to Lexer.
147 if (PP->HandleEndOfFile(Tok, false))
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000148 return;
Ted Kremenekd94668d2008-12-23 19:24:24 +0000149
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000150 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
151 return PPCache->Lex(Tok);
152 }
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000153
Chris Lattnerce8670e2009-01-18 02:34:01 +0000154 if (TKind == tok::hash && Tok.isAtStartOfLine()) {
Ted Kremenekd94668d2008-12-23 19:24:24 +0000155 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
156 assert(!LexingRawMode);
157 PP->HandleDirective(Tok);
158
159 if (PP->isCurrentLexer(this))
160 goto LexNextToken;
161
162 return PP->Lex(Tok);
163 }
164
Chris Lattnerce8670e2009-01-18 02:34:01 +0000165 if (TKind == tok::eom) {
Ted Kremenekd94668d2008-12-23 19:24:24 +0000166 assert(ParsingPreprocessorDirective);
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000167 ParsingPreprocessorDirective = false;
168 return;
169 }
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000170
Ted Kremenekd94668d2008-12-23 19:24:24 +0000171 MIOpt.ReadToken();
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000172}
173
174// FIXME: We can just grab the last token instead of storing a copy
175// into EofToken.
Ted Kremenekd94668d2008-12-23 19:24:24 +0000176void PTHLexer::getEOF(Token& Tok) {
Ted Kremeneke4caf142009-01-09 00:36:11 +0000177 assert(EofToken.is(tok::eof));
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000178 Tok = EofToken;
179}
180
181void PTHLexer::DiscardToEndOfLine() {
182 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
183 "Must be in a preprocessing directive!");
184
185 // We assume that if the preprocessor wishes to discard to the end of
186 // the line that it also means to end the current preprocessor directive.
187 ParsingPreprocessorDirective = false;
188
189 // Skip tokens by only peeking at their token kind and the flags.
190 // We don't need to actually reconstruct full tokens from the token buffer.
191 // This saves some copies and it also reduces IdentifierInfo* lookup.
Chris Lattnerefb35342009-01-18 01:57:14 +0000192 const unsigned char* p = CurPtr;
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000193 while (1) {
194 // Read the token kind. Are we at the end of the file?
195 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
196 if (x == tok::eof) break;
197
198 // Read the token flags. Are we at the start of the next line?
199 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
200 if (y & Token::StartOfLine) break;
201
202 // Skip to the next token.
203 p += DISK_TOKEN_SIZE;
204 }
205
206 CurPtr = p;
207}
208
Ted Kremenekc07091c2008-12-12 18:34:08 +0000209/// SkipBlock - Used by Preprocessor to skip the current conditional block.
210bool PTHLexer::SkipBlock() {
211 assert(CurPPCondPtr && "No cached PP conditional information.");
212 assert(LastHashTokPtr && "No known '#' token.");
213
Chris Lattnerefb35342009-01-18 01:57:14 +0000214 const unsigned char* HashEntryI = 0;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000215 uint32_t Offset;
216 uint32_t TableIdx;
217
218 do {
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000219 // Read the token offset from the side-table.
Chris Lattner673a2862009-01-22 19:48:26 +0000220 Offset = ReadLE32(CurPPCondPtr);
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000221
222 // Read the target table index from the side-table.
Chris Lattner673a2862009-01-22 19:48:26 +0000223 TableIdx = ReadLE32(CurPPCondPtr);
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000224
225 // Compute the actual memory address of the '#' token data for this entry.
226 HashEntryI = TokBuf + Offset;
227
228 // Optmization: "Sibling jumping". #if...#else...#endif blocks can
229 // contain nested blocks. In the side-table we can jump over these
230 // nested blocks instead of doing a linear search if the next "sibling"
231 // entry is not at a location greater than LastHashTokPtr.
232 if (HashEntryI < LastHashTokPtr && TableIdx) {
233 // In the side-table we are still at an entry for a '#' token that
234 // is earlier than the last one we saw. Check if the location we would
235 // stride gets us closer.
Chris Lattnerefb35342009-01-18 01:57:14 +0000236 const unsigned char* NextPPCondPtr =
237 PPCond + TableIdx*(sizeof(uint32_t)*2);
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000238 assert(NextPPCondPtr >= CurPPCondPtr);
239 // Read where we should jump to.
Chris Lattner673a2862009-01-22 19:48:26 +0000240 uint32_t TmpOffset = ReadLE32(NextPPCondPtr);
Chris Lattnerefb35342009-01-18 01:57:14 +0000241 const unsigned char* HashEntryJ = TokBuf + TmpOffset;
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000242
243 if (HashEntryJ <= LastHashTokPtr) {
244 // Jump directly to the next entry in the side table.
245 HashEntryI = HashEntryJ;
246 Offset = TmpOffset;
Chris Lattner673a2862009-01-22 19:48:26 +0000247 TableIdx = ReadLE32(NextPPCondPtr);
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000248 CurPPCondPtr = NextPPCondPtr;
249 }
250 }
Ted Kremenekc07091c2008-12-12 18:34:08 +0000251 }
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000252 while (HashEntryI < LastHashTokPtr);
253 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
Ted Kremenekc07091c2008-12-12 18:34:08 +0000254 assert(TableIdx && "No jumping from #endifs.");
255
256 // Update our side-table iterator.
Chris Lattnerefb35342009-01-18 01:57:14 +0000257 const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
Ted Kremenekc07091c2008-12-12 18:34:08 +0000258 assert(NextPPCondPtr >= CurPPCondPtr);
259 CurPPCondPtr = NextPPCondPtr;
260
261 // Read where we should jump to.
Chris Lattner673a2862009-01-22 19:48:26 +0000262 HashEntryI = TokBuf + ReadLE32(NextPPCondPtr);
263 uint32_t NextIdx = ReadLE32(NextPPCondPtr);
Ted Kremenekc07091c2008-12-12 18:34:08 +0000264
265 // By construction NextIdx will be zero if this is a #endif. This is useful
266 // to know to obviate lexing another token.
267 bool isEndif = NextIdx == 0;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000268
269 // This case can occur when we see something like this:
270 //
271 // #if ...
272 // /* a comment or nothing */
273 // #elif
274 //
275 // If we are skipping the first #if block it will be the case that CurPtr
276 // already points 'elif'. Just return.
277
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000278 if (CurPtr > HashEntryI) {
279 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
Ted Kremenekc07091c2008-12-12 18:34:08 +0000280 // Did we reach a #endif? If so, go ahead and consume that token as well.
281 if (isEndif)
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000282 CurPtr += DISK_TOKEN_SIZE*2;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000283 else
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000284 LastHashTokPtr = HashEntryI;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000285
286 return isEndif;
287 }
288
289 // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000290 CurPtr = HashEntryI;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000291
292 // Update the location of the last observed '#'. This is useful if we
293 // are skipping multiple blocks.
294 LastHashTokPtr = CurPtr;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000295
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000296 // Skip the '#' token.
Chris Lattnerefb35342009-01-18 01:57:14 +0000297 assert(((tok::TokenKind)*CurPtr) == tok::hash);
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000298 CurPtr += DISK_TOKEN_SIZE;
299
Ted Kremenekc07091c2008-12-12 18:34:08 +0000300 // Did we reach a #endif? If so, go ahead and consume that token as well.
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000301 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
Ted Kremenekc07091c2008-12-12 18:34:08 +0000302
303 return isEndif;
304}
305
Ted Kremenekbeb57672008-12-17 23:36:32 +0000306SourceLocation PTHLexer::getSourceLocation() {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000307 // getSourceLocation is not on the hot path. It is used to get the location
308 // of the next token when transitioning back to this lexer when done
Ted Kremenekbeb57672008-12-17 23:36:32 +0000309 // handling a #included file. Just read the necessary data from the token
310 // data buffer to construct the SourceLocation object.
311 // NOTE: This is a virtual function; hence it is defined out-of-line.
Ted Kremenekde04cb42009-01-21 22:41:38 +0000312 const unsigned char *OffsetPtr = CurPtr + (DISK_TOKEN_SIZE - 4);
Chris Lattner673a2862009-01-22 19:48:26 +0000313 uint32_t Offset = ReadLE32(OffsetPtr);
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000314 return FileStartLoc.getFileLocWithOffset(Offset);
Ted Kremenekbeb57672008-12-17 23:36:32 +0000315}
316
Ted Kremenekd310fde2009-01-09 22:05:30 +0000317//===----------------------------------------------------------------------===//
Ted Kremenekab6c4882009-02-10 22:16:22 +0000318// OnDiskChainedHashTable
Ted Kremenek325cd302008-12-03 00:38:03 +0000319//===----------------------------------------------------------------------===//
320
Ted Kremenekab6c4882009-02-10 22:16:22 +0000321template<typename Info>
322class OnDiskChainedHashTable {
323 const unsigned NumBuckets;
324 const unsigned NumEntries;
325 const unsigned char* const Buckets;
326 const unsigned char* const Base;
327public:
328 typedef typename Info::internal_key_type internal_key_type;
329 typedef typename Info::external_key_type external_key_type;
330 typedef typename Info::data_type data_type;
331
332 OnDiskChainedHashTable(unsigned numBuckets, unsigned numEntries,
333 const unsigned char* buckets,
334 const unsigned char* base)
335 : NumBuckets(numBuckets), NumEntries(numEntries),
336 Buckets(buckets), Base(base) {
337 assert((reinterpret_cast<uintptr_t>(buckets) & 0x3) == 0 &&
338 "'buckets' must have a 4-byte alignment");
339 }
340
341
342 bool isEmpty() const { return NumEntries == 0; }
343
344 class iterator {
345 const unsigned char* const data;
346 const unsigned len;
347 public:
348 iterator() : data(0), len(0) {}
349 iterator(const unsigned char* d, unsigned l) : data(d), len(l) {}
350
351 data_type operator*() const { return Info::ReadData(data, len); }
352 bool operator==(const iterator& X) const { return X.data == data; }
353 bool operator!=(const iterator& X) const { return X.data != data; }
354 };
355
356 iterator find(const external_key_type& eKey) {
357 const internal_key_type& iKey = Info::GetInternalKey(eKey);
358 unsigned key_hash = Info::ComputeHash(iKey);
359
360 // Each bucket is just a 32-bit offset into the PTH file.
361 unsigned idx = key_hash & (NumBuckets - 1);
362 const unsigned char* Bucket = Buckets + sizeof(uint32_t)*idx;
363
364 unsigned offset = ReadLE32(Bucket);
365 if (offset == 0) return iterator(); // Empty bucket.
366 const unsigned char* Items = Base + offset;
367
368 // 'Items' starts with a 16-bit unsigned integer representing the
369 // number of items in this bucket.
370 unsigned len = ReadUnalignedLE16(Items);
371
372 for (unsigned i = 0; i < len; ++i) {
373 // Read the hash.
374 uint32_t item_hash = ReadUnalignedLE32(Items);
375
376 // Determine the length of the key and the data.
377 const std::pair<unsigned, unsigned>& L = Info::ReadKeyDataLength(Items);
378 unsigned item_len = L.first + L.second;
379
380 // Compare the hashes. If they are not the same, skip the entry entirely.
381 if (item_hash != key_hash) {
382 Items += item_len;
383 continue;
384 }
385
386 // Read the key.
387 const internal_key_type& X =
388 Info::ReadKey((const unsigned char* const) Items, L.first);
389
390 // If the key doesn't match just skip reading the value.
391 if (!Info::EqualKey(X, iKey)) {
392 Items += item_len;
393 continue;
394 }
395
396 // The key matches!
397 return iterator(Items + L.first, L.second);
398 }
399
400 return iterator();
401 }
402
403 iterator end() const { return iterator(); }
404
405
406 static OnDiskChainedHashTable* Create(const unsigned char* buckets,
407 const unsigned char* const base) {
408
409 assert(buckets > base);
410 assert((reinterpret_cast<uintptr_t>(buckets) & 0x3) == 0 &&
411 "buckets should be 4-byte aligned.");
412
413 unsigned numBuckets = ReadLE32(buckets);
414 unsigned numEntries = ReadLE32(buckets);
415 return new OnDiskChainedHashTable<Info>(numBuckets, numEntries, buckets,
416 base);
417 }
418};
419
420//===----------------------------------------------------------------------===//
421// PTH file lookup: map from strings to file data.
422//===----------------------------------------------------------------------===//
Ted Kremenek325cd302008-12-03 00:38:03 +0000423
424/// PTHFileLookup - This internal data structure is used by the PTHManager
425/// to map from FileEntry objects managed by FileManager to offsets within
426/// the PTH file.
427namespace {
Ted Kremenekab6c4882009-02-10 22:16:22 +0000428class VISIBILITY_HIDDEN PTHFileData {
429 const uint32_t TokenOff;
430 const uint32_t PPCondOff;
Ted Kremenek325cd302008-12-03 00:38:03 +0000431public:
Ted Kremenekab6c4882009-02-10 22:16:22 +0000432 PTHFileData(uint32_t tokenOff, uint32_t ppCondOff)
433 : TokenOff(tokenOff), PPCondOff(ppCondOff) {}
Ted Kremenek325cd302008-12-03 00:38:03 +0000434
Ted Kremenekab6c4882009-02-10 22:16:22 +0000435 uint32_t getTokenOffset() const { return TokenOff; }
436 uint32_t getPPCondOffset() const { return PPCondOff; }
437};
438
439class VISIBILITY_HIDDEN PTHFileLookupTrait {
440public:
441 typedef PTHFileData data_type;
442 typedef const FileEntry* external_key_type;
443 typedef const char* internal_key_type;
444
445 static bool EqualKey(const char* a, const char* b) {
446 return strcmp(a, b) == 0;
447 }
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000448
Ted Kremenekab6c4882009-02-10 22:16:22 +0000449 static unsigned ComputeHash(const char* x) {
450 // More copy-paste nonsense. Will refactor.
451 unsigned int R = 0;
452 for (; *x != '\0' ; ++x) R = R * 33 + *x;
453 return R + (R >> 5);
454 }
455
456 static const char* GetInternalKey(const FileEntry* FE) {
457 return FE->getName();
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000458 }
459
Ted Kremenekab6c4882009-02-10 22:16:22 +0000460 static std::pair<unsigned, unsigned>
461 ReadKeyDataLength(const unsigned char*& d) {
462 return std::make_pair((unsigned) ReadUnalignedLE16(d), 8U);
Ted Kremenek325cd302008-12-03 00:38:03 +0000463 }
464
Ted Kremenekab6c4882009-02-10 22:16:22 +0000465 static const char* ReadKey(const unsigned char* d, unsigned) {
466 return (const char*) d;
467 }
468
469 static PTHFileData ReadData(const unsigned char* d, unsigned) {
470 uint32_t x = ::ReadUnalignedLE32(d);
471 uint32_t y = ::ReadUnalignedLE32(d);
472 return PTHFileData(x, y);
Ted Kremenek325cd302008-12-03 00:38:03 +0000473 }
474};
Ted Kremenekab6c4882009-02-10 22:16:22 +0000475} // end anonymous namespace
476
477typedef OnDiskChainedHashTable<PTHFileLookupTrait> PTHFileLookup;
Ted Kremenek325cd302008-12-03 00:38:03 +0000478
479//===----------------------------------------------------------------------===//
480// PTHManager methods.
481//===----------------------------------------------------------------------===//
482
483PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
Chris Lattnerefb35342009-01-18 01:57:14 +0000484 const unsigned char* idDataTable,
485 IdentifierInfo** perIDCache,
Ted Kremenek562db7f2009-01-27 00:01:05 +0000486 const unsigned char* sortedIdTable, unsigned numIds,
487 const unsigned char* spellingBase)
Ted Kremenekdb4c8e82008-12-03 01:16:39 +0000488: Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000489 IdDataTable(idDataTable), SortedIdTable(sortedIdTable),
Ted Kremenek562db7f2009-01-27 00:01:05 +0000490 NumIds(numIds), PP(0), SpellingBase(spellingBase) {}
Ted Kremenek325cd302008-12-03 00:38:03 +0000491
492PTHManager::~PTHManager() {
493 delete Buf;
494 delete (PTHFileLookup*) FileLookup;
Ted Kremenek93bdc492008-12-04 22:47:11 +0000495 free(PerIDCache);
Ted Kremenek325cd302008-12-03 00:38:03 +0000496}
497
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000498static void InvalidPTH(Diagnostic *Diags, const char* Msg = 0) {
499 if (!Diags) return;
500 if (!Msg) Msg = "Invalid or corrupted PTH file";
501 unsigned DiagID = Diags->getCustomDiagID(Diagnostic::Note, Msg);
502 Diags->Report(FullSourceLoc(), DiagID);
503}
504
Ted Kremenek3d145552009-01-28 20:49:33 +0000505PTHManager* PTHManager::Create(const std::string& file, Diagnostic* Diags) {
Ted Kremenek325cd302008-12-03 00:38:03 +0000506 // Memory map the PTH file.
507 llvm::OwningPtr<llvm::MemoryBuffer>
508 File(llvm::MemoryBuffer::getFile(file.c_str()));
509
Ted Kremenek3d145552009-01-28 20:49:33 +0000510 if (!File) {
511 if (Diags) {
512 unsigned DiagID = Diags->getCustomDiagID(Diagnostic::Note,
513 "PTH file %0 could not be read");
514 Diags->Report(FullSourceLoc(), DiagID) << file;
515 }
516
Ted Kremenek325cd302008-12-03 00:38:03 +0000517 return 0;
Ted Kremenek3d145552009-01-28 20:49:33 +0000518 }
Ted Kremenek325cd302008-12-03 00:38:03 +0000519
520 // Get the buffer ranges and check if there are at least three 32-bit
521 // words at the end of the file.
Chris Lattnerefb35342009-01-18 01:57:14 +0000522 const unsigned char* BufBeg = (unsigned char*)File->getBufferStart();
523 const unsigned char* BufEnd = (unsigned char*)File->getBufferEnd();
Ted Kremenek58b9f932009-01-26 21:43:14 +0000524
525 // Check the prologue of the file.
Ted Kremenek497aba32009-01-26 22:16:12 +0000526 if ((BufEnd - BufBeg) < (signed) (sizeof("cfe-pth") + 3 + 4) ||
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000527 memcmp(BufBeg, "cfe-pth", sizeof("cfe-pth") - 1) != 0) {
528 InvalidPTH(Diags);
Ted Kremenek58b9f932009-01-26 21:43:14 +0000529 return 0;
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000530 }
Ted Kremenek325cd302008-12-03 00:38:03 +0000531
Ted Kremenek169fc352009-01-26 21:50:21 +0000532 // Read the PTH version.
Ted Kremenek58b9f932009-01-26 21:43:14 +0000533 const unsigned char *p = BufBeg + (sizeof("cfe-pth") - 1);
Ted Kremenek169fc352009-01-26 21:50:21 +0000534 unsigned Version = ReadLE32(p);
535
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000536 if (Version != PTHManager::Version) {
537 InvalidPTH(Diags,
538 Version < PTHManager::Version
539 ? "PTH file uses an older PTH format that is no longer supported"
540 : "PTH file uses a newer PTH format that cannot be read");
Ted Kremenek169fc352009-01-26 21:50:21 +0000541 return 0;
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000542 }
Ted Kremenek169fc352009-01-26 21:50:21 +0000543
544 // Compute the address of the index table at the end of the PTH file.
Ted Kremenek58b9f932009-01-26 21:43:14 +0000545 const unsigned char *EndTable = BufBeg + ReadLE32(p);
546
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000547 if (EndTable >= BufEnd) {
548 InvalidPTH(Diags);
Ted Kremenek58b9f932009-01-26 21:43:14 +0000549 return 0;
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000550 }
Ted Kremenek325cd302008-12-03 00:38:03 +0000551
552 // Construct the file lookup table. This will be used for mapping from
553 // FileEntry*'s to cached tokens.
Ted Kremenekc4a1cf62009-02-11 16:06:55 +0000554 const unsigned char* FileTableOffset = EndTable + sizeof(uint32_t)*2;
Chris Lattner673a2862009-01-22 19:48:26 +0000555 const unsigned char* FileTable = BufBeg + ReadLE32(FileTableOffset);
Ted Kremenek325cd302008-12-03 00:38:03 +0000556
557 if (!(FileTable > BufBeg && FileTable < BufEnd)) {
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000558 InvalidPTH(Diags);
Ted Kremenek325cd302008-12-03 00:38:03 +0000559 return 0; // FIXME: Proper error diagnostic?
560 }
561
Ted Kremenekab6c4882009-02-10 22:16:22 +0000562 llvm::OwningPtr<PTHFileLookup> FL(PTHFileLookup::Create(FileTable, BufBeg));
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000563 if (FL->isEmpty()) {
564 InvalidPTH(Diags, "PTH file contains no cached source data");
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000565 return 0;
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000566 }
Ted Kremenek325cd302008-12-03 00:38:03 +0000567
568 // Get the location of the table mapping from persistent ids to the
569 // data needed to reconstruct identifiers.
Ted Kremenekc4a1cf62009-02-11 16:06:55 +0000570 const unsigned char* IDTableOffset = EndTable + sizeof(uint32_t)*0;
Chris Lattner673a2862009-01-22 19:48:26 +0000571 const unsigned char* IData = BufBeg + ReadLE32(IDTableOffset);
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000572
573 if (!(IData >= BufBeg && IData < BufEnd)) {
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000574 InvalidPTH(Diags);
575 return 0;
Ted Kremenek325cd302008-12-03 00:38:03 +0000576 }
577
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000578 // Get the location of the lexigraphically-sorted table of persistent IDs.
Ted Kremenekc4a1cf62009-02-11 16:06:55 +0000579 const unsigned char* SortedIdTableOffset = EndTable + sizeof(uint32_t)*1;
Chris Lattner673a2862009-01-22 19:48:26 +0000580 const unsigned char* SortedIdTable = BufBeg + ReadLE32(SortedIdTableOffset);
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000581 if (!(SortedIdTable >= BufBeg && SortedIdTable < BufEnd)) {
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000582 InvalidPTH(Diags);
583 return 0;
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000584 }
585
Ted Kremenek562db7f2009-01-27 00:01:05 +0000586 // Get the location of the spelling cache.
Ted Kremenekc4a1cf62009-02-11 16:06:55 +0000587 const unsigned char* spellingBaseOffset = EndTable + sizeof(uint32_t)*3;
Ted Kremenek562db7f2009-01-27 00:01:05 +0000588 const unsigned char* spellingBase = BufBeg + ReadLE32(spellingBaseOffset);
589 if (!(spellingBase >= BufBeg && spellingBase < BufEnd)) {
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000590 InvalidPTH(Diags);
Ted Kremenek562db7f2009-01-27 00:01:05 +0000591 return 0;
592 }
593
Ted Kremenekdb4c8e82008-12-03 01:16:39 +0000594 // Get the number of IdentifierInfos and pre-allocate the identifier cache.
Chris Lattner673a2862009-01-22 19:48:26 +0000595 uint32_t NumIds = ReadLE32(IData);
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000596
Ted Kremenekdb4c8e82008-12-03 01:16:39 +0000597 // Pre-allocate the peristent ID -> IdentifierInfo* cache. We use calloc()
598 // so that we in the best case only zero out memory once when the OS returns
599 // us new pages.
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000600 IdentifierInfo** PerIDCache = 0;
Ted Kremenekdb4c8e82008-12-03 01:16:39 +0000601
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000602 if (NumIds) {
603 PerIDCache = (IdentifierInfo**)calloc(NumIds, sizeof(*PerIDCache));
604 if (!PerIDCache) {
Ted Kremeneke6fa38d2009-01-28 21:02:43 +0000605 InvalidPTH(Diags, "Could not allocate memory for processing PTH file");
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000606 return 0;
607 }
Ted Kremenekdb4c8e82008-12-03 01:16:39 +0000608 }
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000609
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000610 // Create the new PTHManager.
611 return new PTHManager(File.take(), FL.take(), IData, PerIDCache,
Ted Kremenek562db7f2009-01-27 00:01:05 +0000612 SortedIdTable, NumIds, spellingBase);
Ted Kremenek325cd302008-12-03 00:38:03 +0000613}
Chris Lattnercbcd26c2009-01-18 02:57:21 +0000614IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) {
Ted Kremenek325cd302008-12-03 00:38:03 +0000615 // Look in the PTH file for the string data for the IdentifierInfo object.
Chris Lattnercbcd26c2009-01-18 02:57:21 +0000616 const unsigned char* TableEntry = IdDataTable + sizeof(uint32_t)*PersistentID;
Chris Lattnerefb35342009-01-18 01:57:14 +0000617 const unsigned char* IDData =
Chris Lattner673a2862009-01-22 19:48:26 +0000618 (const unsigned char*)Buf->getBufferStart() + ReadLE32(TableEntry);
Chris Lattnerefb35342009-01-18 01:57:14 +0000619 assert(IDData < (const unsigned char*)Buf->getBufferEnd());
Ted Kremenek325cd302008-12-03 00:38:03 +0000620
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000621 // Allocate the object.
Chris Lattnerefb35342009-01-18 01:57:14 +0000622 std::pair<IdentifierInfo,const unsigned char*> *Mem =
623 Alloc.Allocate<std::pair<IdentifierInfo,const unsigned char*> >();
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000624
625 Mem->second = IDData;
Ted Kremeneke807f852009-01-20 23:28:34 +0000626 IdentifierInfo *II = new ((void*) Mem) IdentifierInfo();
Ted Kremenek325cd302008-12-03 00:38:03 +0000627
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000628 // Store the new IdentifierInfo in the cache.
Chris Lattnercbcd26c2009-01-18 02:57:21 +0000629 PerIDCache[PersistentID] = II;
Ted Kremenek325cd302008-12-03 00:38:03 +0000630 return II;
631}
632
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000633IdentifierInfo* PTHManager::get(const char *NameStart, const char *NameEnd) {
634 unsigned min = 0;
635 unsigned max = NumIds;
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000636 unsigned Len = NameEnd - NameStart;
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000637
638 do {
639 unsigned i = (max - min) / 2 + min;
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000640 const unsigned char *Ptr = SortedIdTable + (i * 4);
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000641
642 // Read the persistentID.
Chris Lattner673a2862009-01-22 19:48:26 +0000643 unsigned perID = ReadLE32(Ptr);
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000644
645 // Get the IdentifierInfo.
646 IdentifierInfo* II = GetIdentifierInfo(perID);
647
648 // First compare the lengths.
649 unsigned IILen = II->getLength();
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000650 if (Len < IILen) goto IsLess;
651 if (Len > IILen) goto IsGreater;
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000652
653 // Now compare the strings!
654 {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000655 signed comp = strncmp(NameStart, II->getName(), Len);
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000656 if (comp < 0) goto IsLess;
657 if (comp > 0) goto IsGreater;
658 }
659 // We found a match!
660 return II;
661
662 IsGreater:
663 if (i == min) break;
664 min = i;
665 continue;
666
667 IsLess:
668 max = i;
669 assert(!(max == min) || (min == i));
670 }
Ted Kremenek4795ad02009-01-15 19:28:38 +0000671 while (min != max);
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000672
673 return 0;
674}
675
676
Chris Lattner3c727d62009-01-17 08:06:50 +0000677PTHLexer *PTHManager::CreateLexer(FileID FID) {
678 const FileEntry *FE = PP->getSourceManager().getFileEntryForID(FID);
Ted Kremenek325cd302008-12-03 00:38:03 +0000679 if (!FE)
680 return 0;
681
682 // Lookup the FileEntry object in our file lookup data structure. It will
683 // return a variant that indicates whether or not there is an offset within
684 // the PTH file that contains cached tokens.
Ted Kremenekab6c4882009-02-10 22:16:22 +0000685 PTHFileLookup& PFL = *((PTHFileLookup*)FileLookup);
686 PTHFileLookup::iterator I = PFL.find(FE);
Ted Kremenek325cd302008-12-03 00:38:03 +0000687
Ted Kremenekab6c4882009-02-10 22:16:22 +0000688 if (I == PFL.end()) // No tokens available?
Ted Kremenek325cd302008-12-03 00:38:03 +0000689 return 0;
690
Ted Kremenekab6c4882009-02-10 22:16:22 +0000691 const PTHFileData& FileData = *I;
692
Chris Lattnerefb35342009-01-18 01:57:14 +0000693 const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart();
Ted Kremenek325cd302008-12-03 00:38:03 +0000694 // Compute the offset of the token data within the buffer.
Chris Lattnerefb35342009-01-18 01:57:14 +0000695 const unsigned char* data = BufStart + FileData.getTokenOffset();
Ted Kremenekc07091c2008-12-12 18:34:08 +0000696
697 // Get the location of pp-conditional table.
Chris Lattnerefb35342009-01-18 01:57:14 +0000698 const unsigned char* ppcond = BufStart + FileData.getPPCondOffset();
Chris Lattner673a2862009-01-22 19:48:26 +0000699 uint32_t Len = ReadLE32(ppcond);
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000700 if (Len == 0) ppcond = 0;
Ted Kremeneka4d5bf52009-01-08 04:30:32 +0000701
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000702 assert(PP && "No preprocessor set yet!");
Ted Kremenek562db7f2009-01-27 00:01:05 +0000703 return new PTHLexer(*PP, FID, data, ppcond, *this);
Ted Kremenek325cd302008-12-03 00:38:03 +0000704}