blob: 2c19fcd0d9a73d450ef1571ee5de5a49872ee97f [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:
58
59 // Read the token.
60 // FIXME: Setting the flags directly should obviate this step.
61 Tok.startToken();
62
63 // Shadow CurPtr into an automatic variable so that Read8 doesn't load and
64 // store back into the instance variable.
65 const char *CurPtrShadow = CurPtr;
66
67 // Read the type of the token.
68 Tok.setKind((tok::TokenKind) Read8(CurPtrShadow));
69
70 // Set flags. This is gross, since we are really setting multiple flags.
71 Tok.setFlag((Token::TokenFlags) Read8(CurPtrShadow));
72
73 // Set the IdentifierInfo* (if any).
74 Tok.setIdentifierInfo(PTHMgr.ReadIdentifierInfo(CurPtrShadow));
75
76 // Set the SourceLocation. Since all tokens are constructed using a
77 // raw lexer, they will all be offseted from the same FileID.
78 Tok.setLocation(SourceLocation::getFileLoc(FileID, Read32(CurPtrShadow)));
79
80 // Finally, read and set the length of the token.
81 Tok.setLength(Read32(CurPtrShadow));
82
83 CurPtr = CurPtrShadow;
84
85 if (Tok.is(tok::eof)) {
86 // Save the end-of-file token.
87 EofToken = Tok;
88
89 Preprocessor *PPCache = PP;
90
91 if (LexEndOfFile(Tok))
92 return;
93
94 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
95 return PPCache->Lex(Tok);
96 }
97
98 MIOpt.ReadToken();
99
100 if (Tok.is(tok::eom)) {
101 ParsingPreprocessorDirective = false;
102 return;
103 }
104
105#if 0
106 SourceManager& SM = PP->getSourceManager();
107 SourceLocation L = Tok.getLocation();
108
109 static const char* last = 0;
110 const char* next = SM.getContentCacheForLoc(L)->Entry->getName();
111 if (next != last) {
112 last = next;
113 llvm::cerr << next << '\n';
114 }
115
116 llvm::cerr << "line " << SM.getLogicalLineNumber(L) << " col " <<
117 SM.getLogicalColumnNumber(L) << '\n';
118#endif
119
120 if (Tok.is(tok::hash)) {
121 if (Tok.isAtStartOfLine()) {
122 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
123 if (!LexingRawMode) {
124 PP->HandleDirective(Tok);
125
126 if (PP->isCurrentLexer(this))
127 goto LexNextToken;
128
129 return PP->Lex(Tok);
130 }
131 }
132 }
133
134 if (Tok.is(tok::identifier)) {
135 if (LexingRawMode) {
136 Tok.setIdentifierInfo(0);
137 return;
138 }
139
140 return PP->HandleIdentifier(Tok);
141 }
142
143
144 assert(!Tok.is(tok::eom) || ParsingPreprocessorDirective);
145}
146
147// FIXME: This method can just be inlined into Lex().
148bool PTHLexer::LexEndOfFile(Token &Tok) {
149 assert(!ParsingPreprocessorDirective);
150 assert(!LexingRawMode);
151
152 // FIXME: Issue diagnostics similar to Lexer.
153 return PP->HandleEndOfFile(Tok, false);
154}
155
156// FIXME: We can just grab the last token instead of storing a copy
157// into EofToken.
158void PTHLexer::setEOF(Token& Tok) {
159 assert(!EofToken.is(tok::eof));
160 Tok = EofToken;
161}
162
163void PTHLexer::DiscardToEndOfLine() {
164 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
165 "Must be in a preprocessing directive!");
166
167 // We assume that if the preprocessor wishes to discard to the end of
168 // the line that it also means to end the current preprocessor directive.
169 ParsingPreprocessorDirective = false;
170
171 // Skip tokens by only peeking at their token kind and the flags.
172 // We don't need to actually reconstruct full tokens from the token buffer.
173 // This saves some copies and it also reduces IdentifierInfo* lookup.
174 const char* p = CurPtr;
175 while (1) {
176 // Read the token kind. Are we at the end of the file?
177 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
178 if (x == tok::eof) break;
179
180 // Read the token flags. Are we at the start of the next line?
181 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
182 if (y & Token::StartOfLine) break;
183
184 // Skip to the next token.
185 p += DISK_TOKEN_SIZE;
186 }
187
188 CurPtr = p;
189}
190
Ted Kremenek268ee702008-12-12 18:34:08 +0000191/// SkipBlock - Used by Preprocessor to skip the current conditional block.
192bool PTHLexer::SkipBlock() {
193 assert(CurPPCondPtr && "No cached PP conditional information.");
194 assert(LastHashTokPtr && "No known '#' token.");
195
Ted Kremenek41a26602008-12-12 22:05:38 +0000196 const char* HashEntryI = 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000197 uint32_t Offset;
198 uint32_t TableIdx;
199
200 do {
Ted Kremenek41a26602008-12-12 22:05:38 +0000201 // Read the token offset from the side-table.
Ted Kremenek268ee702008-12-12 18:34:08 +0000202 Offset = Read32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000203
204 // Read the target table index from the side-table.
Ted Kremenek268ee702008-12-12 18:34:08 +0000205 TableIdx = Read32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000206
207 // Compute the actual memory address of the '#' token data for this entry.
208 HashEntryI = TokBuf + Offset;
209
210 // Optmization: "Sibling jumping". #if...#else...#endif blocks can
211 // contain nested blocks. In the side-table we can jump over these
212 // nested blocks instead of doing a linear search if the next "sibling"
213 // entry is not at a location greater than LastHashTokPtr.
214 if (HashEntryI < LastHashTokPtr && TableIdx) {
215 // In the side-table we are still at an entry for a '#' token that
216 // is earlier than the last one we saw. Check if the location we would
217 // stride gets us closer.
218 const char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
219 assert(NextPPCondPtr >= CurPPCondPtr);
220 // Read where we should jump to.
221 uint32_t TmpOffset = Read32(NextPPCondPtr);
222 const char* HashEntryJ = TokBuf + TmpOffset;
223
224 if (HashEntryJ <= LastHashTokPtr) {
225 // Jump directly to the next entry in the side table.
226 HashEntryI = HashEntryJ;
227 Offset = TmpOffset;
228 TableIdx = Read32(NextPPCondPtr);
229 CurPPCondPtr = NextPPCondPtr;
230 }
231 }
Ted Kremenek268ee702008-12-12 18:34:08 +0000232 }
Ted Kremenek41a26602008-12-12 22:05:38 +0000233 while (HashEntryI < LastHashTokPtr);
234 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
Ted Kremenek268ee702008-12-12 18:34:08 +0000235 assert(TableIdx && "No jumping from #endifs.");
236
237 // Update our side-table iterator.
238 const char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
239 assert(NextPPCondPtr >= CurPPCondPtr);
240 CurPPCondPtr = NextPPCondPtr;
241
242 // Read where we should jump to.
Ted Kremenek41a26602008-12-12 22:05:38 +0000243 HashEntryI = TokBuf + Read32(NextPPCondPtr);
Ted Kremenek268ee702008-12-12 18:34:08 +0000244 uint32_t NextIdx = Read32(NextPPCondPtr);
245
246 // By construction NextIdx will be zero if this is a #endif. This is useful
247 // to know to obviate lexing another token.
248 bool isEndif = NextIdx == 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000249
250 // This case can occur when we see something like this:
251 //
252 // #if ...
253 // /* a comment or nothing */
254 // #elif
255 //
256 // If we are skipping the first #if block it will be the case that CurPtr
257 // already points 'elif'. Just return.
258
Ted Kremenek41a26602008-12-12 22:05:38 +0000259 if (CurPtr > HashEntryI) {
260 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
Ted Kremenek268ee702008-12-12 18:34:08 +0000261 // Did we reach a #endif? If so, go ahead and consume that token as well.
262 if (isEndif)
Ted Kremeneke5680f32008-12-23 01:30:52 +0000263 CurPtr += DISK_TOKEN_SIZE*2;
Ted Kremenek268ee702008-12-12 18:34:08 +0000264 else
Ted Kremenek41a26602008-12-12 22:05:38 +0000265 LastHashTokPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000266
267 return isEndif;
268 }
269
270 // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
Ted Kremenek41a26602008-12-12 22:05:38 +0000271 CurPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000272
273 // Update the location of the last observed '#'. This is useful if we
274 // are skipping multiple blocks.
275 LastHashTokPtr = CurPtr;
Ted Kremenek268ee702008-12-12 18:34:08 +0000276
Ted Kremeneke5680f32008-12-23 01:30:52 +0000277 // Skip the '#' token.
278 assert(((tok::TokenKind) (unsigned char) *CurPtr) == tok::hash);
279 CurPtr += DISK_TOKEN_SIZE;
280
Ted Kremenek268ee702008-12-12 18:34:08 +0000281 // Did we reach a #endif? If so, go ahead and consume that token as well.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000282 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
Ted Kremenek268ee702008-12-12 18:34:08 +0000283
284 return isEndif;
285}
286
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000287SourceLocation PTHLexer::getSourceLocation() {
288 // getLocation is not on the hot path. It is used to get the location of
289 // the next token when transitioning back to this lexer when done
290 // handling a #included file. Just read the necessary data from the token
291 // data buffer to construct the SourceLocation object.
292 // NOTE: This is a virtual function; hence it is defined out-of-line.
293 const char* p = CurPtr + (1 + 1 + 4);
294 uint32_t offset =
295 ((uint32_t) ((uint8_t) p[0]))
296 | (((uint32_t) ((uint8_t) p[1])) << 8)
297 | (((uint32_t) ((uint8_t) p[2])) << 16)
298 | (((uint32_t) ((uint8_t) p[3])) << 24);
299 return SourceLocation::getFileLoc(FileID, offset);
300}
301
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000302//===----------------------------------------------------------------------===//
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000303// Internal Data Structures for PTH file lookup and resolving identifiers.
304//===----------------------------------------------------------------------===//
305
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000306
307/// PTHFileLookup - This internal data structure is used by the PTHManager
308/// to map from FileEntry objects managed by FileManager to offsets within
309/// the PTH file.
310namespace {
311class VISIBILITY_HIDDEN PTHFileLookup {
312public:
313 class Val {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000314 uint32_t TokenOff;
315 uint32_t PPCondOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000316
317 public:
Ted Kremenekfb645b62008-12-11 23:36:38 +0000318 Val() : TokenOff(~0) {}
319 Val(uint32_t toff, uint32_t poff) : TokenOff(toff), PPCondOff(poff) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000320
Ted Kremenekfb645b62008-12-11 23:36:38 +0000321 uint32_t getTokenOffset() const {
322 assert(TokenOff != ~((uint32_t)0) && "PTHFileLookup entry initialized.");
323 return TokenOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000324 }
325
Ted Kremenekfb645b62008-12-11 23:36:38 +0000326 uint32_t gettPPCondOffset() const {
327 assert(TokenOff != ~((uint32_t)0) && "PTHFileLookup entry initialized.");
328 return PPCondOff;
329 }
330
331 bool isValid() const { return TokenOff != ~((uint32_t)0); }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000332 };
333
334private:
335 llvm::StringMap<Val> FileMap;
336
337public:
338 PTHFileLookup() {};
339
340 Val Lookup(const FileEntry* FE) {
341 const char* s = FE->getName();
342 unsigned size = strlen(s);
343 return FileMap.GetOrCreateValue(s, s+size).getValue();
344 }
345
346 void ReadTable(const char* D) {
347 uint32_t N = Read32(D); // Read the length of the table.
348
349 for ( ; N > 0; --N) { // The rest of the data is the table itself.
350 uint32_t len = Read32(D);
351 const char* s = D;
352 D += len;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000353 uint32_t TokenOff = Read32(D);
354 FileMap.GetOrCreateValue(s, s+len).getValue() = Val(TokenOff, Read32(D));
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000355 }
356 }
357};
358} // end anonymous namespace
359
360//===----------------------------------------------------------------------===//
361// PTHManager methods.
362//===----------------------------------------------------------------------===//
363
364PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
Ted Kremenekcf58e622008-12-10 19:40:23 +0000365 const char* idDataTable, IdentifierInfo** perIDCache,
Ted Kremenek6183e482008-12-03 01:16:39 +0000366 Preprocessor& pp)
367: Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
368 IdDataTable(idDataTable), ITable(pp.getIdentifierTable()), PP(pp) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000369
370PTHManager::~PTHManager() {
371 delete Buf;
372 delete (PTHFileLookup*) FileLookup;
Ted Kremenek0e50b6e2008-12-04 22:47:11 +0000373 free(PerIDCache);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000374}
375
376PTHManager* PTHManager::Create(const std::string& file, Preprocessor& PP) {
377
378 // Memory map the PTH file.
379 llvm::OwningPtr<llvm::MemoryBuffer>
380 File(llvm::MemoryBuffer::getFile(file.c_str()));
381
382 if (!File)
383 return 0;
384
385 // Get the buffer ranges and check if there are at least three 32-bit
386 // words at the end of the file.
387 const char* BufBeg = File->getBufferStart();
388 const char* BufEnd = File->getBufferEnd();
389
390 if(!(BufEnd > BufBeg + sizeof(uint32_t)*3)) {
391 assert(false && "Invalid PTH file.");
392 return 0; // FIXME: Proper error diagnostic?
393 }
394
395 // Compute the address of the index table at the end of the PTH file.
396 // This table contains the offset of the file lookup table, the
397 // persistent ID -> identifer data table.
398 const char* EndTable = BufEnd - sizeof(uint32_t)*3;
399
400 // Construct the file lookup table. This will be used for mapping from
401 // FileEntry*'s to cached tokens.
402 const char* FileTableOffset = EndTable + sizeof(uint32_t)*2;
403 const char* FileTable = BufBeg + Read32(FileTableOffset);
404
405 if (!(FileTable > BufBeg && FileTable < BufEnd)) {
406 assert(false && "Invalid PTH file.");
407 return 0; // FIXME: Proper error diagnostic?
408 }
409
410 llvm::OwningPtr<PTHFileLookup> FL(new PTHFileLookup());
411 FL->ReadTable(FileTable);
412
413 // Get the location of the table mapping from persistent ids to the
414 // data needed to reconstruct identifiers.
415 const char* IDTableOffset = EndTable + sizeof(uint32_t)*1;
416 const char* IData = BufBeg + Read32(IDTableOffset);
417 if (!(IData > BufBeg && IData < BufEnd)) {
418 assert(false && "Invalid PTH file.");
419 return 0; // FIXME: Proper error diagnostic?
420 }
421
Ted Kremenek6183e482008-12-03 01:16:39 +0000422 // Get the number of IdentifierInfos and pre-allocate the identifier cache.
423 uint32_t NumIds = Read32(IData);
424
425 // Pre-allocate the peristent ID -> IdentifierInfo* cache. We use calloc()
426 // so that we in the best case only zero out memory once when the OS returns
427 // us new pages.
428 IdentifierInfo** PerIDCache =
429 (IdentifierInfo**) calloc(NumIds, sizeof(*PerIDCache));
430
431 if (!PerIDCache) {
432 assert(false && "Could not allocate Persistent ID cache.");
433 return 0;
434 }
435
436 // Create the new lexer.
437 return new PTHManager(File.take(), FL.take(), IData, PerIDCache, PP);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000438}
439
440IdentifierInfo* PTHManager::ReadIdentifierInfo(const char*& D) {
441 // Read the persistent ID from the PTH file.
442 uint32_t persistentID = Read32(D);
443
444 // A persistent ID of '0' always maps to NULL.
445 if (!persistentID)
446 return 0;
447
448 // Adjust the persistent ID by subtracting '1' so that it can be used
449 // as an index within a table in the PTH file.
450 --persistentID;
451
452 // Check if the IdentifierInfo has already been resolved.
Ted Kremenekcf58e622008-12-10 19:40:23 +0000453 IdentifierInfo*& II = PerIDCache[persistentID];
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000454 if (II) return II;
455
456 // Look in the PTH file for the string data for the IdentifierInfo object.
457 const char* TableEntry = IdDataTable + sizeof(uint32_t) * persistentID;
458 const char* IDData = Buf->getBufferStart() + Read32(TableEntry);
459 assert(IDData < Buf->getBufferEnd());
460
461 // Read the length of the string.
462 uint32_t len = Read32(IDData);
463
464 // Get the IdentifierInfo* with the specified string.
465 II = &ITable.get(IDData, IDData+len);
466 return II;
467}
468
469PTHLexer* PTHManager::CreateLexer(unsigned FileID, const FileEntry* FE) {
470
471 if (!FE)
472 return 0;
473
474 // Lookup the FileEntry object in our file lookup data structure. It will
475 // return a variant that indicates whether or not there is an offset within
476 // the PTH file that contains cached tokens.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000477 PTHFileLookup::Val FileData = ((PTHFileLookup*) FileLookup)->Lookup(FE);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000478
Ted Kremenekfb645b62008-12-11 23:36:38 +0000479 if (!FileData.isValid()) // No tokens available.
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000480 return 0;
481
482 // Compute the offset of the token data within the buffer.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000483 const char* data = Buf->getBufferStart() + FileData.getTokenOffset();
Ted Kremenek268ee702008-12-12 18:34:08 +0000484
485 // Get the location of pp-conditional table.
486 const char* ppcond = Buf->getBufferStart() + FileData.gettPPCondOffset();
487 uint32_t len = Read32(ppcond);
488 if (len == 0) ppcond = 0;
489
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000490 assert(data < Buf->getBufferEnd());
Ted Kremenek268ee702008-12-12 18:34:08 +0000491 return new PTHLexer(PP, SourceLocation::getFileLoc(FileID, 0), data, ppcond,
492 *this);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000493}