blob: 252e2f87daa98e8a97ae3dae98a578feafabafad [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 Kremenek0c6a77b2008-12-03 00:38:03 +000026
Ted Kremenek274b2082008-11-12 21:37:15 +000027using namespace clang;
28
Ted Kremenek8f174e12008-12-23 02:52:12 +000029#define DISK_TOKEN_SIZE (2+4+4+2)
Ted Kremenek268ee702008-12-12 18:34:08 +000030
Ted Kremenek0c6a77b2008-12-03 00:38:03 +000031//===----------------------------------------------------------------------===//
32// Utility methods for reading from the mmap'ed PTH file.
33//===----------------------------------------------------------------------===//
34
35static inline uint8_t Read8(const char*& data) {
36 return (uint8_t) *(data++);
37}
38
39static inline uint32_t Read32(const char*& data) {
40 uint32_t V = (uint32_t) Read8(data);
41 V |= (((uint32_t) Read8(data)) << 8);
42 V |= (((uint32_t) Read8(data)) << 16);
43 V |= (((uint32_t) Read8(data)) << 24);
44 return V;
45}
46
Ted Kremeneke5680f32008-12-23 01:30:52 +000047//===----------------------------------------------------------------------===//
48// PTHLexer methods.
49//===----------------------------------------------------------------------===//
50
51PTHLexer::PTHLexer(Preprocessor& pp, SourceLocation fileloc, const char* D,
52 const char* ppcond, PTHManager& PM)
53 : PreprocessorLexer(&pp, fileloc), TokBuf(D), CurPtr(D), LastHashTokPtr(0),
54 PPCond(ppcond), CurPPCondPtr(ppcond), PTHMgr(PM) {}
55
56void PTHLexer::Lex(Token& Tok) {
57LexNextToken:
Ted Kremeneke5680f32008-12-23 01:30:52 +000058
Ted Kremenek866bdf72008-12-23 02:30:15 +000059 //===--------------------------------------==//
60 // Read the raw token data.
61 //===--------------------------------------==//
62
63 // Shadow CurPtr into an automatic variable.
64 const unsigned char *CurPtrShadow = (const unsigned char*) CurPtr;
65
66 // Read in the data for the token. 14 bytes in total.
67 tok::TokenKind k = (tok::TokenKind) CurPtrShadow[0];
68 Token::TokenFlags flags = (Token::TokenFlags) CurPtrShadow[1];
69
70 uint32_t persistentID = ((uint32_t) CurPtrShadow[2])
71 | (((uint32_t) CurPtrShadow[3]) << 8)
72 | (((uint32_t) CurPtrShadow[4]) << 16)
73 | (((uint32_t) CurPtrShadow[5]) << 24);
74
75
76 uint32_t FileOffset = ((uint32_t) CurPtrShadow[6])
77 | (((uint32_t) CurPtrShadow[7]) << 8)
78 | (((uint32_t) CurPtrShadow[8]) << 16)
79 | (((uint32_t) CurPtrShadow[9]) << 24);
80
81 uint32_t Len = ((uint32_t) CurPtrShadow[10])
Ted Kremenek8f174e12008-12-23 02:52:12 +000082 | (((uint32_t) CurPtrShadow[11]) << 8);
Ted Kremenek866bdf72008-12-23 02:30:15 +000083
84 CurPtr = (const char*) (CurPtrShadow + DISK_TOKEN_SIZE);
85
86 //===--------------------------------------==//
87 // Construct the token itself.
88 //===--------------------------------------==//
89
90 Tok.startToken();
91 Tok.setKind(k);
92 Tok.setFlag(flags);
93 Tok.setIdentifierInfo(persistentID ? PTHMgr.GetIdentifierInfo(persistentID-1)
94 : 0);
95 Tok.setLocation(SourceLocation::getFileLoc(FileID, FileOffset));
96 Tok.setLength(Len);
97
98 //===--------------------------------------==//
99 // Process the token.
100 //===--------------------------------------==//
Ted Kremeneke5680f32008-12-23 01:30:52 +0000101
102 if (Tok.is(tok::eof)) {
103 // Save the end-of-file token.
104 EofToken = Tok;
105
106 Preprocessor *PPCache = PP;
107
108 if (LexEndOfFile(Tok))
109 return;
110
111 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
112 return PPCache->Lex(Tok);
113 }
114
115 MIOpt.ReadToken();
116
117 if (Tok.is(tok::eom)) {
118 ParsingPreprocessorDirective = false;
119 return;
120 }
121
122#if 0
123 SourceManager& SM = PP->getSourceManager();
124 SourceLocation L = Tok.getLocation();
125
126 static const char* last = 0;
127 const char* next = SM.getContentCacheForLoc(L)->Entry->getName();
128 if (next != last) {
129 last = next;
130 llvm::cerr << next << '\n';
131 }
132
133 llvm::cerr << "line " << SM.getLogicalLineNumber(L) << " col " <<
134 SM.getLogicalColumnNumber(L) << '\n';
135#endif
136
137 if (Tok.is(tok::hash)) {
138 if (Tok.isAtStartOfLine()) {
139 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
140 if (!LexingRawMode) {
141 PP->HandleDirective(Tok);
142
143 if (PP->isCurrentLexer(this))
144 goto LexNextToken;
145
146 return PP->Lex(Tok);
147 }
148 }
149 }
150
151 if (Tok.is(tok::identifier)) {
152 if (LexingRawMode) {
153 Tok.setIdentifierInfo(0);
154 return;
155 }
156
157 return PP->HandleIdentifier(Tok);
158 }
159
160
161 assert(!Tok.is(tok::eom) || ParsingPreprocessorDirective);
162}
163
164// FIXME: This method can just be inlined into Lex().
165bool PTHLexer::LexEndOfFile(Token &Tok) {
166 assert(!ParsingPreprocessorDirective);
167 assert(!LexingRawMode);
168
169 // FIXME: Issue diagnostics similar to Lexer.
170 return PP->HandleEndOfFile(Tok, false);
171}
172
173// FIXME: We can just grab the last token instead of storing a copy
174// into EofToken.
175void PTHLexer::setEOF(Token& Tok) {
176 assert(!EofToken.is(tok::eof));
177 Tok = EofToken;
178}
179
180void PTHLexer::DiscardToEndOfLine() {
181 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
182 "Must be in a preprocessing directive!");
183
184 // We assume that if the preprocessor wishes to discard to the end of
185 // the line that it also means to end the current preprocessor directive.
186 ParsingPreprocessorDirective = false;
187
188 // Skip tokens by only peeking at their token kind and the flags.
189 // We don't need to actually reconstruct full tokens from the token buffer.
190 // This saves some copies and it also reduces IdentifierInfo* lookup.
191 const char* p = CurPtr;
192 while (1) {
193 // Read the token kind. Are we at the end of the file?
194 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
195 if (x == tok::eof) break;
196
197 // Read the token flags. Are we at the start of the next line?
198 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
199 if (y & Token::StartOfLine) break;
200
201 // Skip to the next token.
202 p += DISK_TOKEN_SIZE;
203 }
204
205 CurPtr = p;
206}
207
Ted Kremenek268ee702008-12-12 18:34:08 +0000208/// SkipBlock - Used by Preprocessor to skip the current conditional block.
209bool PTHLexer::SkipBlock() {
210 assert(CurPPCondPtr && "No cached PP conditional information.");
211 assert(LastHashTokPtr && "No known '#' token.");
212
Ted Kremenek41a26602008-12-12 22:05:38 +0000213 const char* HashEntryI = 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000214 uint32_t Offset;
215 uint32_t TableIdx;
216
217 do {
Ted Kremenek41a26602008-12-12 22:05:38 +0000218 // Read the token offset from the side-table.
Ted Kremenek268ee702008-12-12 18:34:08 +0000219 Offset = Read32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000220
221 // Read the target table index from the side-table.
Ted Kremenek268ee702008-12-12 18:34:08 +0000222 TableIdx = Read32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000223
224 // Compute the actual memory address of the '#' token data for this entry.
225 HashEntryI = TokBuf + Offset;
226
227 // Optmization: "Sibling jumping". #if...#else...#endif blocks can
228 // contain nested blocks. In the side-table we can jump over these
229 // nested blocks instead of doing a linear search if the next "sibling"
230 // entry is not at a location greater than LastHashTokPtr.
231 if (HashEntryI < LastHashTokPtr && TableIdx) {
232 // In the side-table we are still at an entry for a '#' token that
233 // is earlier than the last one we saw. Check if the location we would
234 // stride gets us closer.
235 const char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
236 assert(NextPPCondPtr >= CurPPCondPtr);
237 // Read where we should jump to.
238 uint32_t TmpOffset = Read32(NextPPCondPtr);
239 const char* HashEntryJ = TokBuf + TmpOffset;
240
241 if (HashEntryJ <= LastHashTokPtr) {
242 // Jump directly to the next entry in the side table.
243 HashEntryI = HashEntryJ;
244 Offset = TmpOffset;
245 TableIdx = Read32(NextPPCondPtr);
246 CurPPCondPtr = NextPPCondPtr;
247 }
248 }
Ted Kremenek268ee702008-12-12 18:34:08 +0000249 }
Ted Kremenek41a26602008-12-12 22:05:38 +0000250 while (HashEntryI < LastHashTokPtr);
251 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
Ted Kremenek268ee702008-12-12 18:34:08 +0000252 assert(TableIdx && "No jumping from #endifs.");
253
254 // Update our side-table iterator.
255 const char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
256 assert(NextPPCondPtr >= CurPPCondPtr);
257 CurPPCondPtr = NextPPCondPtr;
258
259 // Read where we should jump to.
Ted Kremenek41a26602008-12-12 22:05:38 +0000260 HashEntryI = TokBuf + Read32(NextPPCondPtr);
Ted Kremenek268ee702008-12-12 18:34:08 +0000261 uint32_t NextIdx = Read32(NextPPCondPtr);
262
263 // By construction NextIdx will be zero if this is a #endif. This is useful
264 // to know to obviate lexing another token.
265 bool isEndif = NextIdx == 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000266
267 // This case can occur when we see something like this:
268 //
269 // #if ...
270 // /* a comment or nothing */
271 // #elif
272 //
273 // If we are skipping the first #if block it will be the case that CurPtr
274 // already points 'elif'. Just return.
275
Ted Kremenek41a26602008-12-12 22:05:38 +0000276 if (CurPtr > HashEntryI) {
277 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
Ted Kremenek268ee702008-12-12 18:34:08 +0000278 // Did we reach a #endif? If so, go ahead and consume that token as well.
279 if (isEndif)
Ted Kremeneke5680f32008-12-23 01:30:52 +0000280 CurPtr += DISK_TOKEN_SIZE*2;
Ted Kremenek268ee702008-12-12 18:34:08 +0000281 else
Ted Kremenek41a26602008-12-12 22:05:38 +0000282 LastHashTokPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000283
284 return isEndif;
285 }
286
287 // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
Ted Kremenek41a26602008-12-12 22:05:38 +0000288 CurPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000289
290 // Update the location of the last observed '#'. This is useful if we
291 // are skipping multiple blocks.
292 LastHashTokPtr = CurPtr;
Ted Kremenek268ee702008-12-12 18:34:08 +0000293
Ted Kremeneke5680f32008-12-23 01:30:52 +0000294 // Skip the '#' token.
295 assert(((tok::TokenKind) (unsigned char) *CurPtr) == tok::hash);
296 CurPtr += DISK_TOKEN_SIZE;
297
Ted Kremenek268ee702008-12-12 18:34:08 +0000298 // Did we reach a #endif? If so, go ahead and consume that token as well.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000299 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
Ted Kremenek268ee702008-12-12 18:34:08 +0000300
301 return isEndif;
302}
303
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000304SourceLocation PTHLexer::getSourceLocation() {
305 // getLocation is not on the hot path. It is used to get the location of
306 // the next token when transitioning back to this lexer when done
307 // handling a #included file. Just read the necessary data from the token
308 // data buffer to construct the SourceLocation object.
309 // NOTE: This is a virtual function; hence it is defined out-of-line.
310 const char* p = CurPtr + (1 + 1 + 4);
311 uint32_t offset =
312 ((uint32_t) ((uint8_t) p[0]))
313 | (((uint32_t) ((uint8_t) p[1])) << 8)
314 | (((uint32_t) ((uint8_t) p[2])) << 16)
315 | (((uint32_t) ((uint8_t) p[3])) << 24);
316 return SourceLocation::getFileLoc(FileID, offset);
317}
318
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000319//===----------------------------------------------------------------------===//
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000320// Internal Data Structures for PTH file lookup and resolving identifiers.
321//===----------------------------------------------------------------------===//
322
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000323
324/// PTHFileLookup - This internal data structure is used by the PTHManager
325/// to map from FileEntry objects managed by FileManager to offsets within
326/// the PTH file.
327namespace {
328class VISIBILITY_HIDDEN PTHFileLookup {
329public:
330 class Val {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000331 uint32_t TokenOff;
332 uint32_t PPCondOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000333
334 public:
Ted Kremenekfb645b62008-12-11 23:36:38 +0000335 Val() : TokenOff(~0) {}
336 Val(uint32_t toff, uint32_t poff) : TokenOff(toff), PPCondOff(poff) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000337
Ted Kremenekfb645b62008-12-11 23:36:38 +0000338 uint32_t getTokenOffset() const {
339 assert(TokenOff != ~((uint32_t)0) && "PTHFileLookup entry initialized.");
340 return TokenOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000341 }
342
Ted Kremenekfb645b62008-12-11 23:36:38 +0000343 uint32_t gettPPCondOffset() const {
344 assert(TokenOff != ~((uint32_t)0) && "PTHFileLookup entry initialized.");
345 return PPCondOff;
346 }
347
348 bool isValid() const { return TokenOff != ~((uint32_t)0); }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000349 };
350
351private:
352 llvm::StringMap<Val> FileMap;
353
354public:
355 PTHFileLookup() {};
356
357 Val Lookup(const FileEntry* FE) {
358 const char* s = FE->getName();
359 unsigned size = strlen(s);
360 return FileMap.GetOrCreateValue(s, s+size).getValue();
361 }
362
363 void ReadTable(const char* D) {
364 uint32_t N = Read32(D); // Read the length of the table.
365
366 for ( ; N > 0; --N) { // The rest of the data is the table itself.
367 uint32_t len = Read32(D);
368 const char* s = D;
369 D += len;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000370 uint32_t TokenOff = Read32(D);
371 FileMap.GetOrCreateValue(s, s+len).getValue() = Val(TokenOff, Read32(D));
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000372 }
373 }
374};
375} // end anonymous namespace
376
377//===----------------------------------------------------------------------===//
378// PTHManager methods.
379//===----------------------------------------------------------------------===//
380
381PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
Ted Kremenekcf58e622008-12-10 19:40:23 +0000382 const char* idDataTable, IdentifierInfo** perIDCache,
Ted Kremenek6183e482008-12-03 01:16:39 +0000383 Preprocessor& pp)
384: Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
385 IdDataTable(idDataTable), ITable(pp.getIdentifierTable()), PP(pp) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000386
387PTHManager::~PTHManager() {
388 delete Buf;
389 delete (PTHFileLookup*) FileLookup;
Ted Kremenek0e50b6e2008-12-04 22:47:11 +0000390 free(PerIDCache);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000391}
392
393PTHManager* PTHManager::Create(const std::string& file, Preprocessor& PP) {
394
395 // Memory map the PTH file.
396 llvm::OwningPtr<llvm::MemoryBuffer>
397 File(llvm::MemoryBuffer::getFile(file.c_str()));
398
399 if (!File)
400 return 0;
401
402 // Get the buffer ranges and check if there are at least three 32-bit
403 // words at the end of the file.
404 const char* BufBeg = File->getBufferStart();
405 const char* BufEnd = File->getBufferEnd();
406
407 if(!(BufEnd > BufBeg + sizeof(uint32_t)*3)) {
408 assert(false && "Invalid PTH file.");
409 return 0; // FIXME: Proper error diagnostic?
410 }
411
412 // Compute the address of the index table at the end of the PTH file.
413 // This table contains the offset of the file lookup table, the
414 // persistent ID -> identifer data table.
415 const char* EndTable = BufEnd - sizeof(uint32_t)*3;
416
417 // Construct the file lookup table. This will be used for mapping from
418 // FileEntry*'s to cached tokens.
419 const char* FileTableOffset = EndTable + sizeof(uint32_t)*2;
420 const char* FileTable = BufBeg + Read32(FileTableOffset);
421
422 if (!(FileTable > BufBeg && FileTable < BufEnd)) {
423 assert(false && "Invalid PTH file.");
424 return 0; // FIXME: Proper error diagnostic?
425 }
426
427 llvm::OwningPtr<PTHFileLookup> FL(new PTHFileLookup());
428 FL->ReadTable(FileTable);
429
430 // Get the location of the table mapping from persistent ids to the
431 // data needed to reconstruct identifiers.
432 const char* IDTableOffset = EndTable + sizeof(uint32_t)*1;
433 const char* IData = BufBeg + Read32(IDTableOffset);
434 if (!(IData > BufBeg && IData < BufEnd)) {
435 assert(false && "Invalid PTH file.");
436 return 0; // FIXME: Proper error diagnostic?
437 }
438
Ted Kremenek6183e482008-12-03 01:16:39 +0000439 // Get the number of IdentifierInfos and pre-allocate the identifier cache.
440 uint32_t NumIds = Read32(IData);
441
442 // Pre-allocate the peristent ID -> IdentifierInfo* cache. We use calloc()
443 // so that we in the best case only zero out memory once when the OS returns
444 // us new pages.
445 IdentifierInfo** PerIDCache =
446 (IdentifierInfo**) calloc(NumIds, sizeof(*PerIDCache));
447
448 if (!PerIDCache) {
449 assert(false && "Could not allocate Persistent ID cache.");
450 return 0;
451 }
452
453 // Create the new lexer.
454 return new PTHManager(File.take(), FL.take(), IData, PerIDCache, PP);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000455}
456
Ted Kremenek866bdf72008-12-23 02:30:15 +0000457IdentifierInfo* PTHManager::GetIdentifierInfo(unsigned persistentID) {
458
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000459 // Check if the IdentifierInfo has already been resolved.
Ted Kremenekcf58e622008-12-10 19:40:23 +0000460 IdentifierInfo*& II = PerIDCache[persistentID];
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000461 if (II) return II;
462
463 // Look in the PTH file for the string data for the IdentifierInfo object.
464 const char* TableEntry = IdDataTable + sizeof(uint32_t) * persistentID;
465 const char* IDData = Buf->getBufferStart() + Read32(TableEntry);
466 assert(IDData < Buf->getBufferEnd());
467
468 // Read the length of the string.
469 uint32_t len = Read32(IDData);
470
471 // Get the IdentifierInfo* with the specified string.
472 II = &ITable.get(IDData, IDData+len);
473 return II;
474}
475
476PTHLexer* PTHManager::CreateLexer(unsigned FileID, const FileEntry* FE) {
477
478 if (!FE)
479 return 0;
480
481 // Lookup the FileEntry object in our file lookup data structure. It will
482 // return a variant that indicates whether or not there is an offset within
483 // the PTH file that contains cached tokens.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000484 PTHFileLookup::Val FileData = ((PTHFileLookup*) FileLookup)->Lookup(FE);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000485
Ted Kremenekfb645b62008-12-11 23:36:38 +0000486 if (!FileData.isValid()) // No tokens available.
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000487 return 0;
488
489 // Compute the offset of the token data within the buffer.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000490 const char* data = Buf->getBufferStart() + FileData.getTokenOffset();
Ted Kremenek268ee702008-12-12 18:34:08 +0000491
492 // Get the location of pp-conditional table.
493 const char* ppcond = Buf->getBufferStart() + FileData.gettPPCondOffset();
494 uint32_t len = Read32(ppcond);
495 if (len == 0) ppcond = 0;
496
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000497 assert(data < Buf->getBufferEnd());
Ted Kremenek268ee702008-12-12 18:34:08 +0000498 return new PTHLexer(PP, SourceLocation::getFileLoc(FileID, 0), data, ppcond,
499 *this);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000500}