blob: 3f2cca8c562c934f5e93147b4fe4353d952cfce1 [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 Kremenekbe295332009-01-08 02:44:06 +000055namespace {
56class VISIBILITY_HIDDEN PCHEntry {
57 Offset TokenData, PPCondData;
Ted Kremenekbe295332009-01-08 02:44:06 +000058
59public:
60 PCHEntry() {}
61
Ted Kremenek277faca2009-01-27 00:01:05 +000062 PCHEntry(Offset td, Offset ppcd)
63 : TokenData(td), PPCondData(ppcd) {}
Ted Kremenekbe295332009-01-08 02:44:06 +000064
Ted Kremenek277faca2009-01-27 00:01:05 +000065 Offset getTokenOffset() const { return TokenData; }
Ted Kremenekbe295332009-01-08 02:44:06 +000066 Offset getPPCondTableOffset() const { return PPCondData; }
Ted Kremenek277faca2009-01-27 00:01:05 +000067};
Ted Kremenekbe295332009-01-08 02:44:06 +000068
Ted Kremenek277faca2009-01-27 00:01:05 +000069class OffsetOpt {
70 bool valid;
71 Offset off;
72public:
73 OffsetOpt() : valid(false) {}
74 bool hasOffset() const { return valid; }
75 Offset getOffset() const { assert(valid); return off; }
76 void setOffset(Offset o) { off = o; valid = true; }
Ted Kremenekbe295332009-01-08 02:44:06 +000077};
78} // end anonymous namespace
79
80typedef llvm::DenseMap<const FileEntry*, PCHEntry> PCHMap;
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +000081typedef llvm::DenseMap<const IdentifierInfo*,uint32_t> IDMap;
Ted Kremenek277faca2009-01-27 00:01:05 +000082typedef llvm::StringMap<OffsetOpt, llvm::BumpPtrAllocator> CachedStrsTy;
Ted Kremenek85888962008-10-21 00:54:44 +000083
Ted Kremenekb978c662009-01-08 01:17:37 +000084namespace {
85class VISIBILITY_HIDDEN PTHWriter {
86 IDMap IM;
87 llvm::raw_fd_ostream& Out;
88 Preprocessor& PP;
89 uint32_t idcount;
90 PCHMap PM;
Ted Kremenekbe295332009-01-08 02:44:06 +000091 CachedStrsTy CachedStrs;
Ted Kremenek277faca2009-01-27 00:01:05 +000092 Offset CurStrOffset;
93 std::vector<llvm::StringMapEntry<OffsetOpt>*> StrEntries;
Ted Kremenek8f174e12008-12-23 02:52:12 +000094
Ted Kremenekb978c662009-01-08 01:17:37 +000095 //// Get the persistent id for the given IdentifierInfo*.
96 uint32_t ResolveID(const IdentifierInfo* II);
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +000097
Ted Kremenekb978c662009-01-08 01:17:37 +000098 /// Emit a token to the PTH file.
99 void EmitToken(const Token& T);
100
101 void Emit8(uint32_t V) {
102 Out << (unsigned char)(V);
103 }
104
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000105 void Emit16(uint32_t V) { ::Emit16(Out, V); }
Ted Kremenekb978c662009-01-08 01:17:37 +0000106
107 void Emit24(uint32_t V) {
108 Out << (unsigned char)(V);
109 Out << (unsigned char)(V >> 8);
110 Out << (unsigned char)(V >> 16);
111 assert((V >> 24) == 0);
112 }
113
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000114 void Emit32(uint32_t V) { ::Emit32(Out, V); }
115
Ted Kremenekb978c662009-01-08 01:17:37 +0000116 void EmitBuf(const char* I, const char* E) {
117 for ( ; I != E ; ++I) Out << *I;
118 }
119
Ted Kremenek293b4af2009-01-15 01:26:25 +0000120 std::pair<Offset,std::pair<Offset, Offset> > EmitIdentifierTable();
Ted Kremenekb978c662009-01-08 01:17:37 +0000121 Offset EmitFileTable();
Ted Kremenekbe295332009-01-08 02:44:06 +0000122 PCHEntry LexTokens(Lexer& L);
Ted Kremenek277faca2009-01-27 00:01:05 +0000123 Offset EmitCachedSpellings();
Ted Kremenekbe295332009-01-08 02:44:06 +0000124
Ted Kremenekb978c662009-01-08 01:17:37 +0000125public:
126 PTHWriter(llvm::raw_fd_ostream& out, Preprocessor& pp)
Ted Kremenek277faca2009-01-27 00:01:05 +0000127 : Out(out), PP(pp), idcount(0), CurStrOffset(0) {}
Ted Kremenekb978c662009-01-08 01:17:37 +0000128
129 void GeneratePTH();
130};
131} // end anonymous namespace
132
133uint32_t PTHWriter::ResolveID(const IdentifierInfo* II) {
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000134 // Null IdentifierInfo's map to the persistent ID 0.
135 if (!II)
136 return 0;
137
Ted Kremenek85888962008-10-21 00:54:44 +0000138 IDMap::iterator I = IM.find(II);
139
140 if (I == IM.end()) {
Ted Kremenekb978c662009-01-08 01:17:37 +0000141 IM[II] = ++idcount; // Pre-increment since '0' is reserved for NULL.
142 return idcount;
Ted Kremenek85888962008-10-21 00:54:44 +0000143 }
144
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000145 return I->second; // We've already added 1.
Ted Kremenek85888962008-10-21 00:54:44 +0000146}
147
Ted Kremenekb978c662009-01-08 01:17:37 +0000148void PTHWriter::EmitToken(const Token& T) {
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000149 Emit32(((uint32_t) T.getKind()) |
150 (((uint32_t) T.getFlags()) << 8) |
151 (((uint32_t) T.getLength()) << 16));
Ted Kremenek277faca2009-01-27 00:01:05 +0000152
Chris Lattner47246be2009-01-26 19:29:26 +0000153 // Literals (strings, numbers, characters) get cached spellings.
154 if (T.isLiteral()) {
155 // FIXME: This uses the slow getSpelling(). Perhaps we do better
156 // in the future? This only slows down PTH generation.
157 const std::string &spelling = PP.getSpelling(T);
158 const char* s = spelling.c_str();
159
160 // Get the string entry.
Ted Kremenek277faca2009-01-27 00:01:05 +0000161 llvm::StringMapEntry<OffsetOpt> *E =
162 &CachedStrs.GetOrCreateValue(s, s+spelling.size());
163
164 if (!E->getValue().hasOffset()) {
165 E->getValue().setOffset(CurStrOffset);
166 StrEntries.push_back(E);
167 CurStrOffset += spelling.size() + 1;
168 }
169
170 Emit32(E->getValue().getOffset());
Ted Kremenekb978c662009-01-08 01:17:37 +0000171 }
Ted Kremenek277faca2009-01-27 00:01:05 +0000172 else
173 Emit32(ResolveID(T.getIdentifierInfo()));
174
Chris Lattner52c29082009-01-27 06:27:13 +0000175 Emit32(PP.getSourceManager().getFileOffset(T.getLocation()));
Ted Kremenek85888962008-10-21 00:54:44 +0000176}
177
Ted Kremenekb978c662009-01-08 01:17:37 +0000178namespace {
179struct VISIBILITY_HIDDEN IDData {
Ted Kremenekfa59aad2008-11-26 23:58:26 +0000180 const IdentifierInfo* II;
181 uint32_t FileOffset;
Ted Kremenek293b4af2009-01-15 01:26:25 +0000182};
183
184class VISIBILITY_HIDDEN CompareIDDataIndex {
185 IDData* Table;
186public:
187 CompareIDDataIndex(IDData* table) : Table(table) {}
188
189 bool operator()(unsigned i, unsigned j) const {
Ted Kremenek72b1b152009-01-15 18:47:46 +0000190 const IdentifierInfo* II_i = Table[i].II;
191 const IdentifierInfo* II_j = Table[j].II;
192
193 unsigned i_len = II_i->getLength();
194 unsigned j_len = II_j->getLength();
195
196 if (i_len > j_len)
197 return false;
198
199 if (i_len < j_len)
200 return true;
201
202 // Otherwise, compare the strings themselves!
203 return strncmp(II_i->getName(), II_j->getName(), i_len) < 0;
Ted Kremenek293b4af2009-01-15 01:26:25 +0000204 }
Ted Kremenekfa59aad2008-11-26 23:58:26 +0000205};
Ted Kremenekb978c662009-01-08 01:17:37 +0000206}
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000207
Ted Kremenek293b4af2009-01-15 01:26:25 +0000208std::pair<Offset,std::pair<Offset,Offset> >
209PTHWriter::EmitIdentifierTable() {
210 llvm::BumpPtrAllocator Alloc;
Ted Kremenekfa59aad2008-11-26 23:58:26 +0000211
212 // Build an inverse map from persistent IDs -> IdentifierInfo*.
Ted Kremenek293b4af2009-01-15 01:26:25 +0000213 IDData* IIDMap = Alloc.Allocate<IDData>(idcount);
Ted Kremenek85888962008-10-21 00:54:44 +0000214
Ted Kremenekfa59aad2008-11-26 23:58:26 +0000215 // Generate mapping from persistent IDs -> IdentifierInfo*.
Ted Kremenekb978c662009-01-08 01:17:37 +0000216 for (IDMap::iterator I=IM.begin(), E=IM.end(); I!=E; ++I) {
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000217 // Decrement by 1 because we are using a vector for the lookup and
218 // 0 is reserved for NULL.
219 assert(I->second > 0);
Ted Kremenek293b4af2009-01-15 01:26:25 +0000220 assert(I->second-1 < idcount);
221 unsigned idx = I->second-1;
222 IIDMap[idx].II = I->first;
223 }
Ted Kremenekfa59aad2008-11-26 23:58:26 +0000224
Ted Kremenek293b4af2009-01-15 01:26:25 +0000225 // We want to write out the strings in lexical order to support binary
226 // search of strings to identifiers. Create such a table.
227 unsigned *LexicalOrder = Alloc.Allocate<unsigned>(idcount);
228 for (unsigned i = 0; i < idcount ; ++i ) LexicalOrder[i] = i;
229 std::sort(LexicalOrder, LexicalOrder+idcount, CompareIDDataIndex(IIDMap));
230
231 // Write out the lexically-sorted table of persistent ids.
232 Offset LexicalOff = Out.tell();
233 for (unsigned i = 0; i < idcount ; ++i) Emit32(LexicalOrder[i]);
234
235 // Write out the string data itself.
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000236 Offset DataOff = Out.tell();
Ted Kremenek6183e482008-12-03 01:16:39 +0000237
Ted Kremenek293b4af2009-01-15 01:26:25 +0000238 for (unsigned i = 0; i < idcount; ++i) {
239 IDData& d = IIDMap[i];
240 d.FileOffset = Out.tell(); // Record the location for this data.
241 unsigned len = d.II->getLength(); // Write out the string length.
Ted Kremenekb978c662009-01-08 01:17:37 +0000242 Emit32(len);
Ted Kremenek293b4af2009-01-15 01:26:25 +0000243 const char* buf = d.II->getName(); // Write out the string data.
Ted Kremenek72b1b152009-01-15 18:47:46 +0000244 EmitBuf(buf, buf+len);
245 // Emit a null character for those clients expecting that IdentifierInfo
246 // strings are null terminated.
247 Emit8('\0');
Ted Kremenek85888962008-10-21 00:54:44 +0000248 }
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000249
Ted Kremenekfa59aad2008-11-26 23:58:26 +0000250 // Now emit the table mapping from persistent IDs to PTH file offsets.
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000251 Offset IDOff = Out.tell();
Ted Kremenek293b4af2009-01-15 01:26:25 +0000252 Emit32(idcount); // Emit the number of identifiers.
253 for (unsigned i = 0 ; i < idcount; ++i) Emit32(IIDMap[i].FileOffset);
Ted Kremenek6183e482008-12-03 01:16:39 +0000254
Ted Kremenek293b4af2009-01-15 01:26:25 +0000255 return std::make_pair(DataOff, std::make_pair(IDOff, LexicalOff));
Ted Kremenek85888962008-10-21 00:54:44 +0000256}
257
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000258
Ted Kremenekbe295332009-01-08 02:44:06 +0000259PCHEntry PTHWriter::LexTokens(Lexer& L) {
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000260 // Pad 0's so that we emit tokens to a 4-byte alignment.
261 // This speed up reading them back in.
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000262 Pad(Out, 4);
263 Offset off = (Offset) Out.tell();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000264
265 // Keep track of matching '#if' ... '#endif'.
266 typedef std::vector<std::pair<Offset, unsigned> > PPCondTable;
267 PPCondTable PPCond;
Ted Kremenekdad7b342008-12-12 18:31:09 +0000268 std::vector<unsigned> PPStartCond;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000269 bool ParsingPreprocessorDirective = false;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000270 Token Tok;
271
272 do {
273 L.LexFromRawLexer(Tok);
274
Ted Kremeneke5680f32008-12-23 01:30:52 +0000275 if ((Tok.isAtStartOfLine() || Tok.is(tok::eof)) &&
276 ParsingPreprocessorDirective) {
277 // Insert an eom token into the token cache. It has the same
278 // position as the next token that is not on the same line as the
279 // preprocessor directive. Observe that we continue processing
280 // 'Tok' when we exit this branch.
281 Token Tmp = Tok;
282 Tmp.setKind(tok::eom);
283 Tmp.clearFlag(Token::StartOfLine);
284 Tmp.setIdentifierInfo(0);
Ted Kremenekb978c662009-01-08 01:17:37 +0000285 EmitToken(Tmp);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000286 ParsingPreprocessorDirective = false;
287 }
288
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000289 if (Tok.is(tok::identifier)) {
290 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000291 continue;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000292 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000293
294 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000295 // Special processing for #include. Store the '#' token and lex
296 // the next token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000297 assert(!ParsingPreprocessorDirective);
Ted Kremenekfb645b62008-12-11 23:36:38 +0000298 Offset HashOff = (Offset) Out.tell();
Ted Kremenekb978c662009-01-08 01:17:37 +0000299 EmitToken(Tok);
Ted Kremenekdad7b342008-12-12 18:31:09 +0000300
301 // Get the next token.
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000302 L.LexFromRawLexer(Tok);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000303
304 assert(!Tok.isAtStartOfLine());
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000305
306 // Did we see 'include'/'import'/'include_next'?
307 if (!Tok.is(tok::identifier))
308 continue;
309
310 IdentifierInfo* II = PP.LookUpIdentifierInfo(Tok);
311 Tok.setIdentifierInfo(II);
312 tok::PPKeywordKind K = II->getPPKeywordID();
313
Ted Kremeneke5680f32008-12-23 01:30:52 +0000314 assert(K != tok::pp_not_keyword);
315 ParsingPreprocessorDirective = true;
316
317 switch (K) {
318 default:
319 break;
320 case tok::pp_include:
321 case tok::pp_import:
322 case tok::pp_include_next: {
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000323 // Save the 'include' token.
Ted Kremenekb978c662009-01-08 01:17:37 +0000324 EmitToken(Tok);
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000325 // Lex the next token as an include string.
326 L.setParsingPreprocessorDirective(true);
327 L.LexIncludeFilename(Tok);
328 L.setParsingPreprocessorDirective(false);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000329 assert(!Tok.isAtStartOfLine());
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000330 if (Tok.is(tok::identifier))
331 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000332
333 break;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000334 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000335 case tok::pp_if:
336 case tok::pp_ifdef:
337 case tok::pp_ifndef: {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000338 // Ad an entry for '#if' and friends. We initially set the target index
339 // to 0. This will get backpatched when we hit #endif.
340 PPStartCond.push_back(PPCond.size());
Ted Kremenekdad7b342008-12-12 18:31:09 +0000341 PPCond.push_back(std::make_pair(HashOff, 0U));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000342 break;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000343 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000344 case tok::pp_endif: {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000345 // Add an entry for '#endif'. We set the target table index to itself.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000346 // This will later be set to zero when emitting to the PTH file. We
347 // use 0 for uninitialized indices because that is easier to debug.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000348 unsigned index = PPCond.size();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000349 // Backpatch the opening '#if' entry.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000350 assert(!PPStartCond.empty());
351 assert(PPCond.size() > PPStartCond.back());
Ted Kremenekfb645b62008-12-11 23:36:38 +0000352 assert(PPCond[PPStartCond.back()].second == 0);
353 PPCond[PPStartCond.back()].second = index;
354 PPStartCond.pop_back();
Ted Kremenekdad7b342008-12-12 18:31:09 +0000355 // Add the new entry to PPCond.
356 PPCond.push_back(std::make_pair(HashOff, index));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000357 break;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000358 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000359 case tok::pp_elif:
360 case tok::pp_else: {
361 // Add an entry for #elif or #else.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000362 // This serves as both a closing and opening of a conditional block.
363 // This means that its entry will get backpatched later.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000364 unsigned index = PPCond.size();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000365 // Backpatch the previous '#if' entry.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000366 assert(!PPStartCond.empty());
367 assert(PPCond.size() > PPStartCond.back());
Ted Kremenekfb645b62008-12-11 23:36:38 +0000368 assert(PPCond[PPStartCond.back()].second == 0);
369 PPCond[PPStartCond.back()].second = index;
370 PPStartCond.pop_back();
371 // Now add '#elif' as a new block opening.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000372 PPCond.push_back(std::make_pair(HashOff, 0U));
373 PPStartCond.push_back(index);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000374 break;
375 }
Ted Kremenekfb645b62008-12-11 23:36:38 +0000376 }
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000377 }
378 }
Ted Kremenekb978c662009-01-08 01:17:37 +0000379 while (EmitToken(Tok), Tok.isNot(tok::eof));
380
Ted Kremenekdad7b342008-12-12 18:31:09 +0000381 assert(PPStartCond.empty() && "Error: imblanced preprocessor conditionals.");
Ted Kremenekb978c662009-01-08 01:17:37 +0000382
Ted Kremenekfb645b62008-12-11 23:36:38 +0000383 // Next write out PPCond.
384 Offset PPCondOff = (Offset) Out.tell();
Ted Kremenekdad7b342008-12-12 18:31:09 +0000385
386 // Write out the size of PPCond so that clients can identifer empty tables.
Ted Kremenekb978c662009-01-08 01:17:37 +0000387 Emit32(PPCond.size());
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000388
Ted Kremenekdad7b342008-12-12 18:31:09 +0000389 for (unsigned i = 0, e = PPCond.size(); i!=e; ++i) {
Ted Kremenekb978c662009-01-08 01:17:37 +0000390 Emit32(PPCond[i].first - off);
Ted Kremenekdad7b342008-12-12 18:31:09 +0000391 uint32_t x = PPCond[i].second;
392 assert(x != 0 && "PPCond entry not backpatched.");
393 // Emit zero for #endifs. This allows us to do checking when
394 // we read the PTH file back in.
Ted Kremenekb978c662009-01-08 01:17:37 +0000395 Emit32(x == i ? 0 : x);
Ted Kremenekfb645b62008-12-11 23:36:38 +0000396 }
397
Ted Kremenek277faca2009-01-27 00:01:05 +0000398 return PCHEntry(off, PPCondOff);
Ted Kremenekbe295332009-01-08 02:44:06 +0000399}
400
Ted Kremenek277faca2009-01-27 00:01:05 +0000401Offset PTHWriter::EmitCachedSpellings() {
402 // Write each cached strings to the PTH file.
403 Offset SpellingsOff = Out.tell();
404
405 for (std::vector<llvm::StringMapEntry<OffsetOpt>*>::iterator
406 I = StrEntries.begin(), E = StrEntries.end(); I!=E; ++I) {
Ted Kremenekbe295332009-01-08 02:44:06 +0000407
Ted Kremenek277faca2009-01-27 00:01:05 +0000408 const char* data = (*I)->getKeyData();
409 EmitBuf(data, data + (*I)->getKeyLength());
410 Emit8('\0');
Ted Kremenekbe295332009-01-08 02:44:06 +0000411 }
412
Ted Kremenek277faca2009-01-27 00:01:05 +0000413 return SpellingsOff;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000414}
Ted Kremenek85888962008-10-21 00:54:44 +0000415
Ted Kremenekb978c662009-01-08 01:17:37 +0000416void PTHWriter::GeneratePTH() {
Ted Kremeneke1b64982009-01-26 21:43:14 +0000417 // Generate the prologue.
418 Out << "cfe-pth";
Ted Kremenek67d15052009-01-26 21:50:21 +0000419 Emit32(PTHManager::Version);
Ted Kremeneke1b64982009-01-26 21:43:14 +0000420 Offset JumpOffset = Out.tell();
421 Emit32(0);
422
Ted Kremenek85888962008-10-21 00:54:44 +0000423 // Iterate over all the files in SourceManager. Create a lexer
424 // for each file and cache the tokens.
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000425 SourceManager &SM = PP.getSourceManager();
426 const LangOptions &LOpts = PP.getLangOptions();
Ted Kremenek85888962008-10-21 00:54:44 +0000427
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000428 for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
429 E = SM.fileinfo_end(); I != E; ++I) {
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000430 const SrcMgr::ContentCache &C = *I->second;
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000431 const FileEntry *FE = C.Entry;
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000432
433 // FIXME: Handle files with non-absolute paths.
434 llvm::sys::Path P(FE->getName());
435 if (!P.isAbsolute())
436 continue;
Ted Kremenek85888962008-10-21 00:54:44 +0000437
Chris Lattner5c263852009-01-17 03:49:48 +0000438 assert(!PM.count(FE) && "fileinfo's are not uniqued on FileEntry?");
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000439
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000440 const llvm::MemoryBuffer *B = C.getBuffer();
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000441 if (!B) continue;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000442
Chris Lattner2b2453a2009-01-17 06:22:33 +0000443 FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
Chris Lattner025c3a62009-01-17 07:35:14 +0000444 Lexer L(FID, SM, LOpts);
Ted Kremenekb978c662009-01-08 01:17:37 +0000445 PM[FE] = LexTokens(L);
Daniel Dunbar31309ab2008-11-26 02:18:33 +0000446 }
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000447
448 // Write out the identifier table.
Ted Kremenek293b4af2009-01-15 01:26:25 +0000449 const std::pair<Offset, std::pair<Offset,Offset> >& IdTableOff
450 = EmitIdentifierTable();
Ted Kremenek85888962008-10-21 00:54:44 +0000451
Ted Kremenekbe295332009-01-08 02:44:06 +0000452 // Write out the cached strings table.
Ted Kremenek277faca2009-01-27 00:01:05 +0000453 Offset SpellingOff = EmitCachedSpellings();
Ted Kremenekbe295332009-01-08 02:44:06 +0000454
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000455 // Write out the file table.
Ted Kremenekb978c662009-01-08 01:17:37 +0000456 Offset FileTableOff = EmitFileTable();
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000457
458 // Finally, write out the offset table at the end.
Ted Kremeneke1b64982009-01-26 21:43:14 +0000459 Offset JumpTargetOffset = Out.tell();
Ted Kremenekb978c662009-01-08 01:17:37 +0000460 Emit32(IdTableOff.first);
Ted Kremenek293b4af2009-01-15 01:26:25 +0000461 Emit32(IdTableOff.second.first);
462 Emit32(IdTableOff.second.second);
Ted Kremenekb978c662009-01-08 01:17:37 +0000463 Emit32(FileTableOff);
Ted Kremenek277faca2009-01-27 00:01:05 +0000464 Emit32(SpellingOff);
Ted Kremeneke1b64982009-01-26 21:43:14 +0000465
466 // Now write the offset in the prologue.
467 Out.seek(JumpOffset);
468 Emit32(JumpTargetOffset);
Ted Kremenekb978c662009-01-08 01:17:37 +0000469}
470
471void clang::CacheTokens(Preprocessor& PP, const std::string& OutFile) {
472 // Lex through the entire file. This will populate SourceManager with
473 // all of the header information.
474 Token Tok;
475 PP.EnterMainSourceFile();
476 do { PP.Lex(Tok); } while (Tok.isNot(tok::eof));
477
478 // Open up the PTH file.
479 std::string ErrMsg;
480 llvm::raw_fd_ostream Out(OutFile.c_str(), true, ErrMsg);
481
482 if (!ErrMsg.empty()) {
483 llvm::errs() << "PTH error: " << ErrMsg << "\n";
484 return;
485 }
486
487 // Create the PTHWriter and generate the PTH file.
488 PTHWriter PW(Out, PP);
489 PW.GeneratePTH();
Ted Kremenek85888962008-10-21 00:54:44 +0000490}
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000491
492//===----------------------------------------------------------------------===//
493// On Disk Hashtable Logic. This will eventually get refactored and put
494// elsewhere.
495//===----------------------------------------------------------------------===//
496
497template<typename Info>
498class OnDiskChainedHashTableGenerator {
499 unsigned NumBuckets;
500 unsigned NumEntries;
501 llvm::BumpPtrAllocator BA;
502
503 class Item {
504 public:
505 typename Info::KeyT key;
506 typename Info::DataT data;
507 Item *next;
508 const uint32_t hash;
509
510 Item(typename Info::KeyT_ref k, typename Info::DataT_ref d)
511 : key(k), data(d), next(0), hash(Info::getHash(k)) {}
512 };
513
514 class Bucket {
515 public:
516 Offset off;
517 Item* head;
518 unsigned length;
519
520 Bucket() {}
521 };
522
523 Bucket* Buckets;
524
525private:
526 void insert(Item** b, size_t size, Item* E) {
527 unsigned idx = E->hash & (size - 1);
528 Bucket& B = b[idx];
529 E->next = B.head;
530 ++B.length;
531 B.head = E;
532 }
533
534 void resize(size_t newsize) {
535 Bucket* newBuckets = calloc(newsize, sizeof(Bucket));
536
537 for (unsigned i = 0; i < NumBuckets; ++i)
538 for (Item* E = Buckets[i]; E ; ) {
539 Item* N = E->next;
540 E->Next = 0;
541 insert(newBuckets, newsize, E);
542 E = N;
543 }
544
545 free(Buckets);
546 NumBuckets = newsize;
547 Buckets = newBuckets;
548 }
549
550public:
551
552 void insert(typename Info::Key_ref key, typename Info::DataT_ref data) {
553 ++NumEntries;
554 if (4*NumEntries >= 3*NumBuckets) resize(NumBuckets*2);
555 insert(Buckets, NumBuckets, new (BA.Allocate<Item>()) Item(key, data));
556 }
557
558 Offset Emit(llvm::raw_fd_ostream& out) {
559 // Emit the payload of the table.
560 for (unsigned i = 0; i < NumBuckets; ++i) {
561 Bucket& B = Buckets[i];
562 if (!B.head) continue;
563
564 // Store the offset for the data of this bucket.
565 Pad(out, 4); // 4-byte alignment.
566 B.off = out.tell();
567
568 // Write out the number of items in the bucket. We just write out
569 // 4 bytes to keep things 4-byte aligned.
570 Emit32(out, B.length);
571
572 // Write out the entries in the bucket.
573 for (Item *I = B.head; I ; I = I->next) {
574 Emit32(out, I->hash);
575 Info::EmitKey(out, I->key);
576 Info::EmitData(out, I->data);
577 }
578 }
579
580 // Emit the hashtable itself.
581 Pad(out, 4);
582 Offset TableOff = out.tell();
583 Emit32(out, NumBuckets);
584 for (unsigned i = 0; i < NumBuckets; ++i) Emit32(out, Buckets[i].off);
585
586 return TableOff;
587 }
588
589 OnDiskChainedHashTableGenerator() {
590 NumEntries = 0;
591 NumBuckets = 64;
592 Buckets = calloc(NumBuckets, sizeof(Bucket));
593 }
594
595 ~OnDiskChainedHashTableGenerator() {
596 free(Buckets);
597 }
598};
599
600//===----------------------------------------------------------------------===//
601// Client code of on-disk hashtable logic.
602//===----------------------------------------------------------------------===//
603
604Offset PTHWriter::EmitFileTable() {
605 // Determine the offset where this table appears in the PTH file.
606 Offset off = (Offset) Out.tell();
607
608 // Output the size of the table.
609 Emit32(PM.size());
610
611 for (PCHMap::iterator I=PM.begin(), E=PM.end(); I!=E; ++I) {
612 const FileEntry* FE = I->first;
613 const char* Name = FE->getName();
614 unsigned size = strlen(Name);
615 Emit32(size);
616 EmitBuf(Name, Name+size);
617 Emit32(I->second.getTokenOffset());
618 Emit32(I->second.getPPCondTableOffset());
619 }
620
621 return off;
622}
623