blob: a9eb88a19dbce38ae63413c9243384e94064587c [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"
22#include "llvm/Support/Compiler.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/ADT/OwningPtr.h"
Ted Kremenek5f074262009-01-09 22:05:30 +000026#include "llvm/Support/Streams.h"
Ted Kremenek0c6a77b2008-12-03 00:38:03 +000027
Ted Kremenek274b2082008-11-12 21:37:15 +000028using namespace clang;
29
Ted Kremenek18d9afb2008-12-23 18:41:34 +000030#define DISK_TOKEN_SIZE (1+1+3+4+2)
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
36static inline uint8_t Read8(const char*& data) {
37 return (uint8_t) *(data++);
38}
39
40static inline uint32_t Read32(const char*& data) {
41 uint32_t V = (uint32_t) Read8(data);
42 V |= (((uint32_t) Read8(data)) << 8);
43 V |= (((uint32_t) Read8(data)) << 16);
44 V |= (((uint32_t) Read8(data)) << 24);
45 return V;
46}
47
Ted Kremeneke5680f32008-12-23 01:30:52 +000048//===----------------------------------------------------------------------===//
49// PTHLexer methods.
50//===----------------------------------------------------------------------===//
51
52PTHLexer::PTHLexer(Preprocessor& pp, SourceLocation fileloc, const char* D,
Ted Kremenek32a8ad52009-01-08 04:30:32 +000053 const char* ppcond,
Ted Kremenek5f074262009-01-09 22:05:30 +000054 PTHSpellingSearch& mySpellingSrch,
Ted Kremenek32a8ad52009-01-08 04:30:32 +000055 PTHManager& PM)
Ted Kremeneke5680f32008-12-23 01:30:52 +000056 : PreprocessorLexer(&pp, fileloc), TokBuf(D), CurPtr(D), LastHashTokPtr(0),
Ted Kremenek5f074262009-01-09 22:05:30 +000057 PPCond(ppcond), CurPPCondPtr(ppcond), MySpellingSrch(mySpellingSrch),
58 PTHMgr(PM)
59{
60 FileID = fileloc.getFileID();
61}
Ted Kremeneke5680f32008-12-23 01:30:52 +000062
63void PTHLexer::Lex(Token& Tok) {
64LexNextToken:
Ted Kremeneke5680f32008-12-23 01:30:52 +000065
Ted Kremenek866bdf72008-12-23 02:30:15 +000066 //===--------------------------------------==//
67 // Read the raw token data.
68 //===--------------------------------------==//
69
70 // Shadow CurPtr into an automatic variable.
71 const unsigned char *CurPtrShadow = (const unsigned char*) CurPtr;
72
73 // Read in the data for the token. 14 bytes in total.
74 tok::TokenKind k = (tok::TokenKind) CurPtrShadow[0];
75 Token::TokenFlags flags = (Token::TokenFlags) CurPtrShadow[1];
76
Ted Kremenek6b1c9702008-12-23 18:27:26 +000077 uint32_t perID = ((uint32_t) CurPtrShadow[2])
Ted Kremenek866bdf72008-12-23 02:30:15 +000078 | (((uint32_t) CurPtrShadow[3]) << 8)
Ted Kremenek18d9afb2008-12-23 18:41:34 +000079 | (((uint32_t) CurPtrShadow[4]) << 16);
Ted Kremenek866bdf72008-12-23 02:30:15 +000080
Ted Kremenek18d9afb2008-12-23 18:41:34 +000081 uint32_t FileOffset = ((uint32_t) CurPtrShadow[5])
82 | (((uint32_t) CurPtrShadow[6]) << 8)
83 | (((uint32_t) CurPtrShadow[7]) << 16)
84 | (((uint32_t) CurPtrShadow[8]) << 24);
Ted Kremenek866bdf72008-12-23 02:30:15 +000085
Ted Kremenek18d9afb2008-12-23 18:41:34 +000086 uint32_t Len = ((uint32_t) CurPtrShadow[9])
87 | (((uint32_t) CurPtrShadow[10]) << 8);
Ted Kremenek866bdf72008-12-23 02:30:15 +000088
89 CurPtr = (const char*) (CurPtrShadow + DISK_TOKEN_SIZE);
90
91 //===--------------------------------------==//
92 // Construct the token itself.
93 //===--------------------------------------==//
94
95 Tok.startToken();
96 Tok.setKind(k);
Ted Kremenek59d08cb2008-12-23 19:24:24 +000097 Tok.setFlag(flags);
98 assert(!LexingRawMode);
Ted Kremenek6b1c9702008-12-23 18:27:26 +000099 Tok.setIdentifierInfo(perID ? PTHMgr.GetIdentifierInfo(perID-1) : 0);
Ted Kremenek866bdf72008-12-23 02:30:15 +0000100 Tok.setLocation(SourceLocation::getFileLoc(FileID, FileOffset));
101 Tok.setLength(Len);
102
103 //===--------------------------------------==//
104 // Process the token.
105 //===--------------------------------------==//
Ted Kremenek5f074262009-01-09 22:05:30 +0000106#if 0
107 SourceManager& SM = PP->getSourceManager();
108 llvm::cerr << SM.getFileEntryForID(FileID)->getName()
109 << ':' << SM.getLogicalLineNumber(Tok.getLocation())
110 << ':' << SM.getLogicalColumnNumber(Tok.getLocation())
111 << '\n';
112#endif
Ted Kremeneke5680f32008-12-23 01:30:52 +0000113
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000114 if (k == tok::identifier) {
115 MIOpt.ReadToken();
116 return PP->HandleIdentifier(Tok);
117 }
118
119 if (k == tok::eof) {
Ted Kremeneke5680f32008-12-23 01:30:52 +0000120 // Save the end-of-file token.
121 EofToken = Tok;
122
123 Preprocessor *PPCache = PP;
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000124
125 assert(!ParsingPreprocessorDirective);
126 assert(!LexingRawMode);
127
128 // FIXME: Issue diagnostics similar to Lexer.
129 if (PP->HandleEndOfFile(Tok, false))
Ted Kremeneke5680f32008-12-23 01:30:52 +0000130 return;
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000131
Ted Kremeneke5680f32008-12-23 01:30:52 +0000132 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
133 return PPCache->Lex(Tok);
134 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000135
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000136 if (k == tok::hash && Tok.isAtStartOfLine()) {
137 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
138 assert(!LexingRawMode);
139 PP->HandleDirective(Tok);
140
141 if (PP->isCurrentLexer(this))
142 goto LexNextToken;
143
144 return PP->Lex(Tok);
145 }
146
147 if (k == tok::eom) {
148 assert(ParsingPreprocessorDirective);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000149 ParsingPreprocessorDirective = false;
150 return;
151 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000152
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000153 MIOpt.ReadToken();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000154}
155
156// FIXME: We can just grab the last token instead of storing a copy
157// into EofToken.
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000158void PTHLexer::getEOF(Token& Tok) {
Ted Kremenekdefb7092009-01-09 00:36:11 +0000159 assert(EofToken.is(tok::eof));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000160 Tok = EofToken;
161}
162
163void PTHLexer::DiscardToEndOfLine() {
164 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
165 "Must be in a preprocessing directive!");
166
167 // We assume that if the preprocessor wishes to discard to the end of
168 // the line that it also means to end the current preprocessor directive.
169 ParsingPreprocessorDirective = false;
170
171 // Skip tokens by only peeking at their token kind and the flags.
172 // We don't need to actually reconstruct full tokens from the token buffer.
173 // This saves some copies and it also reduces IdentifierInfo* lookup.
174 const char* p = CurPtr;
175 while (1) {
176 // Read the token kind. Are we at the end of the file?
177 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
178 if (x == tok::eof) break;
179
180 // Read the token flags. Are we at the start of the next line?
181 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
182 if (y & Token::StartOfLine) break;
183
184 // Skip to the next token.
185 p += DISK_TOKEN_SIZE;
186 }
187
188 CurPtr = p;
189}
190
Ted Kremenek268ee702008-12-12 18:34:08 +0000191/// SkipBlock - Used by Preprocessor to skip the current conditional block.
192bool PTHLexer::SkipBlock() {
193 assert(CurPPCondPtr && "No cached PP conditional information.");
194 assert(LastHashTokPtr && "No known '#' token.");
195
Ted Kremenek41a26602008-12-12 22:05:38 +0000196 const char* HashEntryI = 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000197 uint32_t Offset;
198 uint32_t TableIdx;
199
200 do {
Ted Kremenek41a26602008-12-12 22:05:38 +0000201 // Read the token offset from the side-table.
Ted Kremenek268ee702008-12-12 18:34:08 +0000202 Offset = Read32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000203
204 // Read the target table index from the side-table.
Ted Kremenek268ee702008-12-12 18:34:08 +0000205 TableIdx = Read32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000206
207 // Compute the actual memory address of the '#' token data for this entry.
208 HashEntryI = TokBuf + Offset;
209
210 // Optmization: "Sibling jumping". #if...#else...#endif blocks can
211 // contain nested blocks. In the side-table we can jump over these
212 // nested blocks instead of doing a linear search if the next "sibling"
213 // entry is not at a location greater than LastHashTokPtr.
214 if (HashEntryI < LastHashTokPtr && TableIdx) {
215 // In the side-table we are still at an entry for a '#' token that
216 // is earlier than the last one we saw. Check if the location we would
217 // stride gets us closer.
218 const char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
219 assert(NextPPCondPtr >= CurPPCondPtr);
220 // Read where we should jump to.
221 uint32_t TmpOffset = Read32(NextPPCondPtr);
222 const char* HashEntryJ = TokBuf + TmpOffset;
223
224 if (HashEntryJ <= LastHashTokPtr) {
225 // Jump directly to the next entry in the side table.
226 HashEntryI = HashEntryJ;
227 Offset = TmpOffset;
228 TableIdx = Read32(NextPPCondPtr);
229 CurPPCondPtr = NextPPCondPtr;
230 }
231 }
Ted Kremenek268ee702008-12-12 18:34:08 +0000232 }
Ted Kremenek41a26602008-12-12 22:05:38 +0000233 while (HashEntryI < LastHashTokPtr);
234 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
Ted Kremenek268ee702008-12-12 18:34:08 +0000235 assert(TableIdx && "No jumping from #endifs.");
236
237 // Update our side-table iterator.
238 const char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
239 assert(NextPPCondPtr >= CurPPCondPtr);
240 CurPPCondPtr = NextPPCondPtr;
241
242 // Read where we should jump to.
Ted Kremenek41a26602008-12-12 22:05:38 +0000243 HashEntryI = TokBuf + Read32(NextPPCondPtr);
Ted Kremenek268ee702008-12-12 18:34:08 +0000244 uint32_t NextIdx = Read32(NextPPCondPtr);
245
246 // By construction NextIdx will be zero if this is a #endif. This is useful
247 // to know to obviate lexing another token.
248 bool isEndif = NextIdx == 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000249
250 // This case can occur when we see something like this:
251 //
252 // #if ...
253 // /* a comment or nothing */
254 // #elif
255 //
256 // If we are skipping the first #if block it will be the case that CurPtr
257 // already points 'elif'. Just return.
258
Ted Kremenek41a26602008-12-12 22:05:38 +0000259 if (CurPtr > HashEntryI) {
260 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
Ted Kremenek268ee702008-12-12 18:34:08 +0000261 // Did we reach a #endif? If so, go ahead and consume that token as well.
262 if (isEndif)
Ted Kremeneke5680f32008-12-23 01:30:52 +0000263 CurPtr += DISK_TOKEN_SIZE*2;
Ted Kremenek268ee702008-12-12 18:34:08 +0000264 else
Ted Kremenek41a26602008-12-12 22:05:38 +0000265 LastHashTokPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000266
267 return isEndif;
268 }
269
270 // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
Ted Kremenek41a26602008-12-12 22:05:38 +0000271 CurPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000272
273 // Update the location of the last observed '#'. This is useful if we
274 // are skipping multiple blocks.
275 LastHashTokPtr = CurPtr;
Ted Kremenek268ee702008-12-12 18:34:08 +0000276
Ted Kremeneke5680f32008-12-23 01:30:52 +0000277 // Skip the '#' token.
278 assert(((tok::TokenKind) (unsigned char) *CurPtr) == tok::hash);
279 CurPtr += DISK_TOKEN_SIZE;
280
Ted Kremenek268ee702008-12-12 18:34:08 +0000281 // Did we reach a #endif? If so, go ahead and consume that token as well.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000282 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
Ted Kremenek268ee702008-12-12 18:34:08 +0000283
284 return isEndif;
285}
286
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000287SourceLocation PTHLexer::getSourceLocation() {
288 // getLocation is not on the hot path. It is used to get the location of
289 // the next token when transitioning back to this lexer when done
290 // handling a #included file. Just read the necessary data from the token
291 // data buffer to construct the SourceLocation object.
292 // NOTE: This is a virtual function; hence it is defined out-of-line.
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000293 const char* p = CurPtr + (1 + 1 + 3);
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000294 uint32_t offset =
295 ((uint32_t) ((uint8_t) p[0]))
296 | (((uint32_t) ((uint8_t) p[1])) << 8)
297 | (((uint32_t) ((uint8_t) p[2])) << 16)
298 | (((uint32_t) ((uint8_t) p[3])) << 24);
299 return SourceLocation::getFileLoc(FileID, offset);
300}
301
Ted Kremenek5f074262009-01-09 22:05:30 +0000302//===----------------------------------------------------------------------===//
303// getSpelling() - Use cached data in PTH files for getSpelling().
304//===----------------------------------------------------------------------===//
305
306unsigned PTHManager::getSpelling(unsigned FileID, unsigned fpos,
307 const char *& Buffer) {
308
309 llvm::DenseMap<unsigned,PTHSpellingSearch*>::iterator I =
310 SpellingMap.find(FileID);
311
312 if (I == SpellingMap.end())
313 return 0;
314
315 return I->second->getSpellingBinarySearch(fpos, Buffer);
316}
317
318unsigned PTHManager::getSpellingAtPTHOffset(unsigned PTHOffset,
319 const char *& Buffer) {
320
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000321 const char* p = Buf->getBufferStart() + PTHOffset;
322 assert(p < Buf->getBufferEnd());
323
324 // The string is prefixed by 16 bits for its length, followed by the string
325 // itself.
326 unsigned len = ((unsigned) ((uint8_t) p[0]))
327 | (((unsigned) ((uint8_t) p[1])) << 8);
328
329 Buffer = p + 2;
330 return len;
331}
332
Ted Kremenek5f074262009-01-09 22:05:30 +0000333unsigned PTHSpellingSearch::getSpellingLinearSearch(unsigned fpos,
334 const char *&Buffer) {
335 const char* p = LinearItr;
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000336 unsigned len = 0;
Ted Kremenek5f074262009-01-09 22:05:30 +0000337
338 if (!SpellingsLeft)
339 return getSpellingBinarySearch(fpos, Buffer);
340
341 do {
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000342 uint32_t TokOffset =
343 ((uint32_t) ((uint8_t) p[0]))
344 | (((uint32_t) ((uint8_t) p[1])) << 8)
345 | (((uint32_t) ((uint8_t) p[2])) << 16)
346 | (((uint32_t) ((uint8_t) p[3])) << 24);
347
348 if (TokOffset > fpos)
Ted Kremenek5f074262009-01-09 22:05:30 +0000349 return getSpellingBinarySearch(fpos, Buffer);
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000350
351 --SpellingsLeft;
352
353 // Did we find a matching token offset for this spelling?
354 if (TokOffset == fpos) {
355 uint32_t SpellingPTHOffset =
356 ((uint32_t) ((uint8_t) p[4]))
357 | (((uint32_t) ((uint8_t) p[5])) << 8)
358 | (((uint32_t) ((uint8_t) p[6])) << 16)
359 | (((uint32_t) ((uint8_t) p[7])) << 24);
360
Ted Kremenek5f074262009-01-09 22:05:30 +0000361 len = PTHMgr.getSpellingAtPTHOffset(SpellingPTHOffset, Buffer);
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000362 break;
363 }
364
365 // No match. Keep on looking.
366 p += sizeof(uint32_t)*2;
367 }
Ted Kremenek5f074262009-01-09 22:05:30 +0000368 while (SpellingsLeft);
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000369
Ted Kremenek5f074262009-01-09 22:05:30 +0000370 LinearItr = p;
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000371 return len;
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000372}
373
Ted Kremenek5f074262009-01-09 22:05:30 +0000374unsigned PTHSpellingSearch::getSpellingBinarySearch(unsigned fpos,
375 const char *& Buffer) {
376
377 assert ((TableEnd - TableBeg) % SpellingEntrySize == 0);
378
379 unsigned min = 0;
380 const char* tb = TableBeg;
381 unsigned max = (TableEnd - tb) / SpellingEntrySize;
382
383 while (min != max) {
384 unsigned i = (max - min) / 2 + min;
385 const char* p = tb + (i * SpellingEntrySize);
386
387 uint32_t TokOffset =
388 ((uint32_t) ((uint8_t) p[0]))
389 | (((uint32_t) ((uint8_t) p[1])) << 8)
390 | (((uint32_t) ((uint8_t) p[2])) << 16)
391 | (((uint32_t) ((uint8_t) p[3])) << 24);
392
393 if (TokOffset > fpos) {
394 max = i;
395 continue;
396 }
397
398 if (TokOffset < fpos) {
399 min = i;
400 continue;
401 }
402
403 uint32_t SpellingPTHOffset =
404 ((uint32_t) ((uint8_t) p[4]))
405 | (((uint32_t) ((uint8_t) p[5])) << 8)
406 | (((uint32_t) ((uint8_t) p[6])) << 16)
407 | (((uint32_t) ((uint8_t) p[7])) << 24);
408
409 return PTHMgr.getSpellingAtPTHOffset(SpellingPTHOffset, Buffer);
410 }
411
412 return 0;
413}
414
415unsigned PTHLexer::getSpelling(SourceLocation sloc, const char *&Buffer) {
416 SourceManager& SM = PP->getSourceManager();
417 sloc = SM.getPhysicalLoc(sloc);
418 unsigned fid = SM.getCanonicalFileID(sloc);
419 unsigned fpos = SM.getFullFilePos(sloc);
420
421 if (fid == FileID)
422 return MySpellingSrch.getSpellingLinearSearch(fpos, Buffer);
423
424 return PTHMgr.getSpelling(fid, fpos, Buffer);
425}
426
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000427//===----------------------------------------------------------------------===//
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000428// Internal Data Structures for PTH file lookup and resolving identifiers.
429//===----------------------------------------------------------------------===//
430
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000431
432/// PTHFileLookup - This internal data structure is used by the PTHManager
433/// to map from FileEntry objects managed by FileManager to offsets within
434/// the PTH file.
435namespace {
436class VISIBILITY_HIDDEN PTHFileLookup {
437public:
438 class Val {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000439 uint32_t TokenOff;
440 uint32_t PPCondOff;
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000441 uint32_t SpellingOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000442
443 public:
Ted Kremenekfb645b62008-12-11 23:36:38 +0000444 Val() : TokenOff(~0) {}
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000445 Val(uint32_t toff, uint32_t poff, uint32_t soff)
446 : TokenOff(toff), PPCondOff(poff), SpellingOff(soff) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000447
Ted Kremenekfb645b62008-12-11 23:36:38 +0000448 uint32_t getTokenOffset() const {
449 assert(TokenOff != ~((uint32_t)0) && "PTHFileLookup entry initialized.");
450 return TokenOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000451 }
452
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000453 uint32_t getPPCondOffset() const {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000454 assert(TokenOff != ~((uint32_t)0) && "PTHFileLookup entry initialized.");
455 return PPCondOff;
456 }
457
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000458 uint32_t getSpellingOffset() const {
459 assert(TokenOff != ~((uint32_t)0) && "PTHFileLookup entry initialized.");
460 return SpellingOff;
461 }
462
Ted Kremenekfb645b62008-12-11 23:36:38 +0000463 bool isValid() const { return TokenOff != ~((uint32_t)0); }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000464 };
465
466private:
467 llvm::StringMap<Val> FileMap;
468
469public:
470 PTHFileLookup() {};
471
472 Val Lookup(const FileEntry* FE) {
473 const char* s = FE->getName();
474 unsigned size = strlen(s);
475 return FileMap.GetOrCreateValue(s, s+size).getValue();
476 }
477
478 void ReadTable(const char* D) {
479 uint32_t N = Read32(D); // Read the length of the table.
480
481 for ( ; N > 0; --N) { // The rest of the data is the table itself.
482 uint32_t len = Read32(D);
483 const char* s = D;
484 D += len;
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000485
Ted Kremenekfb645b62008-12-11 23:36:38 +0000486 uint32_t TokenOff = Read32(D);
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000487 uint32_t PPCondOff = Read32(D);
488 uint32_t SpellingOff = Read32(D);
489
490 FileMap.GetOrCreateValue(s, s+len).getValue() =
491 Val(TokenOff, PPCondOff, SpellingOff);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000492 }
493 }
494};
495} // end anonymous namespace
496
497//===----------------------------------------------------------------------===//
498// PTHManager methods.
499//===----------------------------------------------------------------------===//
500
501PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
Ted Kremenekcf58e622008-12-10 19:40:23 +0000502 const char* idDataTable, IdentifierInfo** perIDCache,
Ted Kremenek6183e482008-12-03 01:16:39 +0000503 Preprocessor& pp)
504: Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
505 IdDataTable(idDataTable), ITable(pp.getIdentifierTable()), PP(pp) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000506
507PTHManager::~PTHManager() {
508 delete Buf;
509 delete (PTHFileLookup*) FileLookup;
Ted Kremenek0e50b6e2008-12-04 22:47:11 +0000510 free(PerIDCache);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000511}
512
513PTHManager* PTHManager::Create(const std::string& file, Preprocessor& PP) {
514
515 // Memory map the PTH file.
516 llvm::OwningPtr<llvm::MemoryBuffer>
517 File(llvm::MemoryBuffer::getFile(file.c_str()));
518
519 if (!File)
520 return 0;
521
522 // Get the buffer ranges and check if there are at least three 32-bit
523 // words at the end of the file.
524 const char* BufBeg = File->getBufferStart();
525 const char* BufEnd = File->getBufferEnd();
526
527 if(!(BufEnd > BufBeg + sizeof(uint32_t)*3)) {
528 assert(false && "Invalid PTH file.");
529 return 0; // FIXME: Proper error diagnostic?
530 }
531
532 // Compute the address of the index table at the end of the PTH file.
533 // This table contains the offset of the file lookup table, the
534 // persistent ID -> identifer data table.
535 const char* EndTable = BufEnd - sizeof(uint32_t)*3;
536
537 // Construct the file lookup table. This will be used for mapping from
538 // FileEntry*'s to cached tokens.
539 const char* FileTableOffset = EndTable + sizeof(uint32_t)*2;
540 const char* FileTable = BufBeg + Read32(FileTableOffset);
541
542 if (!(FileTable > BufBeg && FileTable < BufEnd)) {
543 assert(false && "Invalid PTH file.");
544 return 0; // FIXME: Proper error diagnostic?
545 }
546
547 llvm::OwningPtr<PTHFileLookup> FL(new PTHFileLookup());
548 FL->ReadTable(FileTable);
549
550 // Get the location of the table mapping from persistent ids to the
551 // data needed to reconstruct identifiers.
552 const char* IDTableOffset = EndTable + sizeof(uint32_t)*1;
553 const char* IData = BufBeg + Read32(IDTableOffset);
554 if (!(IData > BufBeg && IData < BufEnd)) {
555 assert(false && "Invalid PTH file.");
556 return 0; // FIXME: Proper error diagnostic?
557 }
558
Ted Kremenek6183e482008-12-03 01:16:39 +0000559 // Get the number of IdentifierInfos and pre-allocate the identifier cache.
560 uint32_t NumIds = Read32(IData);
561
562 // Pre-allocate the peristent ID -> IdentifierInfo* cache. We use calloc()
563 // so that we in the best case only zero out memory once when the OS returns
564 // us new pages.
565 IdentifierInfo** PerIDCache =
566 (IdentifierInfo**) calloc(NumIds, sizeof(*PerIDCache));
567
568 if (!PerIDCache) {
569 assert(false && "Could not allocate Persistent ID cache.");
570 return 0;
571 }
572
573 // Create the new lexer.
574 return new PTHManager(File.take(), FL.take(), IData, PerIDCache, PP);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000575}
576
Ted Kremenek866bdf72008-12-23 02:30:15 +0000577IdentifierInfo* PTHManager::GetIdentifierInfo(unsigned persistentID) {
578
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000579 // Check if the IdentifierInfo has already been resolved.
Ted Kremenekcf58e622008-12-10 19:40:23 +0000580 IdentifierInfo*& II = PerIDCache[persistentID];
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000581 if (II) return II;
582
583 // Look in the PTH file for the string data for the IdentifierInfo object.
584 const char* TableEntry = IdDataTable + sizeof(uint32_t) * persistentID;
585 const char* IDData = Buf->getBufferStart() + Read32(TableEntry);
586 assert(IDData < Buf->getBufferEnd());
587
588 // Read the length of the string.
589 uint32_t len = Read32(IDData);
590
591 // Get the IdentifierInfo* with the specified string.
592 II = &ITable.get(IDData, IDData+len);
593 return II;
594}
595
596PTHLexer* PTHManager::CreateLexer(unsigned FileID, const FileEntry* FE) {
597
598 if (!FE)
599 return 0;
600
601 // Lookup the FileEntry object in our file lookup data structure. It will
602 // return a variant that indicates whether or not there is an offset within
603 // the PTH file that contains cached tokens.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000604 PTHFileLookup::Val FileData = ((PTHFileLookup*) FileLookup)->Lookup(FE);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000605
Ted Kremenekfb645b62008-12-11 23:36:38 +0000606 if (!FileData.isValid()) // No tokens available.
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000607 return 0;
608
609 // Compute the offset of the token data within the buffer.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000610 const char* data = Buf->getBufferStart() + FileData.getTokenOffset();
Ted Kremenek268ee702008-12-12 18:34:08 +0000611
612 // Get the location of pp-conditional table.
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000613 const char* ppcond = Buf->getBufferStart() + FileData.getPPCondOffset();
614 uint32_t len = Read32(ppcond);
Ted Kremenek268ee702008-12-12 18:34:08 +0000615 if (len == 0) ppcond = 0;
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000616
617 // Get the location of the spelling table.
618 const char* spellingTable = Buf->getBufferStart() +
619 FileData.getSpellingOffset();
620
621 len = Read32(spellingTable);
622 if (len == 0) spellingTable = 0;
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000623
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000624 assert(data < Buf->getBufferEnd());
Ted Kremenek5f074262009-01-09 22:05:30 +0000625
626 // Create the SpellingSearch object for this FileID.
627 PTHSpellingSearch* ss = new PTHSpellingSearch(*this, len, spellingTable);
628 SpellingMap[FileID] = ss;
629
Ted Kremenek268ee702008-12-12 18:34:08 +0000630 return new PTHLexer(PP, SourceLocation::getFileLoc(FileID, 0), data, ppcond,
Ted Kremenek5f074262009-01-09 22:05:30 +0000631 *ss, *this);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000632}