blob: 99bb3f795d8a82d84a3ac78c77306d9525351b37 [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"
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 Kremenekca820862008-11-12 21:37:15 +000026using namespace clang;
27
Ted Kremenekb8344ef2009-01-19 23:13:15 +000028#define DISK_TOKEN_SIZE (1+1+2+4+4)
Ted Kremenekc07091c2008-12-12 18:34:08 +000029
Ted Kremenek325cd302008-12-03 00:38:03 +000030//===----------------------------------------------------------------------===//
31// Utility methods for reading from the mmap'ed PTH file.
32//===----------------------------------------------------------------------===//
33
Chris Lattnerefb35342009-01-18 01:57:14 +000034static inline uint8_t Read8(const unsigned char *&Data) {
35 uint8_t V = Data[0];
36 Data += 1;
Ted Kremenek325cd302008-12-03 00:38:03 +000037 return V;
38}
39
Chris Lattnerefb35342009-01-18 01:57:14 +000040static inline uint16_t Read16(const unsigned char *&Data) {
Chris Lattner5bffcaf2009-01-18 02:19:16 +000041// Targets that directly support unaligned little-endian 16-bit loads can just
42// use them.
43#if defined(__i386__) || defined(__x86_64__)
44 uint16_t V = *((uint16_t*)Data);
45#else
Chris Lattnerefb35342009-01-18 01:57:14 +000046 uint16_t V = ((uint16_t)Data[0] << 0) |
47 ((uint16_t)Data[1] << 8);
Chris Lattner5bffcaf2009-01-18 02:19:16 +000048#endif
Chris Lattnerefb35342009-01-18 01:57:14 +000049 Data += 2;
50 return V;
51}
52
Chris Lattnerddf3b792009-01-21 07:21:56 +000053static inline uint32_t Read24(const unsigned char *&Data) {
54// Targets that directly support unaligned little-endian 16-bit loads can just
55// use them.
56#if defined(__i386__) || defined(__x86_64__)
57 uint32_t V = ((uint16_t*)Data)[0] |
58 ((uint32_t)Data[2] << 16);
59#else
60 uint32_t V = ((uint32_t)Data[0] << 0) |
61 ((uint32_t)Data[1] << 8) |
62 ((uint32_t)Data[2] << 16);
63#endif
64
65 Data += 3;
66 return V;
67}
68
Chris Lattnerefb35342009-01-18 01:57:14 +000069static inline uint32_t Read32(const unsigned char *&Data) {
Chris Lattner5bffcaf2009-01-18 02:19:16 +000070// Targets that directly support unaligned little-endian 32-bit loads can just
71// use them.
72#if defined(__i386__) || defined(__x86_64__)
73 uint32_t V = *((uint32_t*)Data);
74#else
Chris Lattnerefb35342009-01-18 01:57:14 +000075 uint32_t V = ((uint32_t)Data[0] << 0) |
76 ((uint32_t)Data[1] << 8) |
77 ((uint32_t)Data[2] << 16) |
78 ((uint32_t)Data[3] << 24);
Chris Lattner5bffcaf2009-01-18 02:19:16 +000079#endif
Chris Lattnerefb35342009-01-18 01:57:14 +000080 Data += 4;
81 return V;
82}
83
84
Ted Kremenek9ab79bf2008-12-23 01:30:52 +000085//===----------------------------------------------------------------------===//
86// PTHLexer methods.
87//===----------------------------------------------------------------------===//
88
Chris Lattnerefb35342009-01-18 01:57:14 +000089PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D,
90 const unsigned char *ppcond,
Chris Lattnerf4f776a2009-01-17 06:22:33 +000091 PTHSpellingSearch &mySpellingSrch, PTHManager &PM)
92 : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(0),
Ted Kremenekd310fde2009-01-09 22:05:30 +000093 PPCond(ppcond), CurPPCondPtr(ppcond), MySpellingSrch(mySpellingSrch),
Chris Lattnerf4f776a2009-01-17 06:22:33 +000094 PTHMgr(PM) {
95
96 FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID);
Ted Kremenekd310fde2009-01-09 22:05:30 +000097}
Ted Kremenek9ab79bf2008-12-23 01:30:52 +000098
99void PTHLexer::Lex(Token& Tok) {
100LexNextToken:
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000101
Ted Kremenek08d3ff32008-12-23 02:30:15 +0000102 //===--------------------------------------==//
103 // Read the raw token data.
104 //===--------------------------------------==//
105
106 // Shadow CurPtr into an automatic variable.
Chris Lattnerddf3b792009-01-21 07:21:56 +0000107 const unsigned char *CurPtrShadow = CurPtr;
Ted Kremenek08d3ff32008-12-23 02:30:15 +0000108
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000109 // Read in the data for the token.
Chris Lattnerddf3b792009-01-21 07:21:56 +0000110 unsigned Word0 = Read32(CurPtrShadow);
111 uint32_t IdentifierID = Read32(CurPtrShadow);
112 uint32_t FileOffset = Read32(CurPtrShadow);
Ted Kremenekb8344ef2009-01-19 23:13:15 +0000113
114 tok::TokenKind TKind = (tok::TokenKind) (Word0 & 0xFF);
115 Token::TokenFlags TFlags = (Token::TokenFlags) ((Word0 >> 8) & 0xFF);
Chris Lattnerddf3b792009-01-21 07:21:56 +0000116 uint32_t Len = Word0 >> 16;
Ted Kremenekb8344ef2009-01-19 23:13:15 +0000117
Chris Lattnerddf3b792009-01-21 07:21:56 +0000118 CurPtr = CurPtrShadow;
Ted Kremenek08d3ff32008-12-23 02:30:15 +0000119
120 //===--------------------------------------==//
121 // Construct the token itself.
122 //===--------------------------------------==//
123
124 Tok.startToken();
Chris Lattnerce8670e2009-01-18 02:34:01 +0000125 Tok.setKind(TKind);
126 Tok.setFlag(TFlags);
Ted Kremenekd94668d2008-12-23 19:24:24 +0000127 assert(!LexingRawMode);
Chris Lattnerce8670e2009-01-18 02:34:01 +0000128 if (IdentifierID)
129 Tok.setIdentifierInfo(PTHMgr.GetIdentifierInfo(IdentifierID-1));
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000130 Tok.setLocation(FileStartLoc.getFileLocWithOffset(FileOffset));
Ted Kremenek08d3ff32008-12-23 02:30:15 +0000131 Tok.setLength(Len);
132
133 //===--------------------------------------==//
134 // Process the token.
135 //===--------------------------------------==//
Ted Kremenekd310fde2009-01-09 22:05:30 +0000136#if 0
137 SourceManager& SM = PP->getSourceManager();
138 llvm::cerr << SM.getFileEntryForID(FileID)->getName()
139 << ':' << SM.getLogicalLineNumber(Tok.getLocation())
140 << ':' << SM.getLogicalColumnNumber(Tok.getLocation())
141 << '\n';
142#endif
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000143
Chris Lattnerce8670e2009-01-18 02:34:01 +0000144 if (TKind == tok::identifier) {
Ted Kremenekd94668d2008-12-23 19:24:24 +0000145 MIOpt.ReadToken();
Chris Lattner5b747d02009-01-21 07:43:11 +0000146 if (Tok.getIdentifierInfo()->isHandleIdentifierCase())
147 PP->HandleIdentifier(Tok);
148 return;
Ted Kremenekd94668d2008-12-23 19:24:24 +0000149 }
150
Chris Lattnerce8670e2009-01-18 02:34:01 +0000151 if (TKind == tok::eof) {
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000152 // Save the end-of-file token.
153 EofToken = Tok;
154
155 Preprocessor *PPCache = PP;
Ted Kremenekd94668d2008-12-23 19:24:24 +0000156
157 assert(!ParsingPreprocessorDirective);
158 assert(!LexingRawMode);
159
160 // FIXME: Issue diagnostics similar to Lexer.
161 if (PP->HandleEndOfFile(Tok, false))
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000162 return;
Ted Kremenekd94668d2008-12-23 19:24:24 +0000163
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000164 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
165 return PPCache->Lex(Tok);
166 }
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000167
Chris Lattnerce8670e2009-01-18 02:34:01 +0000168 if (TKind == tok::hash && Tok.isAtStartOfLine()) {
Ted Kremenekd94668d2008-12-23 19:24:24 +0000169 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
170 assert(!LexingRawMode);
171 PP->HandleDirective(Tok);
172
173 if (PP->isCurrentLexer(this))
174 goto LexNextToken;
175
176 return PP->Lex(Tok);
177 }
178
Chris Lattnerce8670e2009-01-18 02:34:01 +0000179 if (TKind == tok::eom) {
Ted Kremenekd94668d2008-12-23 19:24:24 +0000180 assert(ParsingPreprocessorDirective);
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000181 ParsingPreprocessorDirective = false;
182 return;
183 }
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000184
Ted Kremenekd94668d2008-12-23 19:24:24 +0000185 MIOpt.ReadToken();
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000186}
187
188// FIXME: We can just grab the last token instead of storing a copy
189// into EofToken.
Ted Kremenekd94668d2008-12-23 19:24:24 +0000190void PTHLexer::getEOF(Token& Tok) {
Ted Kremeneke4caf142009-01-09 00:36:11 +0000191 assert(EofToken.is(tok::eof));
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000192 Tok = EofToken;
193}
194
195void PTHLexer::DiscardToEndOfLine() {
196 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
197 "Must be in a preprocessing directive!");
198
199 // We assume that if the preprocessor wishes to discard to the end of
200 // the line that it also means to end the current preprocessor directive.
201 ParsingPreprocessorDirective = false;
202
203 // Skip tokens by only peeking at their token kind and the flags.
204 // We don't need to actually reconstruct full tokens from the token buffer.
205 // This saves some copies and it also reduces IdentifierInfo* lookup.
Chris Lattnerefb35342009-01-18 01:57:14 +0000206 const unsigned char* p = CurPtr;
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000207 while (1) {
208 // Read the token kind. Are we at the end of the file?
209 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
210 if (x == tok::eof) break;
211
212 // Read the token flags. Are we at the start of the next line?
213 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
214 if (y & Token::StartOfLine) break;
215
216 // Skip to the next token.
217 p += DISK_TOKEN_SIZE;
218 }
219
220 CurPtr = p;
221}
222
Ted Kremenekc07091c2008-12-12 18:34:08 +0000223/// SkipBlock - Used by Preprocessor to skip the current conditional block.
224bool PTHLexer::SkipBlock() {
225 assert(CurPPCondPtr && "No cached PP conditional information.");
226 assert(LastHashTokPtr && "No known '#' token.");
227
Chris Lattnerefb35342009-01-18 01:57:14 +0000228 const unsigned char* HashEntryI = 0;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000229 uint32_t Offset;
230 uint32_t TableIdx;
231
232 do {
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000233 // Read the token offset from the side-table.
Ted Kremenekc07091c2008-12-12 18:34:08 +0000234 Offset = Read32(CurPPCondPtr);
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000235
236 // Read the target table index from the side-table.
Ted Kremenekc07091c2008-12-12 18:34:08 +0000237 TableIdx = Read32(CurPPCondPtr);
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000238
239 // Compute the actual memory address of the '#' token data for this entry.
240 HashEntryI = TokBuf + Offset;
241
242 // Optmization: "Sibling jumping". #if...#else...#endif blocks can
243 // contain nested blocks. In the side-table we can jump over these
244 // nested blocks instead of doing a linear search if the next "sibling"
245 // entry is not at a location greater than LastHashTokPtr.
246 if (HashEntryI < LastHashTokPtr && TableIdx) {
247 // In the side-table we are still at an entry for a '#' token that
248 // is earlier than the last one we saw. Check if the location we would
249 // stride gets us closer.
Chris Lattnerefb35342009-01-18 01:57:14 +0000250 const unsigned char* NextPPCondPtr =
251 PPCond + TableIdx*(sizeof(uint32_t)*2);
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000252 assert(NextPPCondPtr >= CurPPCondPtr);
253 // Read where we should jump to.
254 uint32_t TmpOffset = Read32(NextPPCondPtr);
Chris Lattnerefb35342009-01-18 01:57:14 +0000255 const unsigned char* HashEntryJ = TokBuf + TmpOffset;
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000256
257 if (HashEntryJ <= LastHashTokPtr) {
258 // Jump directly to the next entry in the side table.
259 HashEntryI = HashEntryJ;
260 Offset = TmpOffset;
261 TableIdx = Read32(NextPPCondPtr);
262 CurPPCondPtr = NextPPCondPtr;
263 }
264 }
Ted Kremenekc07091c2008-12-12 18:34:08 +0000265 }
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000266 while (HashEntryI < LastHashTokPtr);
267 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
Ted Kremenekc07091c2008-12-12 18:34:08 +0000268 assert(TableIdx && "No jumping from #endifs.");
269
270 // Update our side-table iterator.
Chris Lattnerefb35342009-01-18 01:57:14 +0000271 const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
Ted Kremenekc07091c2008-12-12 18:34:08 +0000272 assert(NextPPCondPtr >= CurPPCondPtr);
273 CurPPCondPtr = NextPPCondPtr;
274
275 // Read where we should jump to.
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000276 HashEntryI = TokBuf + Read32(NextPPCondPtr);
Ted Kremenekc07091c2008-12-12 18:34:08 +0000277 uint32_t NextIdx = Read32(NextPPCondPtr);
278
279 // By construction NextIdx will be zero if this is a #endif. This is useful
280 // to know to obviate lexing another token.
281 bool isEndif = NextIdx == 0;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000282
283 // This case can occur when we see something like this:
284 //
285 // #if ...
286 // /* a comment or nothing */
287 // #elif
288 //
289 // If we are skipping the first #if block it will be the case that CurPtr
290 // already points 'elif'. Just return.
291
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000292 if (CurPtr > HashEntryI) {
293 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
Ted Kremenekc07091c2008-12-12 18:34:08 +0000294 // Did we reach a #endif? If so, go ahead and consume that token as well.
295 if (isEndif)
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000296 CurPtr += DISK_TOKEN_SIZE*2;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000297 else
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000298 LastHashTokPtr = HashEntryI;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000299
300 return isEndif;
301 }
302
303 // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
Ted Kremenekbe3e84f2008-12-12 22:05:38 +0000304 CurPtr = HashEntryI;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000305
306 // Update the location of the last observed '#'. This is useful if we
307 // are skipping multiple blocks.
308 LastHashTokPtr = CurPtr;
Ted Kremenekc07091c2008-12-12 18:34:08 +0000309
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000310 // Skip the '#' token.
Chris Lattnerefb35342009-01-18 01:57:14 +0000311 assert(((tok::TokenKind)*CurPtr) == tok::hash);
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000312 CurPtr += DISK_TOKEN_SIZE;
313
Ted Kremenekc07091c2008-12-12 18:34:08 +0000314 // Did we reach a #endif? If so, go ahead and consume that token as well.
Ted Kremenek9ab79bf2008-12-23 01:30:52 +0000315 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
Ted Kremenekc07091c2008-12-12 18:34:08 +0000316
317 return isEndif;
318}
319
Ted Kremenekbeb57672008-12-17 23:36:32 +0000320SourceLocation PTHLexer::getSourceLocation() {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000321 // getSourceLocation is not on the hot path. It is used to get the location
322 // of the next token when transitioning back to this lexer when done
Ted Kremenekbeb57672008-12-17 23:36:32 +0000323 // handling a #included file. Just read the necessary data from the token
324 // data buffer to construct the SourceLocation object.
325 // NOTE: This is a virtual function; hence it is defined out-of-line.
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000326 const unsigned char *OffsetPtr = CurPtr + (1 + 1 + 3);
327 uint32_t Offset = Read32(OffsetPtr);
328 return FileStartLoc.getFileLocWithOffset(Offset);
Ted Kremenekbeb57672008-12-17 23:36:32 +0000329}
330
Ted Kremenekd310fde2009-01-09 22:05:30 +0000331//===----------------------------------------------------------------------===//
332// getSpelling() - Use cached data in PTH files for getSpelling().
333//===----------------------------------------------------------------------===//
334
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000335unsigned PTHManager::getSpelling(FileID FID, unsigned FPos,
336 const char *&Buffer) {
337 llvm::DenseMap<FileID, PTHSpellingSearch*>::iterator I =SpellingMap.find(FID);
Ted Kremenekd310fde2009-01-09 22:05:30 +0000338
339 if (I == SpellingMap.end())
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000340 return 0;
Ted Kremenek21069422009-01-13 22:05:50 +0000341
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000342 return I->second->getSpellingBinarySearch(FPos, Buffer);
343}
344
345unsigned PTHManager::getSpelling(SourceLocation Loc, const char *&Buffer) {
Chris Lattnere7fc9622009-01-17 06:29:33 +0000346 SourceManager &SM = PP->getSourceManager();
347 Loc = SM.getSpellingLoc(Loc);
348 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedFileLoc(Loc);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000349 return getSpelling(LocInfo.first, LocInfo.second, Buffer);
Ted Kremenekd310fde2009-01-09 22:05:30 +0000350}
351
352unsigned PTHManager::getSpellingAtPTHOffset(unsigned PTHOffset,
Chris Lattnerefb35342009-01-18 01:57:14 +0000353 const char *&Buffer) {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000354 assert(PTHOffset < Buf->getBufferSize());
355 const unsigned char* Ptr =
356 (const unsigned char*)Buf->getBufferStart() + PTHOffset;
Ted Kremeneka4d5bf52009-01-08 04:30:32 +0000357
358 // The string is prefixed by 16 bits for its length, followed by the string
359 // itself.
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000360 unsigned Len = Read16(Ptr);
361 Buffer = (const char *)Ptr;
362 return Len;
Ted Kremeneka4d5bf52009-01-08 04:30:32 +0000363}
364
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000365unsigned PTHSpellingSearch::getSpellingLinearSearch(unsigned FPos,
Ted Kremenekd310fde2009-01-09 22:05:30 +0000366 const char *&Buffer) {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000367 const unsigned char *Ptr = LinearItr;
368 unsigned Len = 0;
Ted Kremenekd310fde2009-01-09 22:05:30 +0000369
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000370 if (Ptr == TableEnd)
371 return getSpellingBinarySearch(FPos, Buffer);
Ted Kremenekd310fde2009-01-09 22:05:30 +0000372
373 do {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000374 uint32_t TokOffset = Read32(Ptr);
Ted Kremeneka4d5bf52009-01-08 04:30:32 +0000375
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000376 if (TokOffset > FPos)
377 return getSpellingBinarySearch(FPos, Buffer);
Ted Kremeneka4d5bf52009-01-08 04:30:32 +0000378
Ted Kremeneka4d5bf52009-01-08 04:30:32 +0000379 // Did we find a matching token offset for this spelling?
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000380 if (TokOffset == FPos) {
381 uint32_t SpellingPTHOffset = Read32(Ptr);
382 Len = PTHMgr.getSpellingAtPTHOffset(SpellingPTHOffset, Buffer);
Ted Kremeneka4d5bf52009-01-08 04:30:32 +0000383 break;
384 }
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000385 } while (Ptr != TableEnd);
Ted Kremeneka4d5bf52009-01-08 04:30:32 +0000386
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000387 LinearItr = Ptr;
388 return Len;
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000389}
390
Chris Lattnerefb35342009-01-18 01:57:14 +0000391
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000392unsigned PTHSpellingSearch::getSpellingBinarySearch(unsigned FPos,
Chris Lattnerefb35342009-01-18 01:57:14 +0000393 const char *&Buffer) {
Ted Kremenekd310fde2009-01-09 22:05:30 +0000394
Ted Kremenek21069422009-01-13 22:05:50 +0000395 assert((TableEnd - TableBeg) % SpellingEntrySize == 0);
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000396 assert(TableEnd >= TableBeg);
Ted Kremenek21069422009-01-13 22:05:50 +0000397
398 if (TableEnd == TableBeg)
399 return 0;
400
Ted Kremenekd310fde2009-01-09 22:05:30 +0000401 unsigned min = 0;
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000402 const unsigned char *tb = TableBeg;
Ted Kremenek21069422009-01-13 22:05:50 +0000403 unsigned max = NumSpellings;
Ted Kremenekd310fde2009-01-09 22:05:30 +0000404
Ted Kremenek21069422009-01-13 22:05:50 +0000405 do {
Ted Kremenekd310fde2009-01-09 22:05:30 +0000406 unsigned i = (max - min) / 2 + min;
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000407 const unsigned char *Ptr = tb + (i * SpellingEntrySize);
Ted Kremenekd310fde2009-01-09 22:05:30 +0000408
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000409 uint32_t TokOffset = Read32(Ptr);
410 if (TokOffset > FPos) {
Ted Kremenekd310fde2009-01-09 22:05:30 +0000411 max = i;
Ted Kremenek21069422009-01-13 22:05:50 +0000412 assert(!(max == min) || (min == i));
Ted Kremenekd310fde2009-01-09 22:05:30 +0000413 continue;
414 }
415
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000416 if (TokOffset < FPos) {
Ted Kremenekc20d0ab2009-01-13 22:16:45 +0000417 if (i == min)
418 break;
419
Ted Kremenekd310fde2009-01-09 22:05:30 +0000420 min = i;
421 continue;
422 }
423
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000424 uint32_t SpellingPTHOffset = Read32(Ptr);
Ted Kremenekd310fde2009-01-09 22:05:30 +0000425 return PTHMgr.getSpellingAtPTHOffset(SpellingPTHOffset, Buffer);
426 }
Ted Kremenek21069422009-01-13 22:05:50 +0000427 while (min != max);
Ted Kremenekd310fde2009-01-09 22:05:30 +0000428
429 return 0;
430}
431
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000432unsigned PTHLexer::getSpelling(SourceLocation Loc, const char *&Buffer) {
433 SourceManager &SM = PP->getSourceManager();
434 Loc = SM.getSpellingLoc(Loc);
435 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedFileLoc(Loc);
436
437 FileID FID = LocInfo.first;
438 unsigned FPos = LocInfo.second;
Ted Kremenekd310fde2009-01-09 22:05:30 +0000439
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000440 if (FID == getFileID())
441 return MySpellingSrch.getSpellingLinearSearch(FPos, Buffer);
442 return PTHMgr.getSpelling(FID, FPos, Buffer);
Ted Kremenekd310fde2009-01-09 22:05:30 +0000443}
444
Ted Kremenek325cd302008-12-03 00:38:03 +0000445//===----------------------------------------------------------------------===//
Ted Kremenek325cd302008-12-03 00:38:03 +0000446// Internal Data Structures for PTH file lookup and resolving identifiers.
447//===----------------------------------------------------------------------===//
448
Ted Kremenek325cd302008-12-03 00:38:03 +0000449
450/// PTHFileLookup - This internal data structure is used by the PTHManager
451/// to map from FileEntry objects managed by FileManager to offsets within
452/// the PTH file.
453namespace {
454class VISIBILITY_HIDDEN PTHFileLookup {
455public:
456 class Val {
Ted Kremenek8309c922008-12-11 23:36:38 +0000457 uint32_t TokenOff;
458 uint32_t PPCondOff;
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000459 uint32_t SpellingOff;
Ted Kremenek325cd302008-12-03 00:38:03 +0000460 public:
Ted Kremenek8309c922008-12-11 23:36:38 +0000461 Val() : TokenOff(~0) {}
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000462 Val(uint32_t toff, uint32_t poff, uint32_t soff)
463 : TokenOff(toff), PPCondOff(poff), SpellingOff(soff) {}
Ted Kremenek325cd302008-12-03 00:38:03 +0000464
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000465 bool isValid() const { return TokenOff != ~((uint32_t)0); }
466
Ted Kremenek8309c922008-12-11 23:36:38 +0000467 uint32_t getTokenOffset() const {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000468 assert(isValid() && "PTHFileLookup entry initialized.");
Ted Kremenek8309c922008-12-11 23:36:38 +0000469 return TokenOff;
Ted Kremenek325cd302008-12-03 00:38:03 +0000470 }
471
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000472 uint32_t getPPCondOffset() const {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000473 assert(isValid() && "PTHFileLookup entry initialized.");
Ted Kremenek8309c922008-12-11 23:36:38 +0000474 return PPCondOff;
475 }
476
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000477 uint32_t getSpellingOffset() const {
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000478 assert(isValid() && "PTHFileLookup entry initialized.");
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000479 return SpellingOff;
480 }
Ted Kremenek325cd302008-12-03 00:38:03 +0000481 };
482
483private:
484 llvm::StringMap<Val> FileMap;
485
486public:
487 PTHFileLookup() {};
488
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000489 bool isEmpty() const {
490 return FileMap.empty();
491 }
492
Ted Kremenek325cd302008-12-03 00:38:03 +0000493 Val Lookup(const FileEntry* FE) {
494 const char* s = FE->getName();
495 unsigned size = strlen(s);
496 return FileMap.GetOrCreateValue(s, s+size).getValue();
497 }
498
Chris Lattnerefb35342009-01-18 01:57:14 +0000499 void ReadTable(const unsigned char* D) {
Ted Kremenek325cd302008-12-03 00:38:03 +0000500 uint32_t N = Read32(D); // Read the length of the table.
501
502 for ( ; N > 0; --N) { // The rest of the data is the table itself.
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000503 uint32_t Len = Read32(D);
Chris Lattnerefb35342009-01-18 01:57:14 +0000504 const char* s = (const char *)D;
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000505 D += Len;
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000506
Ted Kremenek8309c922008-12-11 23:36:38 +0000507 uint32_t TokenOff = Read32(D);
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000508 uint32_t PPCondOff = Read32(D);
509 uint32_t SpellingOff = Read32(D);
510
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000511 FileMap.GetOrCreateValue(s, s+Len).getValue() =
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000512 Val(TokenOff, PPCondOff, SpellingOff);
Ted Kremenek325cd302008-12-03 00:38:03 +0000513 }
514 }
515};
516} // end anonymous namespace
517
518//===----------------------------------------------------------------------===//
519// PTHManager methods.
520//===----------------------------------------------------------------------===//
521
522PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
Chris Lattnerefb35342009-01-18 01:57:14 +0000523 const unsigned char* idDataTable,
524 IdentifierInfo** perIDCache,
525 const unsigned char* sortedIdTable, unsigned numIds)
Ted Kremenekdb4c8e82008-12-03 01:16:39 +0000526: Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000527 IdDataTable(idDataTable), SortedIdTable(sortedIdTable),
528 NumIds(numIds), PP(0) {}
Ted Kremenek325cd302008-12-03 00:38:03 +0000529
530PTHManager::~PTHManager() {
531 delete Buf;
532 delete (PTHFileLookup*) FileLookup;
Ted Kremenek93bdc492008-12-04 22:47:11 +0000533 free(PerIDCache);
Ted Kremenek325cd302008-12-03 00:38:03 +0000534}
535
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000536PTHManager* PTHManager::Create(const std::string& file) {
Ted Kremenek325cd302008-12-03 00:38:03 +0000537 // Memory map the PTH file.
538 llvm::OwningPtr<llvm::MemoryBuffer>
539 File(llvm::MemoryBuffer::getFile(file.c_str()));
540
541 if (!File)
542 return 0;
543
544 // Get the buffer ranges and check if there are at least three 32-bit
545 // words at the end of the file.
Chris Lattnerefb35342009-01-18 01:57:14 +0000546 const unsigned char* BufBeg = (unsigned char*)File->getBufferStart();
547 const unsigned char* BufEnd = (unsigned char*)File->getBufferEnd();
Ted Kremenek325cd302008-12-03 00:38:03 +0000548
549 if(!(BufEnd > BufBeg + sizeof(uint32_t)*3)) {
550 assert(false && "Invalid PTH file.");
551 return 0; // FIXME: Proper error diagnostic?
552 }
553
554 // Compute the address of the index table at the end of the PTH file.
555 // This table contains the offset of the file lookup table, the
556 // persistent ID -> identifer data table.
Ted Kremenekd4d6d222009-01-15 01:26:25 +0000557 // FIXME: We should just embed this offset in the PTH file.
Chris Lattnerefb35342009-01-18 01:57:14 +0000558 const unsigned char* EndTable = BufEnd - sizeof(uint32_t)*4;
Ted Kremenek325cd302008-12-03 00:38:03 +0000559
560 // Construct the file lookup table. This will be used for mapping from
561 // FileEntry*'s to cached tokens.
Chris Lattnerefb35342009-01-18 01:57:14 +0000562 const unsigned char* FileTableOffset = EndTable + sizeof(uint32_t)*3;
563 const unsigned char* FileTable = BufBeg + Read32(FileTableOffset);
Ted Kremenek325cd302008-12-03 00:38:03 +0000564
565 if (!(FileTable > BufBeg && FileTable < BufEnd)) {
566 assert(false && "Invalid PTH file.");
567 return 0; // FIXME: Proper error diagnostic?
568 }
569
570 llvm::OwningPtr<PTHFileLookup> FL(new PTHFileLookup());
571 FL->ReadTable(FileTable);
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000572
573 if (FL->isEmpty())
574 return 0;
Ted Kremenek325cd302008-12-03 00:38:03 +0000575
576 // Get the location of the table mapping from persistent ids to the
577 // data needed to reconstruct identifiers.
Chris Lattnerefb35342009-01-18 01:57:14 +0000578 const unsigned char* IDTableOffset = EndTable + sizeof(uint32_t)*1;
579 const unsigned char* IData = BufBeg + Read32(IDTableOffset);
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000580
581 if (!(IData >= BufBeg && IData < BufEnd)) {
Ted Kremenek325cd302008-12-03 00:38:03 +0000582 assert(false && "Invalid PTH file.");
583 return 0; // FIXME: Proper error diagnostic?
584 }
585
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000586 // Get the location of the lexigraphically-sorted table of persistent IDs.
Chris Lattnerefb35342009-01-18 01:57:14 +0000587 const unsigned char* SortedIdTableOffset = EndTable + sizeof(uint32_t)*2;
588 const unsigned char* SortedIdTable = BufBeg + Read32(SortedIdTableOffset);
Ted Kremenekabaf7eb2009-01-21 07:34:28 +0000589 if (!(SortedIdTable >= BufBeg && SortedIdTable < BufEnd)) {
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000590 assert(false && "Invalid PTH file.");
591 return 0; // FIXME: Proper error diagnostic?
592 }
593
Ted Kremenekdb4c8e82008-12-03 01:16:39 +0000594 // Get the number of IdentifierInfos and pre-allocate the identifier cache.
595 uint32_t NumIds = Read32(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) {
605 assert(false && "Could not allocate Persistent ID cache.");
606 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,
612 SortedIdTable, NumIds);
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 =
618 (const unsigned char*)Buf->getBufferStart() + Read32(TableEntry);
619 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 Lattner0a6ec5d2009-01-18 02:10:31 +0000643 unsigned perID = Read32(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.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000685 PTHFileLookup::Val FileData = ((PTHFileLookup*)FileLookup)->Lookup(FE);
Ted Kremenek325cd302008-12-03 00:38:03 +0000686
Ted Kremenek8309c922008-12-11 23:36:38 +0000687 if (!FileData.isValid()) // No tokens available.
Ted Kremenek325cd302008-12-03 00:38:03 +0000688 return 0;
689
Chris Lattnerefb35342009-01-18 01:57:14 +0000690 const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart();
Ted Kremenek325cd302008-12-03 00:38:03 +0000691 // Compute the offset of the token data within the buffer.
Chris Lattnerefb35342009-01-18 01:57:14 +0000692 const unsigned char* data = BufStart + FileData.getTokenOffset();
Ted Kremenekc07091c2008-12-12 18:34:08 +0000693
694 // Get the location of pp-conditional table.
Chris Lattnerefb35342009-01-18 01:57:14 +0000695 const unsigned char* ppcond = BufStart + FileData.getPPCondOffset();
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000696 uint32_t Len = Read32(ppcond);
697 if (Len == 0) ppcond = 0;
Ted Kremeneka4d5bf52009-01-08 04:30:32 +0000698
699 // Get the location of the spelling table.
Chris Lattnerefb35342009-01-18 01:57:14 +0000700 const unsigned char* spellingTable = BufStart + FileData.getSpellingOffset();
Ted Kremeneka4d5bf52009-01-08 04:30:32 +0000701
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000702 Len = Read32(spellingTable);
703 if (Len == 0) spellingTable = 0;
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000704
Chris Lattnerefb35342009-01-18 01:57:14 +0000705 assert(data < (const unsigned char*)Buf->getBufferEnd());
Ted Kremenekd310fde2009-01-09 22:05:30 +0000706
707 // Create the SpellingSearch object for this FileID.
Chris Lattner0a6ec5d2009-01-18 02:10:31 +0000708 PTHSpellingSearch* ss = new PTHSpellingSearch(*this, Len, spellingTable);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000709 SpellingMap[FID] = ss;
Ted Kremenekd310fde2009-01-09 22:05:30 +0000710
Ted Kremenekd976c3d2009-01-15 18:47:46 +0000711 assert(PP && "No preprocessor set yet!");
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000712 return new PTHLexer(*PP, FID, data, ppcond, *ss, *this);
Ted Kremenek325cd302008-12-03 00:38:03 +0000713}