blob: 0cd9315f60c89d673cdb005cdbff8ab2e0181b90 [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
50static void Pad(llvm::raw_fd_ostream& Out, unsigned Alignment) {
51 Offset off = (Offset) Out.tell();
52 for (unsigned Pad = off % Alignment ; Pad != 0 ; --Pad, ++off) Emit8(Out, 0);
53}
54
Ted Kremenekf0e1f792009-02-10 01:14:45 +000055//===----------------------------------------------------------------------===//
56// On Disk Hashtable Logic. This will eventually get refactored and put
57// elsewhere.
58//===----------------------------------------------------------------------===//
59
60template<typename Info>
61class OnDiskChainedHashTableGenerator {
62 unsigned NumBuckets;
63 unsigned NumEntries;
64 llvm::BumpPtrAllocator BA;
65
66 class Item {
67 public:
68 typename Info::KeyT key;
69 typename Info::DataT data;
70 Item *next;
71 const uint32_t hash;
72
73 Item(typename Info::KeyT_ref k, typename Info::DataT_ref d)
74 : key(k), data(d), next(0), hash(Info::getHash(k)) {}
75 };
76
77 class Bucket {
78 public:
79 Offset off;
80 Item* head;
81 unsigned length;
82
83 Bucket() {}
84 };
85
86 Bucket* Buckets;
87
88private:
89 void insert(Item** b, size_t size, Item* E) {
90 unsigned idx = E->hash & (size - 1);
91 Bucket& B = b[idx];
92 E->next = B.head;
93 ++B.length;
94 B.head = E;
95 }
96
97 void resize(size_t newsize) {
98 Bucket* newBuckets = calloc(newsize, sizeof(Bucket));
99
100 for (unsigned i = 0; i < NumBuckets; ++i)
101 for (Item* E = Buckets[i]; E ; ) {
102 Item* N = E->next;
103 E->Next = 0;
104 insert(newBuckets, newsize, E);
105 E = N;
106 }
107
108 free(Buckets);
109 NumBuckets = newsize;
110 Buckets = newBuckets;
111 }
112
113public:
114
115 void insert(typename Info::Key_ref key, typename Info::DataT_ref data) {
116 ++NumEntries;
117 if (4*NumEntries >= 3*NumBuckets) resize(NumBuckets*2);
118 insert(Buckets, NumBuckets, new (BA.Allocate<Item>()) Item(key, data));
119 }
120
121 Offset Emit(llvm::raw_fd_ostream& out) {
122 // Emit the payload of the table.
123 for (unsigned i = 0; i < NumBuckets; ++i) {
124 Bucket& B = Buckets[i];
125 if (!B.head) continue;
126
127 // Store the offset for the data of this bucket.
128 Pad(out, 4); // 4-byte alignment.
129 B.off = out.tell();
130
131 // Write out the number of items in the bucket. We just write out
132 // 4 bytes to keep things 4-byte aligned.
133 Emit32(out, B.length);
134
135 // Write out the entries in the bucket.
136 for (Item *I = B.head; I ; I = I->next) {
137 Emit32(out, I->hash);
138 Info::EmitKey(out, I->key);
139 Info::EmitData(out, I->data);
140 }
141 }
142
143 // Emit the hashtable itself.
144 Pad(out, 4);
145 Offset TableOff = out.tell();
146 Emit32(out, NumBuckets);
147 for (unsigned i = 0; i < NumBuckets; ++i) Emit32(out, Buckets[i].off);
148
149 return TableOff;
150 }
151
152 OnDiskChainedHashTableGenerator() {
153 NumEntries = 0;
154 NumBuckets = 64;
155 Buckets = calloc(NumBuckets, sizeof(Bucket));
156 }
157
158 ~OnDiskChainedHashTableGenerator() {
159 free(Buckets);
160 }
161};
162
163//===----------------------------------------------------------------------===//
164// PTH-specific stuff.
165//===----------------------------------------------------------------------===//
166
Ted Kremenekbe295332009-01-08 02:44:06 +0000167namespace {
168class VISIBILITY_HIDDEN PCHEntry {
169 Offset TokenData, PPCondData;
Ted Kremenekbe295332009-01-08 02:44:06 +0000170
171public:
172 PCHEntry() {}
173
Ted Kremenek277faca2009-01-27 00:01:05 +0000174 PCHEntry(Offset td, Offset ppcd)
175 : TokenData(td), PPCondData(ppcd) {}
Ted Kremenekbe295332009-01-08 02:44:06 +0000176
Ted Kremenek277faca2009-01-27 00:01:05 +0000177 Offset getTokenOffset() const { return TokenData; }
Ted Kremenekbe295332009-01-08 02:44:06 +0000178 Offset getPPCondTableOffset() const { return PPCondData; }
Ted Kremenek277faca2009-01-27 00:01:05 +0000179};
Ted Kremenekbe295332009-01-08 02:44:06 +0000180
Ted Kremenek277faca2009-01-27 00:01:05 +0000181class OffsetOpt {
182 bool valid;
183 Offset off;
184public:
185 OffsetOpt() : valid(false) {}
186 bool hasOffset() const { return valid; }
187 Offset getOffset() const { assert(valid); return off; }
188 void setOffset(Offset o) { off = o; valid = true; }
Ted Kremenekbe295332009-01-08 02:44:06 +0000189};
190} // end anonymous namespace
191
192typedef llvm::DenseMap<const FileEntry*, PCHEntry> PCHMap;
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000193typedef llvm::DenseMap<const IdentifierInfo*,uint32_t> IDMap;
Ted Kremenek277faca2009-01-27 00:01:05 +0000194typedef llvm::StringMap<OffsetOpt, llvm::BumpPtrAllocator> CachedStrsTy;
Ted Kremenek85888962008-10-21 00:54:44 +0000195
Ted Kremenekb978c662009-01-08 01:17:37 +0000196namespace {
197class VISIBILITY_HIDDEN PTHWriter {
198 IDMap IM;
199 llvm::raw_fd_ostream& Out;
200 Preprocessor& PP;
201 uint32_t idcount;
202 PCHMap PM;
Ted Kremenekbe295332009-01-08 02:44:06 +0000203 CachedStrsTy CachedStrs;
Ted Kremenek277faca2009-01-27 00:01:05 +0000204 Offset CurStrOffset;
205 std::vector<llvm::StringMapEntry<OffsetOpt>*> StrEntries;
Ted Kremenek8f174e12008-12-23 02:52:12 +0000206
Ted Kremenekb978c662009-01-08 01:17:37 +0000207 //// Get the persistent id for the given IdentifierInfo*.
208 uint32_t ResolveID(const IdentifierInfo* II);
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000209
Ted Kremenekb978c662009-01-08 01:17:37 +0000210 /// Emit a token to the PTH file.
211 void EmitToken(const Token& T);
212
213 void Emit8(uint32_t V) {
214 Out << (unsigned char)(V);
215 }
216
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000217 void Emit16(uint32_t V) { ::Emit16(Out, V); }
Ted Kremenekb978c662009-01-08 01:17:37 +0000218
219 void Emit24(uint32_t V) {
220 Out << (unsigned char)(V);
221 Out << (unsigned char)(V >> 8);
222 Out << (unsigned char)(V >> 16);
223 assert((V >> 24) == 0);
224 }
225
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000226 void Emit32(uint32_t V) { ::Emit32(Out, V); }
227
Ted Kremenekb978c662009-01-08 01:17:37 +0000228 void EmitBuf(const char* I, const char* E) {
229 for ( ; I != E ; ++I) Out << *I;
230 }
231
Ted Kremenek293b4af2009-01-15 01:26:25 +0000232 std::pair<Offset,std::pair<Offset, Offset> > EmitIdentifierTable();
Ted Kremenekb978c662009-01-08 01:17:37 +0000233 Offset EmitFileTable();
Ted Kremenekbe295332009-01-08 02:44:06 +0000234 PCHEntry LexTokens(Lexer& L);
Ted Kremenek277faca2009-01-27 00:01:05 +0000235 Offset EmitCachedSpellings();
Ted Kremenekbe295332009-01-08 02:44:06 +0000236
Ted Kremenekb978c662009-01-08 01:17:37 +0000237public:
238 PTHWriter(llvm::raw_fd_ostream& out, Preprocessor& pp)
Ted Kremenek277faca2009-01-27 00:01:05 +0000239 : Out(out), PP(pp), idcount(0), CurStrOffset(0) {}
Ted Kremenekb978c662009-01-08 01:17:37 +0000240
241 void GeneratePTH();
242};
243} // end anonymous namespace
244
245uint32_t PTHWriter::ResolveID(const IdentifierInfo* II) {
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000246 // Null IdentifierInfo's map to the persistent ID 0.
247 if (!II)
248 return 0;
249
Ted Kremenek85888962008-10-21 00:54:44 +0000250 IDMap::iterator I = IM.find(II);
251
252 if (I == IM.end()) {
Ted Kremenekb978c662009-01-08 01:17:37 +0000253 IM[II] = ++idcount; // Pre-increment since '0' is reserved for NULL.
254 return idcount;
Ted Kremenek85888962008-10-21 00:54:44 +0000255 }
256
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000257 return I->second; // We've already added 1.
Ted Kremenek85888962008-10-21 00:54:44 +0000258}
259
Ted Kremenekb978c662009-01-08 01:17:37 +0000260void PTHWriter::EmitToken(const Token& T) {
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000261 Emit32(((uint32_t) T.getKind()) |
262 (((uint32_t) T.getFlags()) << 8) |
263 (((uint32_t) T.getLength()) << 16));
Ted Kremenek277faca2009-01-27 00:01:05 +0000264
Chris Lattner47246be2009-01-26 19:29:26 +0000265 // Literals (strings, numbers, characters) get cached spellings.
266 if (T.isLiteral()) {
267 // FIXME: This uses the slow getSpelling(). Perhaps we do better
268 // in the future? This only slows down PTH generation.
269 const std::string &spelling = PP.getSpelling(T);
270 const char* s = spelling.c_str();
271
272 // Get the string entry.
Ted Kremenek277faca2009-01-27 00:01:05 +0000273 llvm::StringMapEntry<OffsetOpt> *E =
274 &CachedStrs.GetOrCreateValue(s, s+spelling.size());
275
276 if (!E->getValue().hasOffset()) {
277 E->getValue().setOffset(CurStrOffset);
278 StrEntries.push_back(E);
279 CurStrOffset += spelling.size() + 1;
280 }
281
282 Emit32(E->getValue().getOffset());
Ted Kremenekb978c662009-01-08 01:17:37 +0000283 }
Ted Kremenek277faca2009-01-27 00:01:05 +0000284 else
285 Emit32(ResolveID(T.getIdentifierInfo()));
286
Chris Lattner52c29082009-01-27 06:27:13 +0000287 Emit32(PP.getSourceManager().getFileOffset(T.getLocation()));
Ted Kremenek85888962008-10-21 00:54:44 +0000288}
289
Ted Kremenekb978c662009-01-08 01:17:37 +0000290namespace {
291struct VISIBILITY_HIDDEN IDData {
Ted Kremenekfa59aad2008-11-26 23:58:26 +0000292 const IdentifierInfo* II;
293 uint32_t FileOffset;
Ted Kremenek293b4af2009-01-15 01:26:25 +0000294};
295
296class VISIBILITY_HIDDEN CompareIDDataIndex {
297 IDData* Table;
298public:
299 CompareIDDataIndex(IDData* table) : Table(table) {}
300
301 bool operator()(unsigned i, unsigned j) const {
Ted Kremenek72b1b152009-01-15 18:47:46 +0000302 const IdentifierInfo* II_i = Table[i].II;
303 const IdentifierInfo* II_j = Table[j].II;
304
305 unsigned i_len = II_i->getLength();
306 unsigned j_len = II_j->getLength();
307
308 if (i_len > j_len)
309 return false;
310
311 if (i_len < j_len)
312 return true;
313
314 // Otherwise, compare the strings themselves!
315 return strncmp(II_i->getName(), II_j->getName(), i_len) < 0;
Ted Kremenek293b4af2009-01-15 01:26:25 +0000316 }
Ted Kremenekfa59aad2008-11-26 23:58:26 +0000317};
Ted Kremenekb978c662009-01-08 01:17:37 +0000318}
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000319
Ted Kremenek293b4af2009-01-15 01:26:25 +0000320std::pair<Offset,std::pair<Offset,Offset> >
321PTHWriter::EmitIdentifierTable() {
322 llvm::BumpPtrAllocator Alloc;
Ted Kremenekfa59aad2008-11-26 23:58:26 +0000323
324 // Build an inverse map from persistent IDs -> IdentifierInfo*.
Ted Kremenek293b4af2009-01-15 01:26:25 +0000325 IDData* IIDMap = Alloc.Allocate<IDData>(idcount);
Ted Kremenek85888962008-10-21 00:54:44 +0000326
Ted Kremenekfa59aad2008-11-26 23:58:26 +0000327 // Generate mapping from persistent IDs -> IdentifierInfo*.
Ted Kremenekb978c662009-01-08 01:17:37 +0000328 for (IDMap::iterator I=IM.begin(), E=IM.end(); I!=E; ++I) {
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000329 // Decrement by 1 because we are using a vector for the lookup and
330 // 0 is reserved for NULL.
331 assert(I->second > 0);
Ted Kremenek293b4af2009-01-15 01:26:25 +0000332 assert(I->second-1 < idcount);
333 unsigned idx = I->second-1;
334 IIDMap[idx].II = I->first;
335 }
Ted Kremenekfa59aad2008-11-26 23:58:26 +0000336
Ted Kremenek293b4af2009-01-15 01:26:25 +0000337 // We want to write out the strings in lexical order to support binary
338 // search of strings to identifiers. Create such a table.
339 unsigned *LexicalOrder = Alloc.Allocate<unsigned>(idcount);
340 for (unsigned i = 0; i < idcount ; ++i ) LexicalOrder[i] = i;
341 std::sort(LexicalOrder, LexicalOrder+idcount, CompareIDDataIndex(IIDMap));
342
343 // Write out the lexically-sorted table of persistent ids.
344 Offset LexicalOff = Out.tell();
345 for (unsigned i = 0; i < idcount ; ++i) Emit32(LexicalOrder[i]);
346
347 // Write out the string data itself.
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000348 Offset DataOff = Out.tell();
Ted Kremenek6183e482008-12-03 01:16:39 +0000349
Ted Kremenek293b4af2009-01-15 01:26:25 +0000350 for (unsigned i = 0; i < idcount; ++i) {
351 IDData& d = IIDMap[i];
352 d.FileOffset = Out.tell(); // Record the location for this data.
353 unsigned len = d.II->getLength(); // Write out the string length.
Ted Kremenekb978c662009-01-08 01:17:37 +0000354 Emit32(len);
Ted Kremenek293b4af2009-01-15 01:26:25 +0000355 const char* buf = d.II->getName(); // Write out the string data.
Ted Kremenek72b1b152009-01-15 18:47:46 +0000356 EmitBuf(buf, buf+len);
357 // Emit a null character for those clients expecting that IdentifierInfo
358 // strings are null terminated.
359 Emit8('\0');
Ted Kremenek85888962008-10-21 00:54:44 +0000360 }
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000361
Ted Kremenekfa59aad2008-11-26 23:58:26 +0000362 // Now emit the table mapping from persistent IDs to PTH file offsets.
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000363 Offset IDOff = Out.tell();
Ted Kremenek293b4af2009-01-15 01:26:25 +0000364 Emit32(idcount); // Emit the number of identifiers.
365 for (unsigned i = 0 ; i < idcount; ++i) Emit32(IIDMap[i].FileOffset);
Ted Kremenek6183e482008-12-03 01:16:39 +0000366
Ted Kremenek293b4af2009-01-15 01:26:25 +0000367 return std::make_pair(DataOff, std::make_pair(IDOff, LexicalOff));
Ted Kremenek85888962008-10-21 00:54:44 +0000368}
369
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000370
Ted Kremenekbe295332009-01-08 02:44:06 +0000371PCHEntry PTHWriter::LexTokens(Lexer& L) {
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000372 // Pad 0's so that we emit tokens to a 4-byte alignment.
373 // This speed up reading them back in.
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000374 Pad(Out, 4);
375 Offset off = (Offset) Out.tell();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000376
377 // Keep track of matching '#if' ... '#endif'.
378 typedef std::vector<std::pair<Offset, unsigned> > PPCondTable;
379 PPCondTable PPCond;
Ted Kremenekdad7b342008-12-12 18:31:09 +0000380 std::vector<unsigned> PPStartCond;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000381 bool ParsingPreprocessorDirective = false;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000382 Token Tok;
383
384 do {
385 L.LexFromRawLexer(Tok);
386
Ted Kremeneke5680f32008-12-23 01:30:52 +0000387 if ((Tok.isAtStartOfLine() || Tok.is(tok::eof)) &&
388 ParsingPreprocessorDirective) {
389 // Insert an eom token into the token cache. It has the same
390 // position as the next token that is not on the same line as the
391 // preprocessor directive. Observe that we continue processing
392 // 'Tok' when we exit this branch.
393 Token Tmp = Tok;
394 Tmp.setKind(tok::eom);
395 Tmp.clearFlag(Token::StartOfLine);
396 Tmp.setIdentifierInfo(0);
Ted Kremenekb978c662009-01-08 01:17:37 +0000397 EmitToken(Tmp);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000398 ParsingPreprocessorDirective = false;
399 }
400
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000401 if (Tok.is(tok::identifier)) {
402 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000403 continue;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000404 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000405
406 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000407 // Special processing for #include. Store the '#' token and lex
408 // the next token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000409 assert(!ParsingPreprocessorDirective);
Ted Kremenekfb645b62008-12-11 23:36:38 +0000410 Offset HashOff = (Offset) Out.tell();
Ted Kremenekb978c662009-01-08 01:17:37 +0000411 EmitToken(Tok);
Ted Kremenekdad7b342008-12-12 18:31:09 +0000412
413 // Get the next token.
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000414 L.LexFromRawLexer(Tok);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000415
416 assert(!Tok.isAtStartOfLine());
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000417
418 // Did we see 'include'/'import'/'include_next'?
419 if (!Tok.is(tok::identifier))
420 continue;
421
422 IdentifierInfo* II = PP.LookUpIdentifierInfo(Tok);
423 Tok.setIdentifierInfo(II);
424 tok::PPKeywordKind K = II->getPPKeywordID();
425
Ted Kremeneke5680f32008-12-23 01:30:52 +0000426 assert(K != tok::pp_not_keyword);
427 ParsingPreprocessorDirective = true;
428
429 switch (K) {
430 default:
431 break;
432 case tok::pp_include:
433 case tok::pp_import:
434 case tok::pp_include_next: {
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000435 // Save the 'include' token.
Ted Kremenekb978c662009-01-08 01:17:37 +0000436 EmitToken(Tok);
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000437 // Lex the next token as an include string.
438 L.setParsingPreprocessorDirective(true);
439 L.LexIncludeFilename(Tok);
440 L.setParsingPreprocessorDirective(false);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000441 assert(!Tok.isAtStartOfLine());
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000442 if (Tok.is(tok::identifier))
443 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000444
445 break;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000446 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000447 case tok::pp_if:
448 case tok::pp_ifdef:
449 case tok::pp_ifndef: {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000450 // Ad an entry for '#if' and friends. We initially set the target index
451 // to 0. This will get backpatched when we hit #endif.
452 PPStartCond.push_back(PPCond.size());
Ted Kremenekdad7b342008-12-12 18:31:09 +0000453 PPCond.push_back(std::make_pair(HashOff, 0U));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000454 break;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000455 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000456 case tok::pp_endif: {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000457 // Add an entry for '#endif'. We set the target table index to itself.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000458 // This will later be set to zero when emitting to the PTH file. We
459 // use 0 for uninitialized indices because that is easier to debug.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000460 unsigned index = PPCond.size();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000461 // Backpatch the opening '#if' entry.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000462 assert(!PPStartCond.empty());
463 assert(PPCond.size() > PPStartCond.back());
Ted Kremenekfb645b62008-12-11 23:36:38 +0000464 assert(PPCond[PPStartCond.back()].second == 0);
465 PPCond[PPStartCond.back()].second = index;
466 PPStartCond.pop_back();
Ted Kremenekdad7b342008-12-12 18:31:09 +0000467 // Add the new entry to PPCond.
468 PPCond.push_back(std::make_pair(HashOff, index));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000469 break;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000470 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000471 case tok::pp_elif:
472 case tok::pp_else: {
473 // Add an entry for #elif or #else.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000474 // This serves as both a closing and opening of a conditional block.
475 // This means that its entry will get backpatched later.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000476 unsigned index = PPCond.size();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000477 // Backpatch the previous '#if' entry.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000478 assert(!PPStartCond.empty());
479 assert(PPCond.size() > PPStartCond.back());
Ted Kremenekfb645b62008-12-11 23:36:38 +0000480 assert(PPCond[PPStartCond.back()].second == 0);
481 PPCond[PPStartCond.back()].second = index;
482 PPStartCond.pop_back();
483 // Now add '#elif' as a new block opening.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000484 PPCond.push_back(std::make_pair(HashOff, 0U));
485 PPStartCond.push_back(index);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000486 break;
487 }
Ted Kremenekfb645b62008-12-11 23:36:38 +0000488 }
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000489 }
490 }
Ted Kremenekb978c662009-01-08 01:17:37 +0000491 while (EmitToken(Tok), Tok.isNot(tok::eof));
492
Ted Kremenekdad7b342008-12-12 18:31:09 +0000493 assert(PPStartCond.empty() && "Error: imblanced preprocessor conditionals.");
Ted Kremenekb978c662009-01-08 01:17:37 +0000494
Ted Kremenekfb645b62008-12-11 23:36:38 +0000495 // Next write out PPCond.
496 Offset PPCondOff = (Offset) Out.tell();
Ted Kremenekdad7b342008-12-12 18:31:09 +0000497
498 // Write out the size of PPCond so that clients can identifer empty tables.
Ted Kremenekb978c662009-01-08 01:17:37 +0000499 Emit32(PPCond.size());
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000500
Ted Kremenekdad7b342008-12-12 18:31:09 +0000501 for (unsigned i = 0, e = PPCond.size(); i!=e; ++i) {
Ted Kremenekb978c662009-01-08 01:17:37 +0000502 Emit32(PPCond[i].first - off);
Ted Kremenekdad7b342008-12-12 18:31:09 +0000503 uint32_t x = PPCond[i].second;
504 assert(x != 0 && "PPCond entry not backpatched.");
505 // Emit zero for #endifs. This allows us to do checking when
506 // we read the PTH file back in.
Ted Kremenekb978c662009-01-08 01:17:37 +0000507 Emit32(x == i ? 0 : x);
Ted Kremenekfb645b62008-12-11 23:36:38 +0000508 }
509
Ted Kremenek277faca2009-01-27 00:01:05 +0000510 return PCHEntry(off, PPCondOff);
Ted Kremenekbe295332009-01-08 02:44:06 +0000511}
512
Ted Kremenek277faca2009-01-27 00:01:05 +0000513Offset PTHWriter::EmitCachedSpellings() {
514 // Write each cached strings to the PTH file.
515 Offset SpellingsOff = Out.tell();
516
517 for (std::vector<llvm::StringMapEntry<OffsetOpt>*>::iterator
518 I = StrEntries.begin(), E = StrEntries.end(); I!=E; ++I) {
Ted Kremenekbe295332009-01-08 02:44:06 +0000519
Ted Kremenek277faca2009-01-27 00:01:05 +0000520 const char* data = (*I)->getKeyData();
521 EmitBuf(data, data + (*I)->getKeyLength());
522 Emit8('\0');
Ted Kremenekbe295332009-01-08 02:44:06 +0000523 }
524
Ted Kremenek277faca2009-01-27 00:01:05 +0000525 return SpellingsOff;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000526}
Ted Kremenek85888962008-10-21 00:54:44 +0000527
Ted Kremenekb978c662009-01-08 01:17:37 +0000528void PTHWriter::GeneratePTH() {
Ted Kremeneke1b64982009-01-26 21:43:14 +0000529 // Generate the prologue.
530 Out << "cfe-pth";
Ted Kremenek67d15052009-01-26 21:50:21 +0000531 Emit32(PTHManager::Version);
Ted Kremeneke1b64982009-01-26 21:43:14 +0000532 Offset JumpOffset = Out.tell();
533 Emit32(0);
534
Ted Kremenek85888962008-10-21 00:54:44 +0000535 // Iterate over all the files in SourceManager. Create a lexer
536 // for each file and cache the tokens.
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000537 SourceManager &SM = PP.getSourceManager();
538 const LangOptions &LOpts = PP.getLangOptions();
Ted Kremenek85888962008-10-21 00:54:44 +0000539
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000540 for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
541 E = SM.fileinfo_end(); I != E; ++I) {
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000542 const SrcMgr::ContentCache &C = *I->second;
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000543 const FileEntry *FE = C.Entry;
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000544
545 // FIXME: Handle files with non-absolute paths.
546 llvm::sys::Path P(FE->getName());
547 if (!P.isAbsolute())
548 continue;
Ted Kremenek85888962008-10-21 00:54:44 +0000549
Chris Lattner5c263852009-01-17 03:49:48 +0000550 assert(!PM.count(FE) && "fileinfo's are not uniqued on FileEntry?");
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000551
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000552 const llvm::MemoryBuffer *B = C.getBuffer();
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000553 if (!B) continue;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000554
Chris Lattner2b2453a2009-01-17 06:22:33 +0000555 FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
Chris Lattner025c3a62009-01-17 07:35:14 +0000556 Lexer L(FID, SM, LOpts);
Ted Kremenekb978c662009-01-08 01:17:37 +0000557 PM[FE] = LexTokens(L);
Daniel Dunbar31309ab2008-11-26 02:18:33 +0000558 }
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000559
560 // Write out the identifier table.
Ted Kremenek293b4af2009-01-15 01:26:25 +0000561 const std::pair<Offset, std::pair<Offset,Offset> >& IdTableOff
562 = EmitIdentifierTable();
Ted Kremenek85888962008-10-21 00:54:44 +0000563
Ted Kremenekbe295332009-01-08 02:44:06 +0000564 // Write out the cached strings table.
Ted Kremenek277faca2009-01-27 00:01:05 +0000565 Offset SpellingOff = EmitCachedSpellings();
Ted Kremenekbe295332009-01-08 02:44:06 +0000566
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000567 // Write out the file table.
Ted Kremenekb978c662009-01-08 01:17:37 +0000568 Offset FileTableOff = EmitFileTable();
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000569
570 // Finally, write out the offset table at the end.
Ted Kremeneke1b64982009-01-26 21:43:14 +0000571 Offset JumpTargetOffset = Out.tell();
Ted Kremenekb978c662009-01-08 01:17:37 +0000572 Emit32(IdTableOff.first);
Ted Kremenek293b4af2009-01-15 01:26:25 +0000573 Emit32(IdTableOff.second.first);
574 Emit32(IdTableOff.second.second);
Ted Kremenekb978c662009-01-08 01:17:37 +0000575 Emit32(FileTableOff);
Ted Kremenek277faca2009-01-27 00:01:05 +0000576 Emit32(SpellingOff);
Ted Kremeneke1b64982009-01-26 21:43:14 +0000577
578 // Now write the offset in the prologue.
579 Out.seek(JumpOffset);
580 Emit32(JumpTargetOffset);
Ted Kremenekb978c662009-01-08 01:17:37 +0000581}
582
583void clang::CacheTokens(Preprocessor& PP, const std::string& OutFile) {
584 // Lex through the entire file. This will populate SourceManager with
585 // all of the header information.
586 Token Tok;
587 PP.EnterMainSourceFile();
588 do { PP.Lex(Tok); } while (Tok.isNot(tok::eof));
589
590 // Open up the PTH file.
591 std::string ErrMsg;
592 llvm::raw_fd_ostream Out(OutFile.c_str(), true, ErrMsg);
593
594 if (!ErrMsg.empty()) {
595 llvm::errs() << "PTH error: " << ErrMsg << "\n";
596 return;
597 }
598
599 // Create the PTHWriter and generate the PTH file.
600 PTHWriter PW(Out, PP);
601 PW.GeneratePTH();
Ted Kremenek85888962008-10-21 00:54:44 +0000602}
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000603
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000604
605//===----------------------------------------------------------------------===//
606// Client code of on-disk hashtable logic.
607//===----------------------------------------------------------------------===//
608
609Offset PTHWriter::EmitFileTable() {
610 // Determine the offset where this table appears in the PTH file.
611 Offset off = (Offset) Out.tell();
612
613 // Output the size of the table.
614 Emit32(PM.size());
615
616 for (PCHMap::iterator I=PM.begin(), E=PM.end(); I!=E; ++I) {
617 const FileEntry* FE = I->first;
618 const char* Name = FE->getName();
619 unsigned size = strlen(Name);
620 Emit32(size);
621 EmitBuf(Name, Name+size);
622 Emit32(I->second.getTokenOffset());
623 Emit32(I->second.getPPCondTableOffset());
624 }
625
626 return off;
627}
628