blob: d8a1fe1db1f37dc93a42d1be5faa86a339352ec6 [file] [log] [blame]
Ted Kremenek85888962008-10-21 00:54:44 +00001//===--- CacheTokens.cpp - Caching of lexer tokens for PCH support --------===//
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 provides a possible implementation of PCH support for Clang that is
11// based on caching lexed tokens and identifiers.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang.h"
16#include "clang/Basic/FileManager.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/Basic/IdentifierTable.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Lex/Lexer.h"
21#include "clang/Lex/Preprocessor.h"
Ted Kremenekbe295332009-01-08 02:44:06 +000022#include "llvm/ADT/StringMap.h"
Ted Kremenek85888962008-10-21 00:54:44 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +000025#include "llvm/System/Path.h"
Ted Kremenekb978c662009-01-08 01:17:37 +000026#include "llvm/Support/Compiler.h"
Ted Kremenek72b1b152009-01-15 18:47:46 +000027#include "llvm/Support/Streams.h"
Ted Kremenek85888962008-10-21 00:54:44 +000028
29using namespace clang;
30
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +000031typedef uint32_t Offset;
32
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +000033static void Emit8(llvm::raw_ostream& Out, uint32_t V) {
34 Out << (unsigned char)(V);
35}
36
37static void Emit16(llvm::raw_ostream& Out, uint32_t V) {
38 Out << (unsigned char)(V);
39 Out << (unsigned char)(V >> 8);
40 assert((V >> 16) == 0);
41}
42
43static void Emit32(llvm::raw_ostream& Out, uint32_t V) {
44 Out << (unsigned char)(V);
45 Out << (unsigned char)(V >> 8);
46 Out << (unsigned char)(V >> 16);
47 Out << (unsigned char)(V >> 24);
48}
49
Ted Kremenekd8c02922009-02-10 22:16:22 +000050static void Pad(llvm::raw_fd_ostream& Out, unsigned A) {
51 Offset off = (Offset) Out.tell();
52 uint32_t n = ((uintptr_t)(off+A-1) & ~(uintptr_t)(A-1)) - off;
53 for ( ; n ; --n ) Emit8(Out, 0);
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +000054}
55
Ted Kremenek7e3a0042009-02-11 21:29:16 +000056// Bernstein hash function:
57// This is basically copy-and-paste from StringMap. This likely won't
58// stay here, which is why I didn't both to expose this function from
59// String Map.
60static unsigned BernsteinHash(const char* x) {
61 unsigned int R = 0;
62 for ( ; *x != '\0' ; ++x) R = R * 33 + *x;
63 return R + (R >> 5);
64}
65
Ted Kremenekf0e1f792009-02-10 01:14:45 +000066//===----------------------------------------------------------------------===//
67// On Disk Hashtable Logic. This will eventually get refactored and put
68// elsewhere.
69//===----------------------------------------------------------------------===//
70
71template<typename Info>
72class OnDiskChainedHashTableGenerator {
73 unsigned NumBuckets;
74 unsigned NumEntries;
75 llvm::BumpPtrAllocator BA;
76
77 class Item {
78 public:
Ted Kremenekd8c02922009-02-10 22:16:22 +000079 typename Info::key_type key;
80 typename Info::data_type data;
Ted Kremenekf0e1f792009-02-10 01:14:45 +000081 Item *next;
82 const uint32_t hash;
83
Ted Kremenekd8c02922009-02-10 22:16:22 +000084 Item(typename Info::key_type_ref k, typename Info::data_type_ref d)
85 : key(k), data(d), next(0), hash(Info::ComputeHash(k)) {}
Ted Kremenekf0e1f792009-02-10 01:14:45 +000086 };
87
88 class Bucket {
89 public:
90 Offset off;
91 Item* head;
92 unsigned length;
93
94 Bucket() {}
95 };
96
97 Bucket* Buckets;
98
99private:
Ted Kremenekd8c02922009-02-10 22:16:22 +0000100 void insert(Bucket* b, size_t size, Item* E) {
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000101 unsigned idx = E->hash & (size - 1);
102 Bucket& B = b[idx];
103 E->next = B.head;
104 ++B.length;
105 B.head = E;
106 }
107
108 void resize(size_t newsize) {
Ted Kremenekd8c02922009-02-10 22:16:22 +0000109 Bucket* newBuckets = (Bucket*) calloc(newsize, sizeof(Bucket));
110 // Populate newBuckets with the old entries.
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000111 for (unsigned i = 0; i < NumBuckets; ++i)
Ted Kremenekd8c02922009-02-10 22:16:22 +0000112 for (Item* E = Buckets[i].head; E ; ) {
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000113 Item* N = E->next;
Ted Kremenekd8c02922009-02-10 22:16:22 +0000114 E->next = 0;
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000115 insert(newBuckets, newsize, E);
116 E = N;
117 }
118
119 free(Buckets);
120 NumBuckets = newsize;
121 Buckets = newBuckets;
122 }
123
124public:
125
Ted Kremenekd8c02922009-02-10 22:16:22 +0000126 void insert(typename Info::key_type_ref key,
127 typename Info::data_type_ref data) {
128
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000129 ++NumEntries;
130 if (4*NumEntries >= 3*NumBuckets) resize(NumBuckets*2);
131 insert(Buckets, NumBuckets, new (BA.Allocate<Item>()) Item(key, data));
132 }
133
134 Offset Emit(llvm::raw_fd_ostream& out) {
135 // Emit the payload of the table.
136 for (unsigned i = 0; i < NumBuckets; ++i) {
137 Bucket& B = Buckets[i];
138 if (!B.head) continue;
139
140 // Store the offset for the data of this bucket.
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000141 B.off = out.tell();
142
Ted Kremenekd8c02922009-02-10 22:16:22 +0000143 // Write out the number of items in the bucket.
144 Emit16(out, B.length);
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000145
146 // Write out the entries in the bucket.
147 for (Item *I = B.head; I ; I = I->next) {
148 Emit32(out, I->hash);
Ted Kremenekd8c02922009-02-10 22:16:22 +0000149 const std::pair<unsigned, unsigned>& Len =
150 Info::EmitKeyDataLength(out, I->key, I->data);
151 Info::EmitKey(out, I->key, Len.first);
152 Info::EmitData(out, I->data, Len.second);
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000153 }
154 }
155
156 // Emit the hashtable itself.
157 Pad(out, 4);
158 Offset TableOff = out.tell();
Ted Kremenekd8c02922009-02-10 22:16:22 +0000159 Emit32(out, NumBuckets);
160 Emit32(out, NumEntries);
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000161 for (unsigned i = 0; i < NumBuckets; ++i) Emit32(out, Buckets[i].off);
162
163 return TableOff;
164 }
165
166 OnDiskChainedHashTableGenerator() {
167 NumEntries = 0;
Ted Kremenekd8c02922009-02-10 22:16:22 +0000168 NumBuckets = 64;
169 // Note that we do not need to run the constructors of the individual
170 // Bucket objects since 'calloc' returns bytes that are all 0.
171 Buckets = (Bucket*) calloc(NumBuckets, sizeof(Bucket));
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000172 }
173
174 ~OnDiskChainedHashTableGenerator() {
175 free(Buckets);
176 }
177};
178
179//===----------------------------------------------------------------------===//
180// PTH-specific stuff.
181//===----------------------------------------------------------------------===//
182
Ted Kremenekbe295332009-01-08 02:44:06 +0000183namespace {
184class VISIBILITY_HIDDEN PCHEntry {
185 Offset TokenData, PPCondData;
Ted Kremenekbe295332009-01-08 02:44:06 +0000186
187public:
188 PCHEntry() {}
189
Ted Kremenek277faca2009-01-27 00:01:05 +0000190 PCHEntry(Offset td, Offset ppcd)
191 : TokenData(td), PPCondData(ppcd) {}
Ted Kremenekbe295332009-01-08 02:44:06 +0000192
Ted Kremenek277faca2009-01-27 00:01:05 +0000193 Offset getTokenOffset() const { return TokenData; }
Ted Kremenekbe295332009-01-08 02:44:06 +0000194 Offset getPPCondTableOffset() const { return PPCondData; }
Ted Kremenek277faca2009-01-27 00:01:05 +0000195};
Ted Kremenekbe295332009-01-08 02:44:06 +0000196
Ted Kremenekd8c02922009-02-10 22:16:22 +0000197class VISIBILITY_HIDDEN FileEntryPCHEntryInfo {
198public:
199 typedef const FileEntry* key_type;
200 typedef key_type key_type_ref;
201
202 typedef PCHEntry data_type;
203 typedef const PCHEntry& data_type_ref;
204
205 static unsigned ComputeHash(const FileEntry* FE) {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000206 return BernsteinHash(FE->getName());
Ted Kremenekd8c02922009-02-10 22:16:22 +0000207 }
208
209 static std::pair<unsigned,unsigned>
210 EmitKeyDataLength(llvm::raw_ostream& Out, const FileEntry* FE,
211 const PCHEntry& E) {
212
213 unsigned n = strlen(FE->getName()) + 1;
214 ::Emit16(Out, n);
215 return std::make_pair(n, 8);
216 }
217
218 static void EmitKey(llvm::raw_ostream& Out, const FileEntry* FE, unsigned n) {
219 Out.write(FE->getName(), n);
220 }
221
222 static void EmitData(llvm::raw_ostream& Out, const PCHEntry& E, unsigned) {
223 ::Emit32(Out, E.getTokenOffset());
224 ::Emit32(Out, E.getPPCondTableOffset());
225 }
226};
227
Ted Kremenek277faca2009-01-27 00:01:05 +0000228class OffsetOpt {
229 bool valid;
230 Offset off;
231public:
232 OffsetOpt() : valid(false) {}
233 bool hasOffset() const { return valid; }
234 Offset getOffset() const { assert(valid); return off; }
235 void setOffset(Offset o) { off = o; valid = true; }
Ted Kremenekbe295332009-01-08 02:44:06 +0000236};
237} // end anonymous namespace
238
Ted Kremenekd8c02922009-02-10 22:16:22 +0000239typedef OnDiskChainedHashTableGenerator<FileEntryPCHEntryInfo> PCHMap;
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000240typedef llvm::DenseMap<const IdentifierInfo*,uint32_t> IDMap;
Ted Kremenek277faca2009-01-27 00:01:05 +0000241typedef llvm::StringMap<OffsetOpt, llvm::BumpPtrAllocator> CachedStrsTy;
Ted Kremenek85888962008-10-21 00:54:44 +0000242
Ted Kremenekb978c662009-01-08 01:17:37 +0000243namespace {
244class VISIBILITY_HIDDEN PTHWriter {
245 IDMap IM;
246 llvm::raw_fd_ostream& Out;
247 Preprocessor& PP;
248 uint32_t idcount;
249 PCHMap PM;
Ted Kremenekbe295332009-01-08 02:44:06 +0000250 CachedStrsTy CachedStrs;
Ted Kremenek277faca2009-01-27 00:01:05 +0000251 Offset CurStrOffset;
252 std::vector<llvm::StringMapEntry<OffsetOpt>*> StrEntries;
Ted Kremenek8f174e12008-12-23 02:52:12 +0000253
Ted Kremenekb978c662009-01-08 01:17:37 +0000254 //// Get the persistent id for the given IdentifierInfo*.
255 uint32_t ResolveID(const IdentifierInfo* II);
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000256
Ted Kremenekb978c662009-01-08 01:17:37 +0000257 /// Emit a token to the PTH file.
258 void EmitToken(const Token& T);
259
260 void Emit8(uint32_t V) {
261 Out << (unsigned char)(V);
262 }
263
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000264 void Emit16(uint32_t V) { ::Emit16(Out, V); }
Ted Kremenekb978c662009-01-08 01:17:37 +0000265
266 void Emit24(uint32_t V) {
267 Out << (unsigned char)(V);
268 Out << (unsigned char)(V >> 8);
269 Out << (unsigned char)(V >> 16);
270 assert((V >> 24) == 0);
271 }
272
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000273 void Emit32(uint32_t V) { ::Emit32(Out, V); }
274
Ted Kremenekb978c662009-01-08 01:17:37 +0000275 void EmitBuf(const char* I, const char* E) {
276 for ( ; I != E ; ++I) Out << *I;
277 }
278
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000279 /// EmitIdentifierTable - Emits two tables to the PTH file. The first is
280 /// a hashtable mapping from identifier strings to persistent IDs.
281 /// The second is a straight table mapping from persistent IDs to string data
282 /// (the keys of the first table).
Ted Kremenekf1de4642009-02-11 16:06:55 +0000283 std::pair<Offset, Offset> EmitIdentifierTable();
284
285 /// EmitFileTable - Emit a table mapping from file name strings to PTH
286 /// token data.
287 Offset EmitFileTable() { return PM.Emit(Out); }
288
Ted Kremenekbe295332009-01-08 02:44:06 +0000289 PCHEntry LexTokens(Lexer& L);
Ted Kremenek277faca2009-01-27 00:01:05 +0000290 Offset EmitCachedSpellings();
Ted Kremenekbe295332009-01-08 02:44:06 +0000291
Ted Kremenekb978c662009-01-08 01:17:37 +0000292public:
293 PTHWriter(llvm::raw_fd_ostream& out, Preprocessor& pp)
Ted Kremenek277faca2009-01-27 00:01:05 +0000294 : Out(out), PP(pp), idcount(0), CurStrOffset(0) {}
Ted Kremenekb978c662009-01-08 01:17:37 +0000295
296 void GeneratePTH();
297};
298} // end anonymous namespace
299
300uint32_t PTHWriter::ResolveID(const IdentifierInfo* II) {
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000301 // Null IdentifierInfo's map to the persistent ID 0.
302 if (!II)
303 return 0;
304
Ted Kremenek85888962008-10-21 00:54:44 +0000305 IDMap::iterator I = IM.find(II);
306
307 if (I == IM.end()) {
Ted Kremenekb978c662009-01-08 01:17:37 +0000308 IM[II] = ++idcount; // Pre-increment since '0' is reserved for NULL.
309 return idcount;
Ted Kremenek85888962008-10-21 00:54:44 +0000310 }
311
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000312 return I->second; // We've already added 1.
Ted Kremenek85888962008-10-21 00:54:44 +0000313}
314
Ted Kremenekb978c662009-01-08 01:17:37 +0000315void PTHWriter::EmitToken(const Token& T) {
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000316 Emit32(((uint32_t) T.getKind()) |
317 (((uint32_t) T.getFlags()) << 8) |
318 (((uint32_t) T.getLength()) << 16));
Ted Kremenek277faca2009-01-27 00:01:05 +0000319
Chris Lattner47246be2009-01-26 19:29:26 +0000320 // Literals (strings, numbers, characters) get cached spellings.
321 if (T.isLiteral()) {
322 // FIXME: This uses the slow getSpelling(). Perhaps we do better
323 // in the future? This only slows down PTH generation.
324 const std::string &spelling = PP.getSpelling(T);
325 const char* s = spelling.c_str();
326
327 // Get the string entry.
Ted Kremenek277faca2009-01-27 00:01:05 +0000328 llvm::StringMapEntry<OffsetOpt> *E =
329 &CachedStrs.GetOrCreateValue(s, s+spelling.size());
330
331 if (!E->getValue().hasOffset()) {
332 E->getValue().setOffset(CurStrOffset);
333 StrEntries.push_back(E);
334 CurStrOffset += spelling.size() + 1;
335 }
336
337 Emit32(E->getValue().getOffset());
Ted Kremenekb978c662009-01-08 01:17:37 +0000338 }
Ted Kremenek277faca2009-01-27 00:01:05 +0000339 else
340 Emit32(ResolveID(T.getIdentifierInfo()));
341
Chris Lattner52c29082009-01-27 06:27:13 +0000342 Emit32(PP.getSourceManager().getFileOffset(T.getLocation()));
Ted Kremenek85888962008-10-21 00:54:44 +0000343}
344
Ted Kremenekbe295332009-01-08 02:44:06 +0000345PCHEntry PTHWriter::LexTokens(Lexer& L) {
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000346 // Pad 0's so that we emit tokens to a 4-byte alignment.
347 // This speed up reading them back in.
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000348 Pad(Out, 4);
349 Offset off = (Offset) Out.tell();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000350
351 // Keep track of matching '#if' ... '#endif'.
352 typedef std::vector<std::pair<Offset, unsigned> > PPCondTable;
353 PPCondTable PPCond;
Ted Kremenekdad7b342008-12-12 18:31:09 +0000354 std::vector<unsigned> PPStartCond;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000355 bool ParsingPreprocessorDirective = false;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000356 Token Tok;
357
358 do {
359 L.LexFromRawLexer(Tok);
Ted Kremenek726080d2009-02-10 22:43:16 +0000360 NextToken:
361
Ted Kremeneke5680f32008-12-23 01:30:52 +0000362 if ((Tok.isAtStartOfLine() || Tok.is(tok::eof)) &&
363 ParsingPreprocessorDirective) {
364 // Insert an eom token into the token cache. It has the same
365 // position as the next token that is not on the same line as the
366 // preprocessor directive. Observe that we continue processing
367 // 'Tok' when we exit this branch.
368 Token Tmp = Tok;
369 Tmp.setKind(tok::eom);
370 Tmp.clearFlag(Token::StartOfLine);
371 Tmp.setIdentifierInfo(0);
Ted Kremenekb978c662009-01-08 01:17:37 +0000372 EmitToken(Tmp);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000373 ParsingPreprocessorDirective = false;
374 }
375
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000376 if (Tok.is(tok::identifier)) {
377 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000378 EmitToken(Tok);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000379 continue;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000380 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000381
382 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000383 // Special processing for #include. Store the '#' token and lex
384 // the next token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000385 assert(!ParsingPreprocessorDirective);
Ted Kremenekfb645b62008-12-11 23:36:38 +0000386 Offset HashOff = (Offset) Out.tell();
Ted Kremenekb978c662009-01-08 01:17:37 +0000387 EmitToken(Tok);
Ted Kremenekdad7b342008-12-12 18:31:09 +0000388
389 // Get the next token.
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000390 L.LexFromRawLexer(Tok);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000391
392 assert(!Tok.isAtStartOfLine());
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000393
394 // Did we see 'include'/'import'/'include_next'?
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000395 if (!Tok.is(tok::identifier)) {
396 EmitToken(Tok);
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000397 continue;
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000398 }
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000399
400 IdentifierInfo* II = PP.LookUpIdentifierInfo(Tok);
401 Tok.setIdentifierInfo(II);
402 tok::PPKeywordKind K = II->getPPKeywordID();
403
Ted Kremeneke5680f32008-12-23 01:30:52 +0000404 assert(K != tok::pp_not_keyword);
405 ParsingPreprocessorDirective = true;
406
407 switch (K) {
408 default:
409 break;
410 case tok::pp_include:
411 case tok::pp_import:
412 case tok::pp_include_next: {
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000413 // Save the 'include' token.
Ted Kremenekb978c662009-01-08 01:17:37 +0000414 EmitToken(Tok);
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000415 // Lex the next token as an include string.
416 L.setParsingPreprocessorDirective(true);
417 L.LexIncludeFilename(Tok);
418 L.setParsingPreprocessorDirective(false);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000419 assert(!Tok.isAtStartOfLine());
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000420 if (Tok.is(tok::identifier))
421 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000422
423 break;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000424 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000425 case tok::pp_if:
426 case tok::pp_ifdef:
427 case tok::pp_ifndef: {
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000428 // Add an entry for '#if' and friends. We initially set the target
429 // index to 0. This will get backpatched when we hit #endif.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000430 PPStartCond.push_back(PPCond.size());
Ted Kremenekdad7b342008-12-12 18:31:09 +0000431 PPCond.push_back(std::make_pair(HashOff, 0U));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000432 break;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000433 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000434 case tok::pp_endif: {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000435 // Add an entry for '#endif'. We set the target table index to itself.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000436 // This will later be set to zero when emitting to the PTH file. We
437 // use 0 for uninitialized indices because that is easier to debug.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000438 unsigned index = PPCond.size();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000439 // Backpatch the opening '#if' entry.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000440 assert(!PPStartCond.empty());
441 assert(PPCond.size() > PPStartCond.back());
Ted Kremenekfb645b62008-12-11 23:36:38 +0000442 assert(PPCond[PPStartCond.back()].second == 0);
443 PPCond[PPStartCond.back()].second = index;
444 PPStartCond.pop_back();
Ted Kremenekdad7b342008-12-12 18:31:09 +0000445 // Add the new entry to PPCond.
446 PPCond.push_back(std::make_pair(HashOff, index));
Ted Kremenek726080d2009-02-10 22:43:16 +0000447 EmitToken(Tok);
448
449 // Some files have gibberish on the same line as '#endif'.
450 // Discard these tokens.
451 do L.LexFromRawLexer(Tok); while (!Tok.is(tok::eof) &&
452 !Tok.isAtStartOfLine());
453 // We have the next token in hand.
454 // Don't immediately lex the next one.
455 goto NextToken;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000456 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000457 case tok::pp_elif:
458 case tok::pp_else: {
459 // Add an entry for #elif or #else.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000460 // This serves as both a closing and opening of a conditional block.
461 // This means that its entry will get backpatched later.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000462 unsigned index = PPCond.size();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000463 // Backpatch the previous '#if' entry.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000464 assert(!PPStartCond.empty());
465 assert(PPCond.size() > PPStartCond.back());
Ted Kremenekfb645b62008-12-11 23:36:38 +0000466 assert(PPCond[PPStartCond.back()].second == 0);
467 PPCond[PPStartCond.back()].second = index;
468 PPStartCond.pop_back();
469 // Now add '#elif' as a new block opening.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000470 PPCond.push_back(std::make_pair(HashOff, 0U));
471 PPStartCond.push_back(index);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000472 break;
473 }
Ted Kremenekfb645b62008-12-11 23:36:38 +0000474 }
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000475 }
476
477 EmitToken(Tok);
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000478 }
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000479 while (Tok.isNot(tok::eof));
Ted Kremenekb978c662009-01-08 01:17:37 +0000480
Ted Kremenekdad7b342008-12-12 18:31:09 +0000481 assert(PPStartCond.empty() && "Error: imblanced preprocessor conditionals.");
Ted Kremenekb978c662009-01-08 01:17:37 +0000482
Ted Kremenekfb645b62008-12-11 23:36:38 +0000483 // Next write out PPCond.
484 Offset PPCondOff = (Offset) Out.tell();
Ted Kremenekdad7b342008-12-12 18:31:09 +0000485
486 // Write out the size of PPCond so that clients can identifer empty tables.
Ted Kremenekb978c662009-01-08 01:17:37 +0000487 Emit32(PPCond.size());
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000488
Ted Kremenekdad7b342008-12-12 18:31:09 +0000489 for (unsigned i = 0, e = PPCond.size(); i!=e; ++i) {
Ted Kremenekb978c662009-01-08 01:17:37 +0000490 Emit32(PPCond[i].first - off);
Ted Kremenekdad7b342008-12-12 18:31:09 +0000491 uint32_t x = PPCond[i].second;
492 assert(x != 0 && "PPCond entry not backpatched.");
493 // Emit zero for #endifs. This allows us to do checking when
494 // we read the PTH file back in.
Ted Kremenekb978c662009-01-08 01:17:37 +0000495 Emit32(x == i ? 0 : x);
Ted Kremenekfb645b62008-12-11 23:36:38 +0000496 }
497
Ted Kremenek277faca2009-01-27 00:01:05 +0000498 return PCHEntry(off, PPCondOff);
Ted Kremenekbe295332009-01-08 02:44:06 +0000499}
500
Ted Kremenek277faca2009-01-27 00:01:05 +0000501Offset PTHWriter::EmitCachedSpellings() {
502 // Write each cached strings to the PTH file.
503 Offset SpellingsOff = Out.tell();
504
505 for (std::vector<llvm::StringMapEntry<OffsetOpt>*>::iterator
506 I = StrEntries.begin(), E = StrEntries.end(); I!=E; ++I) {
Ted Kremenekbe295332009-01-08 02:44:06 +0000507
Ted Kremenek277faca2009-01-27 00:01:05 +0000508 const char* data = (*I)->getKeyData();
509 EmitBuf(data, data + (*I)->getKeyLength());
510 Emit8('\0');
Ted Kremenekbe295332009-01-08 02:44:06 +0000511 }
512
Ted Kremenek277faca2009-01-27 00:01:05 +0000513 return SpellingsOff;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000514}
Ted Kremenek85888962008-10-21 00:54:44 +0000515
Ted Kremenekb978c662009-01-08 01:17:37 +0000516void PTHWriter::GeneratePTH() {
Ted Kremeneke1b64982009-01-26 21:43:14 +0000517 // Generate the prologue.
518 Out << "cfe-pth";
Ted Kremenek67d15052009-01-26 21:50:21 +0000519 Emit32(PTHManager::Version);
Ted Kremeneke1b64982009-01-26 21:43:14 +0000520 Offset JumpOffset = Out.tell();
521 Emit32(0);
522
Ted Kremenek85888962008-10-21 00:54:44 +0000523 // Iterate over all the files in SourceManager. Create a lexer
524 // for each file and cache the tokens.
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000525 SourceManager &SM = PP.getSourceManager();
526 const LangOptions &LOpts = PP.getLangOptions();
Ted Kremenek85888962008-10-21 00:54:44 +0000527
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000528 for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
529 E = SM.fileinfo_end(); I != E; ++I) {
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000530 const SrcMgr::ContentCache &C = *I->second;
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000531 const FileEntry *FE = C.Entry;
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000532
533 // FIXME: Handle files with non-absolute paths.
534 llvm::sys::Path P(FE->getName());
535 if (!P.isAbsolute())
536 continue;
Ted Kremenek85888962008-10-21 00:54:44 +0000537
Ted Kremenekd8c02922009-02-10 22:16:22 +0000538 // assert(!PM.count(FE) && "fileinfo's are not uniqued on FileEntry?");
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000539
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000540 const llvm::MemoryBuffer *B = C.getBuffer();
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000541 if (!B) continue;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000542
Chris Lattner2b2453a2009-01-17 06:22:33 +0000543 FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
Chris Lattner025c3a62009-01-17 07:35:14 +0000544 Lexer L(FID, SM, LOpts);
Ted Kremenekd8c02922009-02-10 22:16:22 +0000545 PM.insert(FE, LexTokens(L));
Daniel Dunbar31309ab2008-11-26 02:18:33 +0000546 }
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000547
548 // Write out the identifier table.
Ted Kremenekf1de4642009-02-11 16:06:55 +0000549 const std::pair<Offset,Offset>& IdTableOff = EmitIdentifierTable();
Ted Kremenek85888962008-10-21 00:54:44 +0000550
Ted Kremenekbe295332009-01-08 02:44:06 +0000551 // Write out the cached strings table.
Ted Kremenek277faca2009-01-27 00:01:05 +0000552 Offset SpellingOff = EmitCachedSpellings();
Ted Kremenekbe295332009-01-08 02:44:06 +0000553
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000554 // Write out the file table.
Ted Kremenekb978c662009-01-08 01:17:37 +0000555 Offset FileTableOff = EmitFileTable();
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000556
557 // Finally, write out the offset table at the end.
Ted Kremeneke1b64982009-01-26 21:43:14 +0000558 Offset JumpTargetOffset = Out.tell();
Ted Kremenekb978c662009-01-08 01:17:37 +0000559 Emit32(IdTableOff.first);
Ted Kremenekf1de4642009-02-11 16:06:55 +0000560 Emit32(IdTableOff.second);
Ted Kremenekb978c662009-01-08 01:17:37 +0000561 Emit32(FileTableOff);
Ted Kremenek277faca2009-01-27 00:01:05 +0000562 Emit32(SpellingOff);
Ted Kremeneke1b64982009-01-26 21:43:14 +0000563
564 // Now write the offset in the prologue.
565 Out.seek(JumpOffset);
566 Emit32(JumpTargetOffset);
Ted Kremenekb978c662009-01-08 01:17:37 +0000567}
568
569void clang::CacheTokens(Preprocessor& PP, const std::string& OutFile) {
570 // Lex through the entire file. This will populate SourceManager with
571 // all of the header information.
572 Token Tok;
573 PP.EnterMainSourceFile();
574 do { PP.Lex(Tok); } while (Tok.isNot(tok::eof));
575
576 // Open up the PTH file.
577 std::string ErrMsg;
578 llvm::raw_fd_ostream Out(OutFile.c_str(), true, ErrMsg);
579
580 if (!ErrMsg.empty()) {
581 llvm::errs() << "PTH error: " << ErrMsg << "\n";
582 return;
583 }
584
585 // Create the PTHWriter and generate the PTH file.
586 PTHWriter PW(Out, PP);
587 PW.GeneratePTH();
Ted Kremenek85888962008-10-21 00:54:44 +0000588}
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000589
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000590//===----------------------------------------------------------------------===//
591
592namespace {
593class VISIBILITY_HIDDEN PCHIdKey {
594public:
595 const IdentifierInfo* II;
596 uint32_t FileOffset;
597};
598
599class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
600public:
601 typedef PCHIdKey* key_type;
602 typedef key_type key_type_ref;
603
604 typedef uint32_t data_type;
605 typedef data_type data_type_ref;
606
607 static unsigned ComputeHash(PCHIdKey* key) {
608 return BernsteinHash(key->II->getName());
609 }
610
611 static std::pair<unsigned,unsigned>
612 EmitKeyDataLength(llvm::raw_ostream& Out, const PCHIdKey* key, uint32_t) {
613 unsigned n = strlen(key->II->getName()) + 1;
614 ::Emit16(Out, n);
615 return std::make_pair(n, sizeof(uint32_t));
616 }
617
618 static void EmitKey(llvm::raw_fd_ostream& Out, PCHIdKey* key, unsigned n) {
619 // Record the location of the key data. This is used when generating
620 // the mapping from persistent IDs to strings.
621 key->FileOffset = Out.tell();
622 Out.write(key->II->getName(), n);
623 }
624
625 static void EmitData(llvm::raw_ostream& Out, uint32_t pID, unsigned) {
626 ::Emit32(Out, pID);
627 }
628};
629} // end anonymous namespace
630
631/// EmitIdentifierTable - Emits two tables to the PTH file. The first is
632/// a hashtable mapping from identifier strings to persistent IDs. The second
633/// is a straight table mapping from persistent IDs to string data (the
634/// keys of the first table).
635///
636std::pair<Offset,Offset> PTHWriter::EmitIdentifierTable() {
637 // Build two maps:
638 // (1) an inverse map from persistent IDs -> (IdentifierInfo*,Offset)
639 // (2) a map from (IdentifierInfo*, Offset)* -> persistent IDs
640
641 // Note that we use 'calloc', so all the bytes are 0.
642 PCHIdKey* IIDMap = (PCHIdKey*) calloc(idcount, sizeof(PCHIdKey));
643
644 // Create the hashtable.
645 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> IIOffMap;
646
647 // Generate mapping from persistent IDs -> IdentifierInfo*.
648 for (IDMap::iterator I=IM.begin(), E=IM.end(); I!=E; ++I) {
649 // Decrement by 1 because we are using a vector for the lookup and
650 // 0 is reserved for NULL.
651 assert(I->second > 0);
652 assert(I->second-1 < idcount);
653 unsigned idx = I->second-1;
654
655 // Store the mapping from persistent ID to IdentifierInfo*
656 IIDMap[idx].II = I->first;
657
658 // Store the reverse mapping in a hashtable.
659 IIOffMap.insert(&IIDMap[idx], I->second);
660 }
661
662 // Write out the inverse map first. This causes the PCIDKey entries to
663 // record PTH file offsets for the string data. This is used to write
664 // the second table.
665 Offset StringTableOffset = IIOffMap.Emit(Out);
666
667 // Now emit the table mapping from persistent IDs to PTH file offsets.
668 Offset IDOff = Out.tell();
669 Emit32(idcount); // Emit the number of identifiers.
670 for (unsigned i = 0 ; i < idcount; ++i) Emit32(IIDMap[i].FileOffset);
671
672 // Finally, release the inverse map.
673 free(IIDMap);
674
675 return std::make_pair(IDOff, StringTableOffset);
676}
677
678