blob: fd7c367c70ae3310ed10a2040d13e8c693f4619e [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 Kremenek274b2082008-11-12 21:37:15 +000026using namespace clang;
27
Ted Kremenek18d9afb2008-12-23 18:41:34 +000028#define DISK_TOKEN_SIZE (1+1+3+4+2)
Ted Kremenek268ee702008-12-12 18:34:08 +000029
Ted Kremenek0c6a77b2008-12-03 00:38:03 +000030//===----------------------------------------------------------------------===//
31// Utility methods for reading from the mmap'ed PTH file.
32//===----------------------------------------------------------------------===//
33
34static inline uint8_t Read8(const char*& data) {
35 return (uint8_t) *(data++);
36}
37
38static inline uint32_t Read32(const char*& data) {
39 uint32_t V = (uint32_t) Read8(data);
40 V |= (((uint32_t) Read8(data)) << 8);
41 V |= (((uint32_t) Read8(data)) << 16);
42 V |= (((uint32_t) Read8(data)) << 24);
43 return V;
44}
45
Ted Kremeneke5680f32008-12-23 01:30:52 +000046//===----------------------------------------------------------------------===//
47// PTHLexer methods.
48//===----------------------------------------------------------------------===//
49
Chris Lattner2b2453a2009-01-17 06:22:33 +000050PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const char *D,
51 const char *ppcond,
52 PTHSpellingSearch &mySpellingSrch, PTHManager &PM)
53 : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(0),
Ted Kremenek5f074262009-01-09 22:05:30 +000054 PPCond(ppcond), CurPPCondPtr(ppcond), MySpellingSrch(mySpellingSrch),
Chris Lattner2b2453a2009-01-17 06:22:33 +000055 PTHMgr(PM) {
56
57 FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID);
Ted Kremenek5f074262009-01-09 22:05:30 +000058}
Ted Kremeneke5680f32008-12-23 01:30:52 +000059
60void PTHLexer::Lex(Token& Tok) {
61LexNextToken:
Ted Kremeneke5680f32008-12-23 01:30:52 +000062
Ted Kremenek866bdf72008-12-23 02:30:15 +000063 //===--------------------------------------==//
64 // Read the raw token data.
65 //===--------------------------------------==//
66
67 // Shadow CurPtr into an automatic variable.
68 const unsigned char *CurPtrShadow = (const unsigned char*) CurPtr;
69
70 // Read in the data for the token. 14 bytes in total.
71 tok::TokenKind k = (tok::TokenKind) CurPtrShadow[0];
72 Token::TokenFlags flags = (Token::TokenFlags) CurPtrShadow[1];
73
Ted Kremenek6b1c9702008-12-23 18:27:26 +000074 uint32_t perID = ((uint32_t) CurPtrShadow[2])
Ted Kremenek866bdf72008-12-23 02:30:15 +000075 | (((uint32_t) CurPtrShadow[3]) << 8)
Ted Kremenek18d9afb2008-12-23 18:41:34 +000076 | (((uint32_t) CurPtrShadow[4]) << 16);
Ted Kremenek866bdf72008-12-23 02:30:15 +000077
Ted Kremenek18d9afb2008-12-23 18:41:34 +000078 uint32_t FileOffset = ((uint32_t) CurPtrShadow[5])
79 | (((uint32_t) CurPtrShadow[6]) << 8)
80 | (((uint32_t) CurPtrShadow[7]) << 16)
81 | (((uint32_t) CurPtrShadow[8]) << 24);
Ted Kremenek866bdf72008-12-23 02:30:15 +000082
Ted Kremenek18d9afb2008-12-23 18:41:34 +000083 uint32_t Len = ((uint32_t) CurPtrShadow[9])
84 | (((uint32_t) CurPtrShadow[10]) << 8);
Ted Kremenek866bdf72008-12-23 02:30:15 +000085
86 CurPtr = (const char*) (CurPtrShadow + DISK_TOKEN_SIZE);
87
88 //===--------------------------------------==//
89 // Construct the token itself.
90 //===--------------------------------------==//
91
92 Tok.startToken();
93 Tok.setKind(k);
Ted Kremenek59d08cb2008-12-23 19:24:24 +000094 Tok.setFlag(flags);
95 assert(!LexingRawMode);
Ted Kremenek6b1c9702008-12-23 18:27:26 +000096 Tok.setIdentifierInfo(perID ? PTHMgr.GetIdentifierInfo(perID-1) : 0);
Chris Lattner2b2453a2009-01-17 06:22:33 +000097 Tok.setLocation(FileStartLoc.getFileLocWithOffset(FileOffset));
Ted Kremenek866bdf72008-12-23 02:30:15 +000098 Tok.setLength(Len);
99
100 //===--------------------------------------==//
101 // Process the token.
102 //===--------------------------------------==//
Ted Kremenek5f074262009-01-09 22:05:30 +0000103#if 0
104 SourceManager& SM = PP->getSourceManager();
105 llvm::cerr << SM.getFileEntryForID(FileID)->getName()
106 << ':' << SM.getLogicalLineNumber(Tok.getLocation())
107 << ':' << SM.getLogicalColumnNumber(Tok.getLocation())
108 << '\n';
109#endif
Ted Kremeneke5680f32008-12-23 01:30:52 +0000110
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000111 if (k == tok::identifier) {
112 MIOpt.ReadToken();
113 return PP->HandleIdentifier(Tok);
114 }
115
116 if (k == tok::eof) {
Ted Kremeneke5680f32008-12-23 01:30:52 +0000117 // Save the end-of-file token.
118 EofToken = Tok;
119
120 Preprocessor *PPCache = PP;
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000121
122 assert(!ParsingPreprocessorDirective);
123 assert(!LexingRawMode);
124
125 // FIXME: Issue diagnostics similar to Lexer.
126 if (PP->HandleEndOfFile(Tok, false))
Ted Kremeneke5680f32008-12-23 01:30:52 +0000127 return;
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000128
Ted Kremeneke5680f32008-12-23 01:30:52 +0000129 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
130 return PPCache->Lex(Tok);
131 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000132
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000133 if (k == tok::hash && Tok.isAtStartOfLine()) {
134 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
135 assert(!LexingRawMode);
136 PP->HandleDirective(Tok);
137
138 if (PP->isCurrentLexer(this))
139 goto LexNextToken;
140
141 return PP->Lex(Tok);
142 }
143
144 if (k == tok::eom) {
145 assert(ParsingPreprocessorDirective);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000146 ParsingPreprocessorDirective = false;
147 return;
148 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000149
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000150 MIOpt.ReadToken();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000151}
152
153// FIXME: We can just grab the last token instead of storing a copy
154// into EofToken.
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000155void PTHLexer::getEOF(Token& Tok) {
Ted Kremenekdefb7092009-01-09 00:36:11 +0000156 assert(EofToken.is(tok::eof));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000157 Tok = EofToken;
158}
159
160void PTHLexer::DiscardToEndOfLine() {
161 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
162 "Must be in a preprocessing directive!");
163
164 // We assume that if the preprocessor wishes to discard to the end of
165 // the line that it also means to end the current preprocessor directive.
166 ParsingPreprocessorDirective = false;
167
168 // Skip tokens by only peeking at their token kind and the flags.
169 // We don't need to actually reconstruct full tokens from the token buffer.
170 // This saves some copies and it also reduces IdentifierInfo* lookup.
171 const char* p = CurPtr;
172 while (1) {
173 // Read the token kind. Are we at the end of the file?
174 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
175 if (x == tok::eof) break;
176
177 // Read the token flags. Are we at the start of the next line?
178 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
179 if (y & Token::StartOfLine) break;
180
181 // Skip to the next token.
182 p += DISK_TOKEN_SIZE;
183 }
184
185 CurPtr = p;
186}
187
Ted Kremenek268ee702008-12-12 18:34:08 +0000188/// SkipBlock - Used by Preprocessor to skip the current conditional block.
189bool PTHLexer::SkipBlock() {
190 assert(CurPPCondPtr && "No cached PP conditional information.");
191 assert(LastHashTokPtr && "No known '#' token.");
192
Ted Kremenek41a26602008-12-12 22:05:38 +0000193 const char* HashEntryI = 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000194 uint32_t Offset;
195 uint32_t TableIdx;
196
197 do {
Ted Kremenek41a26602008-12-12 22:05:38 +0000198 // Read the token offset from the side-table.
Ted Kremenek268ee702008-12-12 18:34:08 +0000199 Offset = Read32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000200
201 // Read the target table index from the side-table.
Ted Kremenek268ee702008-12-12 18:34:08 +0000202 TableIdx = Read32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000203
204 // Compute the actual memory address of the '#' token data for this entry.
205 HashEntryI = TokBuf + Offset;
206
207 // Optmization: "Sibling jumping". #if...#else...#endif blocks can
208 // contain nested blocks. In the side-table we can jump over these
209 // nested blocks instead of doing a linear search if the next "sibling"
210 // entry is not at a location greater than LastHashTokPtr.
211 if (HashEntryI < LastHashTokPtr && TableIdx) {
212 // In the side-table we are still at an entry for a '#' token that
213 // is earlier than the last one we saw. Check if the location we would
214 // stride gets us closer.
215 const char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
216 assert(NextPPCondPtr >= CurPPCondPtr);
217 // Read where we should jump to.
218 uint32_t TmpOffset = Read32(NextPPCondPtr);
219 const char* HashEntryJ = TokBuf + TmpOffset;
220
221 if (HashEntryJ <= LastHashTokPtr) {
222 // Jump directly to the next entry in the side table.
223 HashEntryI = HashEntryJ;
224 Offset = TmpOffset;
225 TableIdx = Read32(NextPPCondPtr);
226 CurPPCondPtr = NextPPCondPtr;
227 }
228 }
Ted Kremenek268ee702008-12-12 18:34:08 +0000229 }
Ted Kremenek41a26602008-12-12 22:05:38 +0000230 while (HashEntryI < LastHashTokPtr);
231 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
Ted Kremenek268ee702008-12-12 18:34:08 +0000232 assert(TableIdx && "No jumping from #endifs.");
233
234 // Update our side-table iterator.
235 const char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
236 assert(NextPPCondPtr >= CurPPCondPtr);
237 CurPPCondPtr = NextPPCondPtr;
238
239 // Read where we should jump to.
Ted Kremenek41a26602008-12-12 22:05:38 +0000240 HashEntryI = TokBuf + Read32(NextPPCondPtr);
Ted Kremenek268ee702008-12-12 18:34:08 +0000241 uint32_t NextIdx = Read32(NextPPCondPtr);
242
243 // By construction NextIdx will be zero if this is a #endif. This is useful
244 // to know to obviate lexing another token.
245 bool isEndif = NextIdx == 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000246
247 // This case can occur when we see something like this:
248 //
249 // #if ...
250 // /* a comment or nothing */
251 // #elif
252 //
253 // If we are skipping the first #if block it will be the case that CurPtr
254 // already points 'elif'. Just return.
255
Ted Kremenek41a26602008-12-12 22:05:38 +0000256 if (CurPtr > HashEntryI) {
257 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
Ted Kremenek268ee702008-12-12 18:34:08 +0000258 // Did we reach a #endif? If so, go ahead and consume that token as well.
259 if (isEndif)
Ted Kremeneke5680f32008-12-23 01:30:52 +0000260 CurPtr += DISK_TOKEN_SIZE*2;
Ted Kremenek268ee702008-12-12 18:34:08 +0000261 else
Ted Kremenek41a26602008-12-12 22:05:38 +0000262 LastHashTokPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000263
264 return isEndif;
265 }
266
267 // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
Ted Kremenek41a26602008-12-12 22:05:38 +0000268 CurPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000269
270 // Update the location of the last observed '#'. This is useful if we
271 // are skipping multiple blocks.
272 LastHashTokPtr = CurPtr;
Ted Kremenek268ee702008-12-12 18:34:08 +0000273
Ted Kremeneke5680f32008-12-23 01:30:52 +0000274 // Skip the '#' token.
275 assert(((tok::TokenKind) (unsigned char) *CurPtr) == tok::hash);
276 CurPtr += DISK_TOKEN_SIZE;
277
Ted Kremenek268ee702008-12-12 18:34:08 +0000278 // Did we reach a #endif? If so, go ahead and consume that token as well.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000279 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
Ted Kremenek268ee702008-12-12 18:34:08 +0000280
281 return isEndif;
282}
283
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000284SourceLocation PTHLexer::getSourceLocation() {
285 // getLocation is not on the hot path. It is used to get the location of
286 // the next token when transitioning back to this lexer when done
287 // handling a #included file. Just read the necessary data from the token
288 // data buffer to construct the SourceLocation object.
289 // NOTE: This is a virtual function; hence it is defined out-of-line.
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000290 const char* p = CurPtr + (1 + 1 + 3);
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000291 uint32_t offset =
292 ((uint32_t) ((uint8_t) p[0]))
293 | (((uint32_t) ((uint8_t) p[1])) << 8)
294 | (((uint32_t) ((uint8_t) p[2])) << 16)
295 | (((uint32_t) ((uint8_t) p[3])) << 24);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000296 return FileStartLoc.getFileLocWithOffset(offset);
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000297}
298
Ted Kremenek5f074262009-01-09 22:05:30 +0000299//===----------------------------------------------------------------------===//
300// getSpelling() - Use cached data in PTH files for getSpelling().
301//===----------------------------------------------------------------------===//
302
Chris Lattner2b2453a2009-01-17 06:22:33 +0000303unsigned PTHManager::getSpelling(FileID FID, unsigned FPos,
304 const char *&Buffer) {
305 llvm::DenseMap<FileID, PTHSpellingSearch*>::iterator I =SpellingMap.find(FID);
Ted Kremenek5f074262009-01-09 22:05:30 +0000306
307 if (I == SpellingMap.end())
308 return 0;
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000309
Chris Lattner2b2453a2009-01-17 06:22:33 +0000310 return I->second->getSpellingBinarySearch(FPos, Buffer);
311}
312
313unsigned PTHManager::getSpelling(SourceLocation Loc, const char *&Buffer) {
Chris Lattner6b7b8402009-01-17 06:29:33 +0000314 SourceManager &SM = PP->getSourceManager();
315 Loc = SM.getSpellingLoc(Loc);
316 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedFileLoc(Loc);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000317 return getSpelling(LocInfo.first, LocInfo.second, Buffer);
Ted Kremenek5f074262009-01-09 22:05:30 +0000318}
319
320unsigned PTHManager::getSpellingAtPTHOffset(unsigned PTHOffset,
321 const char *& Buffer) {
322
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000323 const char* p = Buf->getBufferStart() + PTHOffset;
324 assert(p < Buf->getBufferEnd());
325
326 // The string is prefixed by 16 bits for its length, followed by the string
327 // itself.
328 unsigned len = ((unsigned) ((uint8_t) p[0]))
329 | (((unsigned) ((uint8_t) p[1])) << 8);
330
331 Buffer = p + 2;
332 return len;
333}
334
Ted Kremenek5f074262009-01-09 22:05:30 +0000335unsigned PTHSpellingSearch::getSpellingLinearSearch(unsigned fpos,
336 const char *&Buffer) {
337 const char* p = LinearItr;
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000338 unsigned len = 0;
Ted Kremenek5f074262009-01-09 22:05:30 +0000339
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000340 if (p == TableEnd)
Ted Kremenek5f074262009-01-09 22:05:30 +0000341 return getSpellingBinarySearch(fpos, Buffer);
342
343 do {
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000344 uint32_t TokOffset =
345 ((uint32_t) ((uint8_t) p[0]))
346 | (((uint32_t) ((uint8_t) p[1])) << 8)
347 | (((uint32_t) ((uint8_t) p[2])) << 16)
348 | (((uint32_t) ((uint8_t) p[3])) << 24);
349
350 if (TokOffset > fpos)
Ted Kremenek5f074262009-01-09 22:05:30 +0000351 return getSpellingBinarySearch(fpos, Buffer);
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000352
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000353 // 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 Kremenekf02f6f02009-01-13 22:05:50 +0000361 p += SpellingEntrySize;
Ted Kremenek5f074262009-01-09 22:05:30 +0000362 len = PTHMgr.getSpellingAtPTHOffset(SpellingPTHOffset, Buffer);
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000363 break;
364 }
365
366 // No match. Keep on looking.
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000367 p += SpellingEntrySize;
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000368 }
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000369 while (p != TableEnd);
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000370
Ted Kremenek5f074262009-01-09 22:05:30 +0000371 LinearItr = p;
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000372 return len;
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000373}
374
Ted Kremenek5f074262009-01-09 22:05:30 +0000375unsigned PTHSpellingSearch::getSpellingBinarySearch(unsigned fpos,
376 const char *& Buffer) {
377
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000378 assert((TableEnd - TableBeg) % SpellingEntrySize == 0);
379
380 if (TableEnd == TableBeg)
381 return 0;
382
383 assert(TableEnd > TableBeg);
Ted Kremenek5f074262009-01-09 22:05:30 +0000384
385 unsigned min = 0;
386 const char* tb = TableBeg;
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000387 unsigned max = NumSpellings;
Ted Kremenek5f074262009-01-09 22:05:30 +0000388
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000389 do {
Ted Kremenek5f074262009-01-09 22:05:30 +0000390 unsigned i = (max - min) / 2 + min;
391 const char* p = tb + (i * SpellingEntrySize);
392
393 uint32_t TokOffset =
394 ((uint32_t) ((uint8_t) p[0]))
395 | (((uint32_t) ((uint8_t) p[1])) << 8)
396 | (((uint32_t) ((uint8_t) p[2])) << 16)
397 | (((uint32_t) ((uint8_t) p[3])) << 24);
398
399 if (TokOffset > fpos) {
400 max = i;
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000401 assert(!(max == min) || (min == i));
Ted Kremenek5f074262009-01-09 22:05:30 +0000402 continue;
403 }
404
405 if (TokOffset < fpos) {
Ted Kremenek7bd88aa2009-01-13 22:16:45 +0000406 if (i == min)
407 break;
408
Ted Kremenek5f074262009-01-09 22:05:30 +0000409 min = i;
410 continue;
411 }
412
413 uint32_t SpellingPTHOffset =
414 ((uint32_t) ((uint8_t) p[4]))
415 | (((uint32_t) ((uint8_t) p[5])) << 8)
416 | (((uint32_t) ((uint8_t) p[6])) << 16)
417 | (((uint32_t) ((uint8_t) p[7])) << 24);
418
419 return PTHMgr.getSpellingAtPTHOffset(SpellingPTHOffset, Buffer);
420 }
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000421 while (min != max);
Ted Kremenek5f074262009-01-09 22:05:30 +0000422
423 return 0;
424}
425
Chris Lattner2b2453a2009-01-17 06:22:33 +0000426unsigned PTHLexer::getSpelling(SourceLocation Loc, const char *&Buffer) {
427 SourceManager &SM = PP->getSourceManager();
428 Loc = SM.getSpellingLoc(Loc);
429 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedFileLoc(Loc);
430
431 FileID FID = LocInfo.first;
432 unsigned FPos = LocInfo.second;
Ted Kremenek5f074262009-01-09 22:05:30 +0000433
Chris Lattner2b2453a2009-01-17 06:22:33 +0000434 if (FID == getFileID())
435 return MySpellingSrch.getSpellingLinearSearch(FPos, Buffer);
436 return PTHMgr.getSpelling(FID, FPos, Buffer);
Ted Kremenek5f074262009-01-09 22:05:30 +0000437}
438
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000439//===----------------------------------------------------------------------===//
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000440// Internal Data Structures for PTH file lookup and resolving identifiers.
441//===----------------------------------------------------------------------===//
442
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000443
444/// PTHFileLookup - This internal data structure is used by the PTHManager
445/// to map from FileEntry objects managed by FileManager to offsets within
446/// the PTH file.
447namespace {
448class VISIBILITY_HIDDEN PTHFileLookup {
449public:
450 class Val {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000451 uint32_t TokenOff;
452 uint32_t PPCondOff;
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000453 uint32_t SpellingOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000454
455 public:
Ted Kremenekfb645b62008-12-11 23:36:38 +0000456 Val() : TokenOff(~0) {}
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000457 Val(uint32_t toff, uint32_t poff, uint32_t soff)
458 : TokenOff(toff), PPCondOff(poff), SpellingOff(soff) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000459
Ted Kremenekfb645b62008-12-11 23:36:38 +0000460 uint32_t getTokenOffset() const {
461 assert(TokenOff != ~((uint32_t)0) && "PTHFileLookup entry initialized.");
462 return TokenOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000463 }
464
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000465 uint32_t getPPCondOffset() const {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000466 assert(TokenOff != ~((uint32_t)0) && "PTHFileLookup entry initialized.");
467 return PPCondOff;
468 }
469
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000470 uint32_t getSpellingOffset() const {
471 assert(TokenOff != ~((uint32_t)0) && "PTHFileLookup entry initialized.");
472 return SpellingOff;
473 }
474
Ted Kremenekfb645b62008-12-11 23:36:38 +0000475 bool isValid() const { return TokenOff != ~((uint32_t)0); }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000476 };
477
478private:
479 llvm::StringMap<Val> FileMap;
480
481public:
482 PTHFileLookup() {};
483
484 Val Lookup(const FileEntry* FE) {
485 const char* s = FE->getName();
486 unsigned size = strlen(s);
487 return FileMap.GetOrCreateValue(s, s+size).getValue();
488 }
489
490 void ReadTable(const char* D) {
491 uint32_t N = Read32(D); // Read the length of the table.
492
493 for ( ; N > 0; --N) { // The rest of the data is the table itself.
494 uint32_t len = Read32(D);
495 const char* s = D;
496 D += len;
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000497
Ted Kremenekfb645b62008-12-11 23:36:38 +0000498 uint32_t TokenOff = Read32(D);
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000499 uint32_t PPCondOff = Read32(D);
500 uint32_t SpellingOff = Read32(D);
501
502 FileMap.GetOrCreateValue(s, s+len).getValue() =
503 Val(TokenOff, PPCondOff, SpellingOff);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000504 }
505 }
506};
507} // end anonymous namespace
508
509//===----------------------------------------------------------------------===//
510// PTHManager methods.
511//===----------------------------------------------------------------------===//
512
513PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
Ted Kremenekcf58e622008-12-10 19:40:23 +0000514 const char* idDataTable, IdentifierInfo** perIDCache,
Ted Kremenek72b1b152009-01-15 18:47:46 +0000515 const char* sortedIdTable, unsigned numIds)
Ted Kremenek6183e482008-12-03 01:16:39 +0000516: Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
Ted Kremenek72b1b152009-01-15 18:47:46 +0000517 IdDataTable(idDataTable), SortedIdTable(sortedIdTable),
518 NumIds(numIds), PP(0) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000519
520PTHManager::~PTHManager() {
521 delete Buf;
522 delete (PTHFileLookup*) FileLookup;
Ted Kremenek0e50b6e2008-12-04 22:47:11 +0000523 free(PerIDCache);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000524}
525
Ted Kremenek72b1b152009-01-15 18:47:46 +0000526PTHManager* PTHManager::Create(const std::string& file) {
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000527
528 // Memory map the PTH file.
529 llvm::OwningPtr<llvm::MemoryBuffer>
530 File(llvm::MemoryBuffer::getFile(file.c_str()));
531
532 if (!File)
533 return 0;
534
535 // Get the buffer ranges and check if there are at least three 32-bit
536 // words at the end of the file.
537 const char* BufBeg = File->getBufferStart();
538 const char* BufEnd = File->getBufferEnd();
539
540 if(!(BufEnd > BufBeg + sizeof(uint32_t)*3)) {
541 assert(false && "Invalid PTH file.");
542 return 0; // FIXME: Proper error diagnostic?
543 }
544
545 // Compute the address of the index table at the end of the PTH file.
546 // This table contains the offset of the file lookup table, the
547 // persistent ID -> identifer data table.
Ted Kremenek293b4af2009-01-15 01:26:25 +0000548 // FIXME: We should just embed this offset in the PTH file.
549 const char* EndTable = BufEnd - sizeof(uint32_t)*4;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000550
551 // Construct the file lookup table. This will be used for mapping from
552 // FileEntry*'s to cached tokens.
Ted Kremenek293b4af2009-01-15 01:26:25 +0000553 const char* FileTableOffset = EndTable + sizeof(uint32_t)*3;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000554 const char* FileTable = BufBeg + Read32(FileTableOffset);
555
556 if (!(FileTable > BufBeg && FileTable < BufEnd)) {
557 assert(false && "Invalid PTH file.");
558 return 0; // FIXME: Proper error diagnostic?
559 }
560
561 llvm::OwningPtr<PTHFileLookup> FL(new PTHFileLookup());
562 FL->ReadTable(FileTable);
563
564 // Get the location of the table mapping from persistent ids to the
565 // data needed to reconstruct identifiers.
566 const char* IDTableOffset = EndTable + sizeof(uint32_t)*1;
567 const char* IData = BufBeg + Read32(IDTableOffset);
568 if (!(IData > BufBeg && IData < BufEnd)) {
569 assert(false && "Invalid PTH file.");
570 return 0; // FIXME: Proper error diagnostic?
571 }
572
Ted Kremenek72b1b152009-01-15 18:47:46 +0000573 // Get the location of the lexigraphically-sorted table of persistent IDs.
574 const char* SortedIdTableOffset = EndTable + sizeof(uint32_t)*2;
575 const char* SortedIdTable = BufBeg + Read32(SortedIdTableOffset);
576 if (!(SortedIdTable > BufBeg && SortedIdTable < BufEnd)) {
577 assert(false && "Invalid PTH file.");
578 return 0; // FIXME: Proper error diagnostic?
579 }
580
Ted Kremenek6183e482008-12-03 01:16:39 +0000581 // Get the number of IdentifierInfos and pre-allocate the identifier cache.
582 uint32_t NumIds = Read32(IData);
583
584 // Pre-allocate the peristent ID -> IdentifierInfo* cache. We use calloc()
585 // so that we in the best case only zero out memory once when the OS returns
586 // us new pages.
587 IdentifierInfo** PerIDCache =
588 (IdentifierInfo**) calloc(NumIds, sizeof(*PerIDCache));
589
590 if (!PerIDCache) {
591 assert(false && "Could not allocate Persistent ID cache.");
592 return 0;
593 }
594
Ted Kremenek72b1b152009-01-15 18:47:46 +0000595 // Create the new PTHManager.
596 return new PTHManager(File.take(), FL.take(), IData, PerIDCache,
597 SortedIdTable, NumIds);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000598}
599
Ted Kremenek866bdf72008-12-23 02:30:15 +0000600IdentifierInfo* PTHManager::GetIdentifierInfo(unsigned persistentID) {
601
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000602 // Check if the IdentifierInfo has already been resolved.
Ted Kremenek72b1b152009-01-15 18:47:46 +0000603 IdentifierInfo* II = PerIDCache[persistentID];
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000604 if (II) return II;
605
606 // Look in the PTH file for the string data for the IdentifierInfo object.
607 const char* TableEntry = IdDataTable + sizeof(uint32_t) * persistentID;
608 const char* IDData = Buf->getBufferStart() + Read32(TableEntry);
609 assert(IDData < Buf->getBufferEnd());
610
Ted Kremenek72b1b152009-01-15 18:47:46 +0000611 // Allocate the object.
612 std::pair<IdentifierInfo,const char*> *Mem =
613 Alloc.Allocate<std::pair<IdentifierInfo,const char*> >();
614
615 Mem->second = IDData;
616 II = new ((void*) Mem) IdentifierInfo(true);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000617
Ted Kremenek72b1b152009-01-15 18:47:46 +0000618 // Store the new IdentifierInfo in the cache.
619 PerIDCache[persistentID] = II;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000620 return II;
621}
622
Ted Kremenek72b1b152009-01-15 18:47:46 +0000623IdentifierInfo* PTHManager::get(const char *NameStart, const char *NameEnd) {
624 unsigned min = 0;
625 unsigned max = NumIds;
626 unsigned len = NameEnd - NameStart;
627
628 do {
629 unsigned i = (max - min) / 2 + min;
630 const char* p = SortedIdTable + (i * 4);
631
632 // Read the persistentID.
633 unsigned perID =
634 ((unsigned) ((uint8_t) p[0]))
635 | (((unsigned) ((uint8_t) p[1])) << 8)
636 | (((unsigned) ((uint8_t) p[2])) << 16)
637 | (((unsigned) ((uint8_t) p[3])) << 24);
638
639 // Get the IdentifierInfo.
640 IdentifierInfo* II = GetIdentifierInfo(perID);
641
642 // First compare the lengths.
643 unsigned IILen = II->getLength();
644 if (len < IILen) goto IsLess;
645 if (len > IILen) goto IsGreater;
646
647 // Now compare the strings!
648 {
649 signed comp = strncmp(NameStart, II->getName(), len);
650 if (comp < 0) goto IsLess;
651 if (comp > 0) goto IsGreater;
652 }
653 // We found a match!
654 return II;
655
656 IsGreater:
657 if (i == min) break;
658 min = i;
659 continue;
660
661 IsLess:
662 max = i;
663 assert(!(max == min) || (min == i));
664 }
Ted Kremeneke1deaac2009-01-15 19:28:38 +0000665 while (min != max);
Ted Kremenek72b1b152009-01-15 18:47:46 +0000666
667 return 0;
668}
669
670
Chris Lattner2b2453a2009-01-17 06:22:33 +0000671PTHLexer* PTHManager::CreateLexer(FileID FID, const FileEntry* FE) {
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000672 if (!FE)
673 return 0;
674
675 // Lookup the FileEntry object in our file lookup data structure. It will
676 // return a variant that indicates whether or not there is an offset within
677 // the PTH file that contains cached tokens.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000678 PTHFileLookup::Val FileData = ((PTHFileLookup*)FileLookup)->Lookup(FE);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000679
Ted Kremenekfb645b62008-12-11 23:36:38 +0000680 if (!FileData.isValid()) // No tokens available.
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000681 return 0;
682
683 // Compute the offset of the token data within the buffer.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000684 const char* data = Buf->getBufferStart() + FileData.getTokenOffset();
Ted Kremenek268ee702008-12-12 18:34:08 +0000685
686 // Get the location of pp-conditional table.
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000687 const char* ppcond = Buf->getBufferStart() + FileData.getPPCondOffset();
688 uint32_t len = Read32(ppcond);
Ted Kremenek268ee702008-12-12 18:34:08 +0000689 if (len == 0) ppcond = 0;
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000690
691 // Get the location of the spelling table.
692 const char* spellingTable = Buf->getBufferStart() +
693 FileData.getSpellingOffset();
694
695 len = Read32(spellingTable);
696 if (len == 0) spellingTable = 0;
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000697
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000698 assert(data < Buf->getBufferEnd());
Ted Kremenek5f074262009-01-09 22:05:30 +0000699
700 // Create the SpellingSearch object for this FileID.
701 PTHSpellingSearch* ss = new PTHSpellingSearch(*this, len, spellingTable);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000702 SpellingMap[FID] = ss;
Ted Kremenek5f074262009-01-09 22:05:30 +0000703
Ted Kremenek72b1b152009-01-15 18:47:46 +0000704 assert(PP && "No preprocessor set yet!");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000705 return new PTHLexer(*PP, FID, data, ppcond, *ss, *this);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000706}