blob: 1038e3b70ccba6d6f2c39770961a473da2c93aa9 [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 Kremenek268ee702008-12-12 18:34:08 +000029#define DISK_TOKEN_SIZE (2+3*4)
30
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])
82 | (((uint32_t) CurPtrShadow[11]) << 8)
83 | (((uint32_t) CurPtrShadow[12]) << 16)
84 | (((uint32_t) CurPtrShadow[13]) << 24);
85
86 CurPtr = (const char*) (CurPtrShadow + DISK_TOKEN_SIZE);
87
88 //===--------------------------------------==//
89 // Construct the token itself.
90 //===--------------------------------------==//
91
92 Tok.startToken();
93 Tok.setKind(k);
94 Tok.setFlag(flags);
95 Tok.setIdentifierInfo(persistentID ? PTHMgr.GetIdentifierInfo(persistentID-1)
96 : 0);
97 Tok.setLocation(SourceLocation::getFileLoc(FileID, FileOffset));
98 Tok.setLength(Len);
99
100 //===--------------------------------------==//
101 // Process the token.
102 //===--------------------------------------==//
Ted Kremeneke5680f32008-12-23 01:30:52 +0000103
104 if (Tok.is(tok::eof)) {
105 // Save the end-of-file token.
106 EofToken = Tok;
107
108 Preprocessor *PPCache = PP;
109
110 if (LexEndOfFile(Tok))
111 return;
112
113 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
114 return PPCache->Lex(Tok);
115 }
116
117 MIOpt.ReadToken();
118
119 if (Tok.is(tok::eom)) {
120 ParsingPreprocessorDirective = false;
121 return;
122 }
123
124#if 0
125 SourceManager& SM = PP->getSourceManager();
126 SourceLocation L = Tok.getLocation();
127
128 static const char* last = 0;
129 const char* next = SM.getContentCacheForLoc(L)->Entry->getName();
130 if (next != last) {
131 last = next;
132 llvm::cerr << next << '\n';
133 }
134
135 llvm::cerr << "line " << SM.getLogicalLineNumber(L) << " col " <<
136 SM.getLogicalColumnNumber(L) << '\n';
137#endif
138
139 if (Tok.is(tok::hash)) {
140 if (Tok.isAtStartOfLine()) {
141 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
142 if (!LexingRawMode) {
143 PP->HandleDirective(Tok);
144
145 if (PP->isCurrentLexer(this))
146 goto LexNextToken;
147
148 return PP->Lex(Tok);
149 }
150 }
151 }
152
153 if (Tok.is(tok::identifier)) {
154 if (LexingRawMode) {
155 Tok.setIdentifierInfo(0);
156 return;
157 }
158
159 return PP->HandleIdentifier(Tok);
160 }
161
162
163 assert(!Tok.is(tok::eom) || ParsingPreprocessorDirective);
164}
165
166// FIXME: This method can just be inlined into Lex().
167bool PTHLexer::LexEndOfFile(Token &Tok) {
168 assert(!ParsingPreprocessorDirective);
169 assert(!LexingRawMode);
170
171 // FIXME: Issue diagnostics similar to Lexer.
172 return PP->HandleEndOfFile(Tok, false);
173}
174
175// FIXME: We can just grab the last token instead of storing a copy
176// into EofToken.
177void PTHLexer::setEOF(Token& Tok) {
178 assert(!EofToken.is(tok::eof));
179 Tok = EofToken;
180}
181
182void PTHLexer::DiscardToEndOfLine() {
183 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
184 "Must be in a preprocessing directive!");
185
186 // We assume that if the preprocessor wishes to discard to the end of
187 // the line that it also means to end the current preprocessor directive.
188 ParsingPreprocessorDirective = false;
189
190 // Skip tokens by only peeking at their token kind and the flags.
191 // We don't need to actually reconstruct full tokens from the token buffer.
192 // This saves some copies and it also reduces IdentifierInfo* lookup.
193 const char* p = CurPtr;
194 while (1) {
195 // Read the token kind. Are we at the end of the file?
196 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
197 if (x == tok::eof) break;
198
199 // Read the token flags. Are we at the start of the next line?
200 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
201 if (y & Token::StartOfLine) break;
202
203 // Skip to the next token.
204 p += DISK_TOKEN_SIZE;
205 }
206
207 CurPtr = p;
208}
209
Ted Kremenek268ee702008-12-12 18:34:08 +0000210/// SkipBlock - Used by Preprocessor to skip the current conditional block.
211bool PTHLexer::SkipBlock() {
212 assert(CurPPCondPtr && "No cached PP conditional information.");
213 assert(LastHashTokPtr && "No known '#' token.");
214
Ted Kremenek41a26602008-12-12 22:05:38 +0000215 const char* HashEntryI = 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000216 uint32_t Offset;
217 uint32_t TableIdx;
218
219 do {
Ted Kremenek41a26602008-12-12 22:05:38 +0000220 // Read the token offset from the side-table.
Ted Kremenek268ee702008-12-12 18:34:08 +0000221 Offset = Read32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000222
223 // Read the target table index from the side-table.
Ted Kremenek268ee702008-12-12 18:34:08 +0000224 TableIdx = Read32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000225
226 // Compute the actual memory address of the '#' token data for this entry.
227 HashEntryI = TokBuf + Offset;
228
229 // Optmization: "Sibling jumping". #if...#else...#endif blocks can
230 // contain nested blocks. In the side-table we can jump over these
231 // nested blocks instead of doing a linear search if the next "sibling"
232 // entry is not at a location greater than LastHashTokPtr.
233 if (HashEntryI < LastHashTokPtr && TableIdx) {
234 // In the side-table we are still at an entry for a '#' token that
235 // is earlier than the last one we saw. Check if the location we would
236 // stride gets us closer.
237 const char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
238 assert(NextPPCondPtr >= CurPPCondPtr);
239 // Read where we should jump to.
240 uint32_t TmpOffset = Read32(NextPPCondPtr);
241 const char* HashEntryJ = TokBuf + TmpOffset;
242
243 if (HashEntryJ <= LastHashTokPtr) {
244 // Jump directly to the next entry in the side table.
245 HashEntryI = HashEntryJ;
246 Offset = TmpOffset;
247 TableIdx = Read32(NextPPCondPtr);
248 CurPPCondPtr = NextPPCondPtr;
249 }
250 }
Ted Kremenek268ee702008-12-12 18:34:08 +0000251 }
Ted Kremenek41a26602008-12-12 22:05:38 +0000252 while (HashEntryI < LastHashTokPtr);
253 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
Ted Kremenek268ee702008-12-12 18:34:08 +0000254 assert(TableIdx && "No jumping from #endifs.");
255
256 // Update our side-table iterator.
257 const char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
258 assert(NextPPCondPtr >= CurPPCondPtr);
259 CurPPCondPtr = NextPPCondPtr;
260
261 // Read where we should jump to.
Ted Kremenek41a26602008-12-12 22:05:38 +0000262 HashEntryI = TokBuf + Read32(NextPPCondPtr);
Ted Kremenek268ee702008-12-12 18:34:08 +0000263 uint32_t NextIdx = Read32(NextPPCondPtr);
264
265 // By construction NextIdx will be zero if this is a #endif. This is useful
266 // to know to obviate lexing another token.
267 bool isEndif = NextIdx == 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000268
269 // This case can occur when we see something like this:
270 //
271 // #if ...
272 // /* a comment or nothing */
273 // #elif
274 //
275 // If we are skipping the first #if block it will be the case that CurPtr
276 // already points 'elif'. Just return.
277
Ted Kremenek41a26602008-12-12 22:05:38 +0000278 if (CurPtr > HashEntryI) {
279 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
Ted Kremenek268ee702008-12-12 18:34:08 +0000280 // Did we reach a #endif? If so, go ahead and consume that token as well.
281 if (isEndif)
Ted Kremeneke5680f32008-12-23 01:30:52 +0000282 CurPtr += DISK_TOKEN_SIZE*2;
Ted Kremenek268ee702008-12-12 18:34:08 +0000283 else
Ted Kremenek41a26602008-12-12 22:05:38 +0000284 LastHashTokPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000285
286 return isEndif;
287 }
288
289 // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
Ted Kremenek41a26602008-12-12 22:05:38 +0000290 CurPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000291
292 // Update the location of the last observed '#'. This is useful if we
293 // are skipping multiple blocks.
294 LastHashTokPtr = CurPtr;
Ted Kremenek268ee702008-12-12 18:34:08 +0000295
Ted Kremeneke5680f32008-12-23 01:30:52 +0000296 // Skip the '#' token.
297 assert(((tok::TokenKind) (unsigned char) *CurPtr) == tok::hash);
298 CurPtr += DISK_TOKEN_SIZE;
299
Ted Kremenek268ee702008-12-12 18:34:08 +0000300 // Did we reach a #endif? If so, go ahead and consume that token as well.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000301 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
Ted Kremenek268ee702008-12-12 18:34:08 +0000302
303 return isEndif;
304}
305
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000306SourceLocation PTHLexer::getSourceLocation() {
307 // getLocation is not on the hot path. It is used to get the location of
308 // the next token when transitioning back to this lexer when done
309 // handling a #included file. Just read the necessary data from the token
310 // data buffer to construct the SourceLocation object.
311 // NOTE: This is a virtual function; hence it is defined out-of-line.
312 const char* p = CurPtr + (1 + 1 + 4);
313 uint32_t offset =
314 ((uint32_t) ((uint8_t) p[0]))
315 | (((uint32_t) ((uint8_t) p[1])) << 8)
316 | (((uint32_t) ((uint8_t) p[2])) << 16)
317 | (((uint32_t) ((uint8_t) p[3])) << 24);
318 return SourceLocation::getFileLoc(FileID, offset);
319}
320
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000321//===----------------------------------------------------------------------===//
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000322// Internal Data Structures for PTH file lookup and resolving identifiers.
323//===----------------------------------------------------------------------===//
324
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000325
326/// PTHFileLookup - This internal data structure is used by the PTHManager
327/// to map from FileEntry objects managed by FileManager to offsets within
328/// the PTH file.
329namespace {
330class VISIBILITY_HIDDEN PTHFileLookup {
331public:
332 class Val {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000333 uint32_t TokenOff;
334 uint32_t PPCondOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000335
336 public:
Ted Kremenekfb645b62008-12-11 23:36:38 +0000337 Val() : TokenOff(~0) {}
338 Val(uint32_t toff, uint32_t poff) : TokenOff(toff), PPCondOff(poff) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000339
Ted Kremenekfb645b62008-12-11 23:36:38 +0000340 uint32_t getTokenOffset() const {
341 assert(TokenOff != ~((uint32_t)0) && "PTHFileLookup entry initialized.");
342 return TokenOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000343 }
344
Ted Kremenekfb645b62008-12-11 23:36:38 +0000345 uint32_t gettPPCondOffset() const {
346 assert(TokenOff != ~((uint32_t)0) && "PTHFileLookup entry initialized.");
347 return PPCondOff;
348 }
349
350 bool isValid() const { return TokenOff != ~((uint32_t)0); }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000351 };
352
353private:
354 llvm::StringMap<Val> FileMap;
355
356public:
357 PTHFileLookup() {};
358
359 Val Lookup(const FileEntry* FE) {
360 const char* s = FE->getName();
361 unsigned size = strlen(s);
362 return FileMap.GetOrCreateValue(s, s+size).getValue();
363 }
364
365 void ReadTable(const char* D) {
366 uint32_t N = Read32(D); // Read the length of the table.
367
368 for ( ; N > 0; --N) { // The rest of the data is the table itself.
369 uint32_t len = Read32(D);
370 const char* s = D;
371 D += len;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000372 uint32_t TokenOff = Read32(D);
373 FileMap.GetOrCreateValue(s, s+len).getValue() = Val(TokenOff, Read32(D));
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000374 }
375 }
376};
377} // end anonymous namespace
378
379//===----------------------------------------------------------------------===//
380// PTHManager methods.
381//===----------------------------------------------------------------------===//
382
383PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
Ted Kremenekcf58e622008-12-10 19:40:23 +0000384 const char* idDataTable, IdentifierInfo** perIDCache,
Ted Kremenek6183e482008-12-03 01:16:39 +0000385 Preprocessor& pp)
386: Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
387 IdDataTable(idDataTable), ITable(pp.getIdentifierTable()), PP(pp) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000388
389PTHManager::~PTHManager() {
390 delete Buf;
391 delete (PTHFileLookup*) FileLookup;
Ted Kremenek0e50b6e2008-12-04 22:47:11 +0000392 free(PerIDCache);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000393}
394
395PTHManager* PTHManager::Create(const std::string& file, Preprocessor& PP) {
396
397 // Memory map the PTH file.
398 llvm::OwningPtr<llvm::MemoryBuffer>
399 File(llvm::MemoryBuffer::getFile(file.c_str()));
400
401 if (!File)
402 return 0;
403
404 // Get the buffer ranges and check if there are at least three 32-bit
405 // words at the end of the file.
406 const char* BufBeg = File->getBufferStart();
407 const char* BufEnd = File->getBufferEnd();
408
409 if(!(BufEnd > BufBeg + sizeof(uint32_t)*3)) {
410 assert(false && "Invalid PTH file.");
411 return 0; // FIXME: Proper error diagnostic?
412 }
413
414 // Compute the address of the index table at the end of the PTH file.
415 // This table contains the offset of the file lookup table, the
416 // persistent ID -> identifer data table.
417 const char* EndTable = BufEnd - sizeof(uint32_t)*3;
418
419 // Construct the file lookup table. This will be used for mapping from
420 // FileEntry*'s to cached tokens.
421 const char* FileTableOffset = EndTable + sizeof(uint32_t)*2;
422 const char* FileTable = BufBeg + Read32(FileTableOffset);
423
424 if (!(FileTable > BufBeg && FileTable < BufEnd)) {
425 assert(false && "Invalid PTH file.");
426 return 0; // FIXME: Proper error diagnostic?
427 }
428
429 llvm::OwningPtr<PTHFileLookup> FL(new PTHFileLookup());
430 FL->ReadTable(FileTable);
431
432 // Get the location of the table mapping from persistent ids to the
433 // data needed to reconstruct identifiers.
434 const char* IDTableOffset = EndTable + sizeof(uint32_t)*1;
435 const char* IData = BufBeg + Read32(IDTableOffset);
436 if (!(IData > BufBeg && IData < BufEnd)) {
437 assert(false && "Invalid PTH file.");
438 return 0; // FIXME: Proper error diagnostic?
439 }
440
Ted Kremenek6183e482008-12-03 01:16:39 +0000441 // Get the number of IdentifierInfos and pre-allocate the identifier cache.
442 uint32_t NumIds = Read32(IData);
443
444 // Pre-allocate the peristent ID -> IdentifierInfo* cache. We use calloc()
445 // so that we in the best case only zero out memory once when the OS returns
446 // us new pages.
447 IdentifierInfo** PerIDCache =
448 (IdentifierInfo**) calloc(NumIds, sizeof(*PerIDCache));
449
450 if (!PerIDCache) {
451 assert(false && "Could not allocate Persistent ID cache.");
452 return 0;
453 }
454
455 // Create the new lexer.
456 return new PTHManager(File.take(), FL.take(), IData, PerIDCache, PP);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000457}
458
Ted Kremenek866bdf72008-12-23 02:30:15 +0000459IdentifierInfo* PTHManager::GetIdentifierInfo(unsigned persistentID) {
460
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000461 // Check if the IdentifierInfo has already been resolved.
Ted Kremenekcf58e622008-12-10 19:40:23 +0000462 IdentifierInfo*& II = PerIDCache[persistentID];
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000463 if (II) return II;
464
465 // Look in the PTH file for the string data for the IdentifierInfo object.
466 const char* TableEntry = IdDataTable + sizeof(uint32_t) * persistentID;
467 const char* IDData = Buf->getBufferStart() + Read32(TableEntry);
468 assert(IDData < Buf->getBufferEnd());
469
470 // Read the length of the string.
471 uint32_t len = Read32(IDData);
472
473 // Get the IdentifierInfo* with the specified string.
474 II = &ITable.get(IDData, IDData+len);
475 return II;
476}
477
478PTHLexer* PTHManager::CreateLexer(unsigned FileID, const FileEntry* FE) {
479
480 if (!FE)
481 return 0;
482
483 // Lookup the FileEntry object in our file lookup data structure. It will
484 // return a variant that indicates whether or not there is an offset within
485 // the PTH file that contains cached tokens.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000486 PTHFileLookup::Val FileData = ((PTHFileLookup*) FileLookup)->Lookup(FE);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000487
Ted Kremenekfb645b62008-12-11 23:36:38 +0000488 if (!FileData.isValid()) // No tokens available.
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000489 return 0;
490
491 // Compute the offset of the token data within the buffer.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000492 const char* data = Buf->getBufferStart() + FileData.getTokenOffset();
Ted Kremenek268ee702008-12-12 18:34:08 +0000493
494 // Get the location of pp-conditional table.
495 const char* ppcond = Buf->getBufferStart() + FileData.gettPPCondOffset();
496 uint32_t len = Read32(ppcond);
497 if (len == 0) ppcond = 0;
498
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000499 assert(data < Buf->getBufferEnd());
Ted Kremenek268ee702008-12-12 18:34:08 +0000500 return new PTHLexer(PP, SourceLocation::getFileLoc(FileID, 0), data, ppcond,
501 *this);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000502}