blob: f9f2b21061203e497c44f1af2e44c81a83d0f595 [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) {
Chris Lattnerefb35342009-01-18 01:57:14 +000037 uint16_t V = ((uint16_t)Data[0] << 0) |
38 ((uint16_t)Data[1] << 8);
39 Data += 2;
40 return V;
41}
42
Chris Lattner673a2862009-01-22 19:48:26 +000043static inline uint32_t ReadLE32(const unsigned char *&Data) {
Chris Lattner007c4dc2009-01-23 00:13:28 +000044 // Hosts that directly support little-endian 32-bit loads can just
45 // use them. Big-endian hosts need a bswap.
Chris Lattner5bffcaf2009-01-18 02:19:16 +000046 uint32_t V = *((uint32_t*)Data);
Chris Lattner6b0f1c72009-01-22 23:50:07 +000047 if (llvm::sys::isBigEndianHost())
48 V = llvm::ByteSwap_32(V);
Chris Lattnerefb35342009-01-18 01:57:14 +000049 Data += 4;
50 return V;
51}
52
53
Ted Kremenek9ab79bf2008-12-23 01:30:52 +000054//===----------------------------------------------------------------------===//
55// PTHLexer methods.
56//===----------------------------------------------------------------------===//
57
Chris Lattnerefb35342009-01-18 01:57:14 +000058PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D,
Ted Kremenek562db7f2009-01-27 00:01:05 +000059 const unsigned char *ppcond, PTHManager &PM)
Chris Lattnerf4f776a2009-01-17 06:22:33 +000060 : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(0),
Ted Kremenek562db7f2009-01-27 00:01:05 +000061 PPCond(ppcond), CurPPCondPtr(ppcond), PTHMgr(PM) {
Chris Lattnerf4f776a2009-01-17 06:22:33 +000062
63 FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID);
Ted Kremenekd310fde2009-01-09 22:05:30 +000064}
Ted Kremenek9ab79bf2008-12-23 01:30:52 +000065
66void PTHLexer::Lex(Token& Tok) {
67LexNextToken:
Ted Kremenek9ab79bf2008-12-23 01:30:52 +000068
Ted Kremenek08d3ff32008-12-23 02:30:15 +000069 //===--------------------------------------==//
70 // Read the raw token data.
71 //===--------------------------------------==//
72
73 // Shadow CurPtr into an automatic variable.
Chris Lattnerddf3b792009-01-21 07:21:56 +000074 const unsigned char *CurPtrShadow = CurPtr;
Ted Kremenek08d3ff32008-12-23 02:30:15 +000075
Chris Lattner0a6ec5d2009-01-18 02:10:31 +000076 // Read in the data for the token.
Chris Lattner673a2862009-01-22 19:48:26 +000077 unsigned Word0 = ReadLE32(CurPtrShadow);
78 uint32_t IdentifierID = ReadLE32(CurPtrShadow);
79 uint32_t FileOffset = ReadLE32(CurPtrShadow);
Ted Kremenekb8344ef2009-01-19 23:13:15 +000080
81 tok::TokenKind TKind = (tok::TokenKind) (Word0 & 0xFF);
82 Token::TokenFlags TFlags = (Token::TokenFlags) ((Word0 >> 8) & 0xFF);
Chris Lattnerddf3b792009-01-21 07:21:56 +000083 uint32_t Len = Word0 >> 16;
Ted Kremenekb8344ef2009-01-19 23:13:15 +000084
Chris Lattnerddf3b792009-01-21 07:21:56 +000085 CurPtr = CurPtrShadow;
Ted Kremenek08d3ff32008-12-23 02:30:15 +000086
87 //===--------------------------------------==//
88 // Construct the token itself.
89 //===--------------------------------------==//
90
91 Tok.startToken();
Chris Lattnerce8670e2009-01-18 02:34:01 +000092 Tok.setKind(TKind);
93 Tok.setFlag(TFlags);
Ted Kremenekd94668d2008-12-23 19:24:24 +000094 assert(!LexingRawMode);
Chris Lattnerf4f776a2009-01-17 06:22:33 +000095 Tok.setLocation(FileStartLoc.getFileLocWithOffset(FileOffset));
Ted Kremenek08d3ff32008-12-23 02:30:15 +000096 Tok.setLength(Len);
97
Chris Lattner8b2aa222009-01-21 07:50:06 +000098 // Handle identifiers.
Ted Kremenek562db7f2009-01-27 00:01:05 +000099 if (Tok.isLiteral()) {
100 Tok.setLiteralData((const char*) (PTHMgr.SpellingBase + IdentifierID));
101 }
102 else if (IdentifierID) {
Chris Lattner8b2aa222009-01-21 07:50:06 +0000103 MIOpt.ReadToken();
104 IdentifierInfo *II = PTHMgr.GetIdentifierInfo(IdentifierID-1);
Chris Lattner9ac3dd92009-01-23 18:35:48 +0000105
Chris Lattner8b2aa222009-01-21 07:50:06 +0000106 Tok.setIdentifierInfo(II);
Chris Lattner9ac3dd92009-01-23 18:35:48 +0000107
108 // Change the kind of this identifier to the appropriate token kind, e.g.
109 // turning "for" into a keyword.
110 Tok.setKind(II->getTokenID());
111
Chris Lattner8b2aa222009-01-21 07:50:06 +0000112 if (II->isHandleIdentifierCase())
113 PP->HandleIdentifier(Tok);
114 return;
115 }
116
Ted Kremenek08d3ff32008-12-23 02:30:15 +0000117 //===--------------------------------------==//
118 // Process the token.
119 //===--------------------------------------==//
Ted Kremenekd310fde2009-01-09 22:05:30 +0000120#if 0
121 SourceManager& SM = PP->getSourceManager();
122 llvm::cerr << SM.getFileEntryForID(FileID)->getName()
123 << ':' << SM.getLogicalLineNumber(Tok.getLocation())
124 << ':' << SM.getLogicalColumnNumber(Tok.getLocation())
125 << '\n';
126#endif
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000127
Chris Lattnerce8670e2009-01-18 02:34:01 +0000128 if (TKind == tok::eof) {
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000129 // Save the end-of-file token.
130 EofToken = Tok;
131
132 Preprocessor *PPCache = PP;
Ted Kremenekd94668d2008-12-23 19:24:24 +0000133
134 assert(!ParsingPreprocessorDirective);
135 assert(!LexingRawMode);
136
137 // FIXME: Issue diagnostics similar to Lexer.
138 if (PP->HandleEndOfFile(Tok, false))
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000139 return;
Ted Kremenekd94668d2008-12-23 19:24:24 +0000140
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000141 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
142 return PPCache->Lex(Tok);
143 }
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000144
Chris Lattnerce8670e2009-01-18 02:34:01 +0000145 if (TKind == tok::hash && Tok.isAtStartOfLine()) {
Ted Kremenekd94668d2008-12-23 19:24:24 +0000146 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
147 assert(!LexingRawMode);
148 PP->HandleDirective(Tok);
149
150 if (PP->isCurrentLexer(this))
151 goto LexNextToken;
152
153 return PP->Lex(Tok);
154 }
155
Chris Lattnerce8670e2009-01-18 02:34:01 +0000156 if (TKind == tok::eom) {
Ted Kremenekd94668d2008-12-23 19:24:24 +0000157 assert(ParsingPreprocessorDirective);
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000158 ParsingPreprocessorDirective = false;
159 return;
160 }
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000161
Ted Kremenekd94668d2008-12-23 19:24:24 +0000162 MIOpt.ReadToken();
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000163}
164
165// FIXME: We can just grab the last token instead of storing a copy
166// into EofToken.
Ted Kremenekd94668d2008-12-23 19:24:24 +0000167void PTHLexer::getEOF(Token& Tok) {
Ted Kremeneke4caf142009-01-09 00:36:11 +0000168 assert(EofToken.is(tok::eof));
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000169 Tok = EofToken;
170}
171
172void PTHLexer::DiscardToEndOfLine() {
173 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
174 "Must be in a preprocessing directive!");
175
176 // We assume that if the preprocessor wishes to discard to the end of
177 // the line that it also means to end the current preprocessor directive.
178 ParsingPreprocessorDirective = false;
179
180 // Skip tokens by only peeking at their token kind and the flags.
181 // We don't need to actually reconstruct full tokens from the token buffer.
182 // This saves some copies and it also reduces IdentifierInfo* lookup.
Chris Lattnerefb35342009-01-18 01:57:14 +0000183 const unsigned char* p = CurPtr;
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000184 while (1) {
185 // Read the token kind. Are we at the end of the file?
186 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
187 if (x == tok::eof) break;
188
189 // Read the token flags. Are we at the start of the next line?
190 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
191 if (y & Token::StartOfLine) break;
192
193 // Skip to the next token.
194 p += DISK_TOKEN_SIZE;
195 }
196
197 CurPtr = p;
198}
199
Ted Kremenekc07091c2008-12-12 18:34:08 +0000200/// SkipBlock - Used by Preprocessor to skip the current conditional block.
201bool PTHLexer::SkipBlock() {
202 assert(CurPPCondPtr && "No cached PP conditional information.");
203 assert(LastHashTokPtr && "No known '#' token.");
204
Chris Lattnerefb35342009-01-18 01:57:14 +0000205 const unsigned char* HashEntryI = 0;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000206 uint32_t Offset;
207 uint32_t TableIdx;
208
209 do {
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000210 // Read the token offset from the side-table.
Chris Lattner673a2862009-01-22 19:48:26 +0000211 Offset = ReadLE32(CurPPCondPtr);
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000212
213 // Read the target table index from the side-table.
Chris Lattner673a2862009-01-22 19:48:26 +0000214 TableIdx = ReadLE32(CurPPCondPtr);
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000215
216 // Compute the actual memory address of the '#' token data for this entry.
217 HashEntryI = TokBuf + Offset;
218
219 // Optmization: "Sibling jumping". #if...#else...#endif blocks can
220 // contain nested blocks. In the side-table we can jump over these
221 // nested blocks instead of doing a linear search if the next "sibling"
222 // entry is not at a location greater than LastHashTokPtr.
223 if (HashEntryI < LastHashTokPtr && TableIdx) {
224 // In the side-table we are still at an entry for a '#' token that
225 // is earlier than the last one we saw. Check if the location we would
226 // stride gets us closer.
Chris Lattnerefb35342009-01-18 01:57:14 +0000227 const unsigned char* NextPPCondPtr =
228 PPCond + TableIdx*(sizeof(uint32_t)*2);
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000229 assert(NextPPCondPtr >= CurPPCondPtr);
230 // Read where we should jump to.
Chris Lattner673a2862009-01-22 19:48:26 +0000231 uint32_t TmpOffset = ReadLE32(NextPPCondPtr);
Chris Lattnerefb35342009-01-18 01:57:14 +0000232 const unsigned char* HashEntryJ = TokBuf + TmpOffset;
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000233
234 if (HashEntryJ <= LastHashTokPtr) {
235 // Jump directly to the next entry in the side table.
236 HashEntryI = HashEntryJ;
237 Offset = TmpOffset;
Chris Lattner673a2862009-01-22 19:48:26 +0000238 TableIdx = ReadLE32(NextPPCondPtr);
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000239 CurPPCondPtr = NextPPCondPtr;
240 }
241 }
Ted Kremenekc07091c2008-12-12 18:34:08 +0000242 }
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000243 while (HashEntryI < LastHashTokPtr);
244 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
Ted Kremenekc07091c2008-12-12 18:34:08 +0000245 assert(TableIdx && "No jumping from #endifs.");
246
247 // Update our side-table iterator.
Chris Lattnerefb35342009-01-18 01:57:14 +0000248 const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
Ted Kremenekc07091c2008-12-12 18:34:08 +0000249 assert(NextPPCondPtr >= CurPPCondPtr);
250 CurPPCondPtr = NextPPCondPtr;
251
252 // Read where we should jump to.
Chris Lattner673a2862009-01-22 19:48:26 +0000253 HashEntryI = TokBuf + ReadLE32(NextPPCondPtr);
254 uint32_t NextIdx = ReadLE32(NextPPCondPtr);
Ted Kremenekc07091c2008-12-12 18:34:08 +0000255
256 // By construction NextIdx will be zero if this is a #endif. This is useful
257 // to know to obviate lexing another token.
258 bool isEndif = NextIdx == 0;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000259
260 // This case can occur when we see something like this:
261 //
262 // #if ...
263 // /* a comment or nothing */
264 // #elif
265 //
266 // If we are skipping the first #if block it will be the case that CurPtr
267 // already points 'elif'. Just return.
268
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000269 if (CurPtr > HashEntryI) {
270 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
Ted Kremenekc07091c2008-12-12 18:34:08 +0000271 // Did we reach a #endif? If so, go ahead and consume that token as well.
272 if (isEndif)
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000273 CurPtr += DISK_TOKEN_SIZE*2;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000274 else
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000275 LastHashTokPtr = HashEntryI;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000276
277 return isEndif;
278 }
279
280 // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000281 CurPtr = HashEntryI;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000282
283 // Update the location of the last observed '#'. This is useful if we
284 // are skipping multiple blocks.
285 LastHashTokPtr = CurPtr;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000286
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000287 // Skip the '#' token.
Chris Lattnerefb35342009-01-18 01:57:14 +0000288 assert(((tok::TokenKind)*CurPtr) == tok::hash);
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000289 CurPtr += DISK_TOKEN_SIZE;
290
Ted Kremenekc07091c2008-12-12 18:34:08 +0000291 // Did we reach a #endif? If so, go ahead and consume that token as well.
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000292 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
Ted Kremenekc07091c2008-12-12 18:34:08 +0000293
294 return isEndif;
295}
296
Ted Kremenekbeb57672008-12-17 23:36:32 +0000297SourceLocation PTHLexer::getSourceLocation() {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000298 // getSourceLocation is not on the hot path. It is used to get the location
299 // of the next token when transitioning back to this lexer when done
Ted Kremenekbeb57672008-12-17 23:36:32 +0000300 // handling a #included file. Just read the necessary data from the token
301 // data buffer to construct the SourceLocation object.
302 // NOTE: This is a virtual function; hence it is defined out-of-line.
Ted Kremenekde04cb42009-01-21 22:41:38 +0000303 const unsigned char *OffsetPtr = CurPtr + (DISK_TOKEN_SIZE - 4);
Chris Lattner673a2862009-01-22 19:48:26 +0000304 uint32_t Offset = ReadLE32(OffsetPtr);
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000305 return FileStartLoc.getFileLocWithOffset(Offset);
Ted Kremenekbeb57672008-12-17 23:36:32 +0000306}
307
Ted Kremenekd310fde2009-01-09 22:05:30 +0000308//===----------------------------------------------------------------------===//
Ted Kremenek325cd302008-12-03 00:38:03 +0000309// Internal Data Structures for PTH file lookup and resolving identifiers.
310//===----------------------------------------------------------------------===//
311
Ted Kremenek325cd302008-12-03 00:38:03 +0000312
313/// PTHFileLookup - This internal data structure is used by the PTHManager
314/// to map from FileEntry objects managed by FileManager to offsets within
315/// the PTH file.
316namespace {
317class VISIBILITY_HIDDEN PTHFileLookup {
318public:
319 class Val {
Ted Kremenek8309c922008-12-11 23:36:38 +0000320 uint32_t TokenOff;
321 uint32_t PPCondOff;
Ted Kremenek325cd302008-12-03 00:38:03 +0000322 public:
Ted Kremenek8309c922008-12-11 23:36:38 +0000323 Val() : TokenOff(~0) {}
Ted Kremenek562db7f2009-01-27 00:01:05 +0000324 Val(uint32_t toff, uint32_t poff)
325 : TokenOff(toff), PPCondOff(poff) {}
Ted Kremenek325cd302008-12-03 00:38:03 +0000326
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000327 bool isValid() const { return TokenOff != ~((uint32_t)0); }
328
Ted Kremenek8309c922008-12-11 23:36:38 +0000329 uint32_t getTokenOffset() const {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000330 assert(isValid() && "PTHFileLookup entry initialized.");
Ted Kremenek8309c922008-12-11 23:36:38 +0000331 return TokenOff;
Ted Kremenek325cd302008-12-03 00:38:03 +0000332 }
333
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000334 uint32_t getPPCondOffset() const {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000335 assert(isValid() && "PTHFileLookup entry initialized.");
Ted Kremenek8309c922008-12-11 23:36:38 +0000336 return PPCondOff;
Ted Kremenek562db7f2009-01-27 00:01:05 +0000337 }
Ted Kremenek325cd302008-12-03 00:38:03 +0000338 };
339
340private:
341 llvm::StringMap<Val> FileMap;
342
343public:
344 PTHFileLookup() {};
345
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000346 bool isEmpty() const {
347 return FileMap.empty();
348 }
349
Ted Kremenek325cd302008-12-03 00:38:03 +0000350 Val Lookup(const FileEntry* FE) {
351 const char* s = FE->getName();
352 unsigned size = strlen(s);
353 return FileMap.GetOrCreateValue(s, s+size).getValue();
354 }
355
Chris Lattnerefb35342009-01-18 01:57:14 +0000356 void ReadTable(const unsigned char* D) {
Chris Lattner673a2862009-01-22 19:48:26 +0000357 uint32_t N = ReadLE32(D); // Read the length of the table.
Ted Kremenek325cd302008-12-03 00:38:03 +0000358
359 for ( ; N > 0; --N) { // The rest of the data is the table itself.
Chris Lattner673a2862009-01-22 19:48:26 +0000360 uint32_t Len = ReadLE32(D);
Chris Lattnerefb35342009-01-18 01:57:14 +0000361 const char* s = (const char *)D;
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000362 D += Len;
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000363
Chris Lattner673a2862009-01-22 19:48:26 +0000364 uint32_t TokenOff = ReadLE32(D);
365 uint32_t PPCondOff = ReadLE32(D);
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000366
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000367 FileMap.GetOrCreateValue(s, s+Len).getValue() =
Ted Kremenek562db7f2009-01-27 00:01:05 +0000368 Val(TokenOff, PPCondOff);
Ted Kremenek325cd302008-12-03 00:38:03 +0000369 }
370 }
371};
372} // end anonymous namespace
373
374//===----------------------------------------------------------------------===//
375// PTHManager methods.
376//===----------------------------------------------------------------------===//
377
378PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
Chris Lattnerefb35342009-01-18 01:57:14 +0000379 const unsigned char* idDataTable,
380 IdentifierInfo** perIDCache,
Ted Kremenek562db7f2009-01-27 00:01:05 +0000381 const unsigned char* sortedIdTable, unsigned numIds,
382 const unsigned char* spellingBase)
Ted Kremenekdb4c8e82008-12-03 01:16:39 +0000383: Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000384 IdDataTable(idDataTable), SortedIdTable(sortedIdTable),
Ted Kremenek562db7f2009-01-27 00:01:05 +0000385 NumIds(numIds), PP(0), SpellingBase(spellingBase) {}
Ted Kremenek325cd302008-12-03 00:38:03 +0000386
387PTHManager::~PTHManager() {
388 delete Buf;
389 delete (PTHFileLookup*) FileLookup;
Ted Kremenek93bdc492008-12-04 22:47:11 +0000390 free(PerIDCache);
Ted Kremenek325cd302008-12-03 00:38:03 +0000391}
392
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000393PTHManager* PTHManager::Create(const std::string& file) {
Ted Kremenek325cd302008-12-03 00:38:03 +0000394 // Memory map the PTH file.
395 llvm::OwningPtr<llvm::MemoryBuffer>
396 File(llvm::MemoryBuffer::getFile(file.c_str()));
397
398 if (!File)
399 return 0;
400
401 // Get the buffer ranges and check if there are at least three 32-bit
402 // words at the end of the file.
Chris Lattnerefb35342009-01-18 01:57:14 +0000403 const unsigned char* BufBeg = (unsigned char*)File->getBufferStart();
404 const unsigned char* BufEnd = (unsigned char*)File->getBufferEnd();
Ted Kremenek58b9f932009-01-26 21:43:14 +0000405
406 // Check the prologue of the file.
Ted Kremenek497aba32009-01-26 22:16:12 +0000407 if ((BufEnd - BufBeg) < (signed) (sizeof("cfe-pth") + 3 + 4) ||
Ted Kremenek58b9f932009-01-26 21:43:14 +0000408 memcmp(BufBeg, "cfe-pth", sizeof("cfe-pth") - 1) != 0)
409 return 0;
Ted Kremenek325cd302008-12-03 00:38:03 +0000410
Ted Kremenek169fc352009-01-26 21:50:21 +0000411 // Read the PTH version.
Ted Kremenek58b9f932009-01-26 21:43:14 +0000412 const unsigned char *p = BufBeg + (sizeof("cfe-pth") - 1);
Ted Kremenek169fc352009-01-26 21:50:21 +0000413 unsigned Version = ReadLE32(p);
414
415 if (Version != PTHManager::Version)
416 return 0;
417
418 // Compute the address of the index table at the end of the PTH file.
Ted Kremenek58b9f932009-01-26 21:43:14 +0000419 const unsigned char *EndTable = BufBeg + ReadLE32(p);
420
421 if (EndTable >= BufEnd)
422 return 0;
Ted Kremenek325cd302008-12-03 00:38:03 +0000423
424 // Construct the file lookup table. This will be used for mapping from
425 // FileEntry*'s to cached tokens.
Chris Lattnerefb35342009-01-18 01:57:14 +0000426 const unsigned char* FileTableOffset = EndTable + sizeof(uint32_t)*3;
Chris Lattner673a2862009-01-22 19:48:26 +0000427 const unsigned char* FileTable = BufBeg + ReadLE32(FileTableOffset);
Ted Kremenek325cd302008-12-03 00:38:03 +0000428
429 if (!(FileTable > BufBeg && FileTable < BufEnd)) {
430 assert(false && "Invalid PTH file.");
431 return 0; // FIXME: Proper error diagnostic?
432 }
433
434 llvm::OwningPtr<PTHFileLookup> FL(new PTHFileLookup());
435 FL->ReadTable(FileTable);
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000436
437 if (FL->isEmpty())
438 return 0;
Ted Kremenek325cd302008-12-03 00:38:03 +0000439
440 // Get the location of the table mapping from persistent ids to the
441 // data needed to reconstruct identifiers.
Chris Lattnerefb35342009-01-18 01:57:14 +0000442 const unsigned char* IDTableOffset = EndTable + sizeof(uint32_t)*1;
Chris Lattner673a2862009-01-22 19:48:26 +0000443 const unsigned char* IData = BufBeg + ReadLE32(IDTableOffset);
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000444
445 if (!(IData >= BufBeg && IData < BufEnd)) {
Ted Kremenek325cd302008-12-03 00:38:03 +0000446 assert(false && "Invalid PTH file.");
447 return 0; // FIXME: Proper error diagnostic?
448 }
449
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000450 // Get the location of the lexigraphically-sorted table of persistent IDs.
Chris Lattnerefb35342009-01-18 01:57:14 +0000451 const unsigned char* SortedIdTableOffset = EndTable + sizeof(uint32_t)*2;
Chris Lattner673a2862009-01-22 19:48:26 +0000452 const unsigned char* SortedIdTable = BufBeg + ReadLE32(SortedIdTableOffset);
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000453 if (!(SortedIdTable >= BufBeg && SortedIdTable < BufEnd)) {
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000454 assert(false && "Invalid PTH file.");
455 return 0; // FIXME: Proper error diagnostic?
456 }
457
Ted Kremenek562db7f2009-01-27 00:01:05 +0000458 // Get the location of the spelling cache.
459 const unsigned char* spellingBaseOffset = EndTable + sizeof(uint32_t)*4;
460 const unsigned char* spellingBase = BufBeg + ReadLE32(spellingBaseOffset);
461 if (!(spellingBase >= BufBeg && spellingBase < BufEnd)) {
462 assert(false && "Invalid PTH file.");
463 return 0;
464 }
465
Ted Kremenekdb4c8e82008-12-03 01:16:39 +0000466 // Get the number of IdentifierInfos and pre-allocate the identifier cache.
Chris Lattner673a2862009-01-22 19:48:26 +0000467 uint32_t NumIds = ReadLE32(IData);
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000468
Ted Kremenekdb4c8e82008-12-03 01:16:39 +0000469 // Pre-allocate the peristent ID -> IdentifierInfo* cache. We use calloc()
470 // so that we in the best case only zero out memory once when the OS returns
471 // us new pages.
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000472 IdentifierInfo** PerIDCache = 0;
Ted Kremenekdb4c8e82008-12-03 01:16:39 +0000473
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000474 if (NumIds) {
475 PerIDCache = (IdentifierInfo**)calloc(NumIds, sizeof(*PerIDCache));
476 if (!PerIDCache) {
477 assert(false && "Could not allocate Persistent ID cache.");
478 return 0;
479 }
Ted Kremenekdb4c8e82008-12-03 01:16:39 +0000480 }
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000481
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000482 // Create the new PTHManager.
483 return new PTHManager(File.take(), FL.take(), IData, PerIDCache,
Ted Kremenek562db7f2009-01-27 00:01:05 +0000484 SortedIdTable, NumIds, spellingBase);
Ted Kremenek325cd302008-12-03 00:38:03 +0000485}
Chris Lattnercbcd26c2009-01-18 02:57:21 +0000486IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) {
Ted Kremenek325cd302008-12-03 00:38:03 +0000487 // Look in the PTH file for the string data for the IdentifierInfo object.
Chris Lattnercbcd26c2009-01-18 02:57:21 +0000488 const unsigned char* TableEntry = IdDataTable + sizeof(uint32_t)*PersistentID;
Chris Lattnerefb35342009-01-18 01:57:14 +0000489 const unsigned char* IDData =
Chris Lattner673a2862009-01-22 19:48:26 +0000490 (const unsigned char*)Buf->getBufferStart() + ReadLE32(TableEntry);
Chris Lattnerefb35342009-01-18 01:57:14 +0000491 assert(IDData < (const unsigned char*)Buf->getBufferEnd());
Ted Kremenek325cd302008-12-03 00:38:03 +0000492
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000493 // Allocate the object.
Chris Lattnerefb35342009-01-18 01:57:14 +0000494 std::pair<IdentifierInfo,const unsigned char*> *Mem =
495 Alloc.Allocate<std::pair<IdentifierInfo,const unsigned char*> >();
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000496
497 Mem->second = IDData;
Ted Kremeneke807f852009-01-20 23:28:34 +0000498 IdentifierInfo *II = new ((void*) Mem) IdentifierInfo();
Ted Kremenek325cd302008-12-03 00:38:03 +0000499
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000500 // Store the new IdentifierInfo in the cache.
Chris Lattnercbcd26c2009-01-18 02:57:21 +0000501 PerIDCache[PersistentID] = II;
Ted Kremenek325cd302008-12-03 00:38:03 +0000502 return II;
503}
504
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000505IdentifierInfo* PTHManager::get(const char *NameStart, const char *NameEnd) {
506 unsigned min = 0;
507 unsigned max = NumIds;
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000508 unsigned Len = NameEnd - NameStart;
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000509
510 do {
511 unsigned i = (max - min) / 2 + min;
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000512 const unsigned char *Ptr = SortedIdTable + (i * 4);
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000513
514 // Read the persistentID.
Chris Lattner673a2862009-01-22 19:48:26 +0000515 unsigned perID = ReadLE32(Ptr);
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000516
517 // Get the IdentifierInfo.
518 IdentifierInfo* II = GetIdentifierInfo(perID);
519
520 // First compare the lengths.
521 unsigned IILen = II->getLength();
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000522 if (Len < IILen) goto IsLess;
523 if (Len > IILen) goto IsGreater;
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000524
525 // Now compare the strings!
526 {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000527 signed comp = strncmp(NameStart, II->getName(), Len);
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000528 if (comp < 0) goto IsLess;
529 if (comp > 0) goto IsGreater;
530 }
531 // We found a match!
532 return II;
533
534 IsGreater:
535 if (i == min) break;
536 min = i;
537 continue;
538
539 IsLess:
540 max = i;
541 assert(!(max == min) || (min == i));
542 }
Ted Kremenek4795ad02009-01-15 19:28:38 +0000543 while (min != max);
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000544
545 return 0;
546}
547
548
Chris Lattner3c727d62009-01-17 08:06:50 +0000549PTHLexer *PTHManager::CreateLexer(FileID FID) {
550 const FileEntry *FE = PP->getSourceManager().getFileEntryForID(FID);
Ted Kremenek325cd302008-12-03 00:38:03 +0000551 if (!FE)
552 return 0;
553
554 // Lookup the FileEntry object in our file lookup data structure. It will
555 // return a variant that indicates whether or not there is an offset within
556 // the PTH file that contains cached tokens.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000557 PTHFileLookup::Val FileData = ((PTHFileLookup*)FileLookup)->Lookup(FE);
Ted Kremenek325cd302008-12-03 00:38:03 +0000558
Ted Kremenek8309c922008-12-11 23:36:38 +0000559 if (!FileData.isValid()) // No tokens available.
Ted Kremenek325cd302008-12-03 00:38:03 +0000560 return 0;
561
Chris Lattnerefb35342009-01-18 01:57:14 +0000562 const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart();
Ted Kremenek325cd302008-12-03 00:38:03 +0000563 // Compute the offset of the token data within the buffer.
Chris Lattnerefb35342009-01-18 01:57:14 +0000564 const unsigned char* data = BufStart + FileData.getTokenOffset();
Ted Kremenekc07091c2008-12-12 18:34:08 +0000565
566 // Get the location of pp-conditional table.
Chris Lattnerefb35342009-01-18 01:57:14 +0000567 const unsigned char* ppcond = BufStart + FileData.getPPCondOffset();
Chris Lattner673a2862009-01-22 19:48:26 +0000568 uint32_t Len = ReadLE32(ppcond);
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000569 if (Len == 0) ppcond = 0;
Ted Kremeneka4d5bf52009-01-08 04:30:32 +0000570
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000571 assert(PP && "No preprocessor set yet!");
Ted Kremenek562db7f2009-01-27 00:01:05 +0000572 return new PTHLexer(*PP, FID, data, ppcond, *this);
Ted Kremenek325cd302008-12-03 00:38:03 +0000573}