CacheTokens.cpp revision 622ab50adc847564d62dd88694166a7466a6136a
1//===--- CacheTokens.cpp - Caching of lexer tokens for PTH 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 PTH support for Clang that is
11// based on caching lexed tokens and identifiers.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Frontend/Utils.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/Basic/OnDiskHashTable.h"
21#include "clang/Lex/Lexer.h"
22#include "clang/Lex/Preprocessor.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/Support/MemoryBuffer.h"
26#include "llvm/Support/raw_ostream.h"
27#include "llvm/System/Path.h"
28
29// FIXME: put this somewhere else?
30#ifndef S_ISDIR
31#define S_ISDIR(x) (((x)&_S_IFDIR)!=0)
32#endif
33
34using namespace clang;
35using namespace clang::io;
36
37//===----------------------------------------------------------------------===//
38// PTH-specific stuff.
39//===----------------------------------------------------------------------===//
40
41namespace {
42class PTHEntry {
43  Offset TokenData, PPCondData;
44
45public:
46  PTHEntry() {}
47
48  PTHEntry(Offset td, Offset ppcd)
49    : TokenData(td), PPCondData(ppcd) {}
50
51  Offset getTokenOffset() const { return TokenData; }
52  Offset getPPCondTableOffset() const { return PPCondData; }
53};
54
55
56class PTHEntryKeyVariant {
57  union { const FileEntry* FE; const char* Path; };
58  enum { IsFE = 0x1, IsDE = 0x2, IsNoExist = 0x0 } Kind;
59  struct stat *StatBuf;
60public:
61  PTHEntryKeyVariant(const FileEntry *fe)
62    : FE(fe), Kind(IsFE), StatBuf(0) {}
63
64  PTHEntryKeyVariant(struct stat* statbuf, const char* path)
65    : Path(path), Kind(IsDE), StatBuf(new struct stat(*statbuf)) {}
66
67  explicit PTHEntryKeyVariant(const char* path)
68    : Path(path), Kind(IsNoExist), StatBuf(0) {}
69
70  bool isFile() const { return Kind == IsFE; }
71
72  llvm::StringRef getString() const {
73    return Kind == IsFE ? FE->getName() : Path;
74  }
75
76  unsigned getKind() const { return (unsigned) Kind; }
77
78  void EmitData(llvm::raw_ostream& Out) {
79    switch (Kind) {
80    case IsFE:
81      // Emit stat information.
82      ::Emit32(Out, FE->getInode());
83      ::Emit32(Out, FE->getDevice());
84      ::Emit16(Out, FE->getFileMode());
85      ::Emit64(Out, FE->getModificationTime());
86      ::Emit64(Out, FE->getSize());
87      break;
88    case IsDE:
89      // Emit stat information.
90      ::Emit32(Out, (uint32_t) StatBuf->st_ino);
91      ::Emit32(Out, (uint32_t) StatBuf->st_dev);
92      ::Emit16(Out, (uint16_t) StatBuf->st_mode);
93      ::Emit64(Out, (uint64_t) StatBuf->st_mtime);
94      ::Emit64(Out, (uint64_t) StatBuf->st_size);
95      delete StatBuf;
96      break;
97    default:
98      break;
99    }
100  }
101
102  unsigned getRepresentationLength() const {
103    return Kind == IsNoExist ? 0 : 4 + 4 + 2 + 8 + 8;
104  }
105};
106
107class FileEntryPTHEntryInfo {
108public:
109  typedef PTHEntryKeyVariant key_type;
110  typedef key_type key_type_ref;
111
112  typedef PTHEntry data_type;
113  typedef const PTHEntry& data_type_ref;
114
115  static unsigned ComputeHash(PTHEntryKeyVariant V) {
116    return llvm::HashString(V.getString());
117  }
118
119  static std::pair<unsigned,unsigned>
120  EmitKeyDataLength(llvm::raw_ostream& Out, PTHEntryKeyVariant V,
121                    const PTHEntry& E) {
122
123    unsigned n = V.getString().size() + 1 + 1;
124    ::Emit16(Out, n);
125
126    unsigned m = V.getRepresentationLength() + (V.isFile() ? 4 + 4 : 0);
127    ::Emit8(Out, m);
128
129    return std::make_pair(n, m);
130  }
131
132  static void EmitKey(llvm::raw_ostream& Out, PTHEntryKeyVariant V, unsigned n){
133    // Emit the entry kind.
134    ::Emit8(Out, (unsigned) V.getKind());
135    // Emit the string.
136    Out.write(V.getString().data(), n - 1);
137  }
138
139  static void EmitData(llvm::raw_ostream& Out, PTHEntryKeyVariant V,
140                       const PTHEntry& E, unsigned) {
141
142
143    // For file entries emit the offsets into the PTH file for token data
144    // and the preprocessor blocks table.
145    if (V.isFile()) {
146      ::Emit32(Out, E.getTokenOffset());
147      ::Emit32(Out, E.getPPCondTableOffset());
148    }
149
150    // Emit any other data associated with the key (i.e., stat information).
151    V.EmitData(Out);
152  }
153};
154
155class OffsetOpt {
156  bool valid;
157  Offset off;
158public:
159  OffsetOpt() : valid(false) {}
160  bool hasOffset() const { return valid; }
161  Offset getOffset() const { assert(valid); return off; }
162  void setOffset(Offset o) { off = o; valid = true; }
163};
164} // end anonymous namespace
165
166typedef OnDiskChainedHashTableGenerator<FileEntryPTHEntryInfo> PTHMap;
167
168namespace {
169class PTHWriter {
170  typedef llvm::DenseMap<const IdentifierInfo*,uint32_t> IDMap;
171  typedef llvm::StringMap<OffsetOpt, llvm::BumpPtrAllocator> CachedStrsTy;
172
173  IDMap IM;
174  llvm::raw_fd_ostream& Out;
175  Preprocessor& PP;
176  uint32_t idcount;
177  PTHMap PM;
178  CachedStrsTy CachedStrs;
179  Offset CurStrOffset;
180  std::vector<llvm::StringMapEntry<OffsetOpt>*> StrEntries;
181
182  //// Get the persistent id for the given IdentifierInfo*.
183  uint32_t ResolveID(const IdentifierInfo* II);
184
185  /// Emit a token to the PTH file.
186  void EmitToken(const Token& T);
187
188  void Emit8(uint32_t V) { ::Emit8(Out, V); }
189
190  void Emit16(uint32_t V) { ::Emit16(Out, V); }
191
192  void Emit24(uint32_t V) { ::Emit24(Out, V); }
193
194  void Emit32(uint32_t V) { ::Emit32(Out, V); }
195
196  void EmitBuf(const char *Ptr, unsigned NumBytes) {
197    Out.write(Ptr, NumBytes);
198  }
199
200  void EmitString(llvm::StringRef V) {
201    ::Emit16(Out, V.size());
202    EmitBuf(V.data(), V.size());
203  }
204
205  /// EmitIdentifierTable - Emits two tables to the PTH file.  The first is
206  ///  a hashtable mapping from identifier strings to persistent IDs.
207  ///  The second is a straight table mapping from persistent IDs to string data
208  ///  (the keys of the first table).
209  std::pair<Offset, Offset> EmitIdentifierTable();
210
211  /// EmitFileTable - Emit a table mapping from file name strings to PTH
212  /// token data.
213  Offset EmitFileTable() { return PM.Emit(Out); }
214
215  PTHEntry LexTokens(Lexer& L);
216  Offset EmitCachedSpellings();
217
218public:
219  PTHWriter(llvm::raw_fd_ostream& out, Preprocessor& pp)
220    : Out(out), PP(pp), idcount(0), CurStrOffset(0) {}
221
222  PTHMap &getPM() { return PM; }
223  void GeneratePTH(const std::string &MainFile);
224};
225} // end anonymous namespace
226
227uint32_t PTHWriter::ResolveID(const IdentifierInfo* II) {
228  // Null IdentifierInfo's map to the persistent ID 0.
229  if (!II)
230    return 0;
231
232  IDMap::iterator I = IM.find(II);
233  if (I != IM.end())
234    return I->second; // We've already added 1.
235
236  IM[II] = ++idcount; // Pre-increment since '0' is reserved for NULL.
237  return idcount;
238}
239
240void PTHWriter::EmitToken(const Token& T) {
241  // Emit the token kind, flags, and length.
242  Emit32(((uint32_t) T.getKind()) | ((((uint32_t) T.getFlags())) << 8)|
243         (((uint32_t) T.getLength()) << 16));
244
245  if (!T.isLiteral()) {
246    Emit32(ResolveID(T.getIdentifierInfo()));
247  } else {
248    // We cache *un-cleaned* spellings. This gives us 100% fidelity with the
249    // source code.
250    const char* s = T.getLiteralData();
251    unsigned len = T.getLength();
252
253    // Get the string entry.
254    llvm::StringMapEntry<OffsetOpt> *E = &CachedStrs.GetOrCreateValue(s, s+len);
255
256    // If this is a new string entry, bump the PTH offset.
257    if (!E->getValue().hasOffset()) {
258      E->getValue().setOffset(CurStrOffset);
259      StrEntries.push_back(E);
260      CurStrOffset += len + 1;
261    }
262
263    // Emit the relative offset into the PTH file for the spelling string.
264    Emit32(E->getValue().getOffset());
265  }
266
267  // Emit the offset into the original source file of this token so that we
268  // can reconstruct its SourceLocation.
269  Emit32(PP.getSourceManager().getFileOffset(T.getLocation()));
270}
271
272PTHEntry PTHWriter::LexTokens(Lexer& L) {
273  // Pad 0's so that we emit tokens to a 4-byte alignment.
274  // This speed up reading them back in.
275  Pad(Out, 4);
276  Offset TokenOff = (Offset) Out.tell();
277
278  // Keep track of matching '#if' ... '#endif'.
279  typedef std::vector<std::pair<Offset, unsigned> > PPCondTable;
280  PPCondTable PPCond;
281  std::vector<unsigned> PPStartCond;
282  bool ParsingPreprocessorDirective = false;
283  Token Tok;
284
285  do {
286    L.LexFromRawLexer(Tok);
287  NextToken:
288
289    if ((Tok.isAtStartOfLine() || Tok.is(tok::eof)) &&
290        ParsingPreprocessorDirective) {
291      // Insert an eom token into the token cache.  It has the same
292      // position as the next token that is not on the same line as the
293      // preprocessor directive.  Observe that we continue processing
294      // 'Tok' when we exit this branch.
295      Token Tmp = Tok;
296      Tmp.setKind(tok::eom);
297      Tmp.clearFlag(Token::StartOfLine);
298      Tmp.setIdentifierInfo(0);
299      EmitToken(Tmp);
300      ParsingPreprocessorDirective = false;
301    }
302
303    if (Tok.is(tok::identifier)) {
304      PP.LookUpIdentifierInfo(Tok);
305      EmitToken(Tok);
306      continue;
307    }
308
309    if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
310      // Special processing for #include.  Store the '#' token and lex
311      // the next token.
312      assert(!ParsingPreprocessorDirective);
313      Offset HashOff = (Offset) Out.tell();
314      EmitToken(Tok);
315
316      // Get the next token.
317      L.LexFromRawLexer(Tok);
318
319      // If we see the start of line, then we had a null directive "#".
320      if (Tok.isAtStartOfLine())
321        goto NextToken;
322
323      // Did we see 'include'/'import'/'include_next'?
324      if (Tok.isNot(tok::identifier)) {
325        EmitToken(Tok);
326        continue;
327      }
328
329      IdentifierInfo* II = PP.LookUpIdentifierInfo(Tok);
330      tok::PPKeywordKind K = II->getPPKeywordID();
331
332      ParsingPreprocessorDirective = true;
333
334      switch (K) {
335      case tok::pp_not_keyword:
336        // Invalid directives "#foo" can occur in #if 0 blocks etc, just pass
337        // them through.
338      default:
339        break;
340
341      case tok::pp_include:
342      case tok::pp_import:
343      case tok::pp_include_next: {
344        // Save the 'include' token.
345        EmitToken(Tok);
346        // Lex the next token as an include string.
347        L.setParsingPreprocessorDirective(true);
348        L.LexIncludeFilename(Tok);
349        L.setParsingPreprocessorDirective(false);
350        assert(!Tok.isAtStartOfLine());
351        if (Tok.is(tok::identifier))
352          PP.LookUpIdentifierInfo(Tok);
353
354        break;
355      }
356      case tok::pp_if:
357      case tok::pp_ifdef:
358      case tok::pp_ifndef: {
359        // Add an entry for '#if' and friends.  We initially set the target
360        // index to 0.  This will get backpatched when we hit #endif.
361        PPStartCond.push_back(PPCond.size());
362        PPCond.push_back(std::make_pair(HashOff, 0U));
363        break;
364      }
365      case tok::pp_endif: {
366        // Add an entry for '#endif'.  We set the target table index to itself.
367        // This will later be set to zero when emitting to the PTH file.  We
368        // use 0 for uninitialized indices because that is easier to debug.
369        unsigned index = PPCond.size();
370        // Backpatch the opening '#if' entry.
371        assert(!PPStartCond.empty());
372        assert(PPCond.size() > PPStartCond.back());
373        assert(PPCond[PPStartCond.back()].second == 0);
374        PPCond[PPStartCond.back()].second = index;
375        PPStartCond.pop_back();
376        // Add the new entry to PPCond.
377        PPCond.push_back(std::make_pair(HashOff, index));
378        EmitToken(Tok);
379
380        // Some files have gibberish on the same line as '#endif'.
381        // Discard these tokens.
382        do
383          L.LexFromRawLexer(Tok);
384        while (Tok.isNot(tok::eof) && !Tok.isAtStartOfLine());
385        // We have the next token in hand.
386        // Don't immediately lex the next one.
387        goto NextToken;
388      }
389      case tok::pp_elif:
390      case tok::pp_else: {
391        // Add an entry for #elif or #else.
392        // This serves as both a closing and opening of a conditional block.
393        // This means that its entry will get backpatched later.
394        unsigned index = PPCond.size();
395        // Backpatch the previous '#if' entry.
396        assert(!PPStartCond.empty());
397        assert(PPCond.size() > PPStartCond.back());
398        assert(PPCond[PPStartCond.back()].second == 0);
399        PPCond[PPStartCond.back()].second = index;
400        PPStartCond.pop_back();
401        // Now add '#elif' as a new block opening.
402        PPCond.push_back(std::make_pair(HashOff, 0U));
403        PPStartCond.push_back(index);
404        break;
405      }
406      }
407    }
408
409    EmitToken(Tok);
410  }
411  while (Tok.isNot(tok::eof));
412
413  assert(PPStartCond.empty() && "Error: imblanced preprocessor conditionals.");
414
415  // Next write out PPCond.
416  Offset PPCondOff = (Offset) Out.tell();
417
418  // Write out the size of PPCond so that clients can identifer empty tables.
419  Emit32(PPCond.size());
420
421  for (unsigned i = 0, e = PPCond.size(); i!=e; ++i) {
422    Emit32(PPCond[i].first - TokenOff);
423    uint32_t x = PPCond[i].second;
424    assert(x != 0 && "PPCond entry not backpatched.");
425    // Emit zero for #endifs.  This allows us to do checking when
426    // we read the PTH file back in.
427    Emit32(x == i ? 0 : x);
428  }
429
430  return PTHEntry(TokenOff, PPCondOff);
431}
432
433Offset PTHWriter::EmitCachedSpellings() {
434  // Write each cached strings to the PTH file.
435  Offset SpellingsOff = Out.tell();
436
437  for (std::vector<llvm::StringMapEntry<OffsetOpt>*>::iterator
438       I = StrEntries.begin(), E = StrEntries.end(); I!=E; ++I)
439    EmitBuf((*I)->getKeyData(), (*I)->getKeyLength()+1 /*nul included*/);
440
441  return SpellingsOff;
442}
443
444void PTHWriter::GeneratePTH(const std::string &MainFile) {
445  // Generate the prologue.
446  Out << "cfe-pth";
447  Emit32(PTHManager::Version);
448
449  // Leave 4 words for the prologue.
450  Offset PrologueOffset = Out.tell();
451  for (unsigned i = 0; i < 4; ++i)
452    Emit32(0);
453
454  // Write the name of the MainFile.
455  if (!MainFile.empty()) {
456    EmitString(MainFile);
457  } else {
458    // String with 0 bytes.
459    Emit16(0);
460  }
461  Emit8(0);
462
463  // Iterate over all the files in SourceManager.  Create a lexer
464  // for each file and cache the tokens.
465  SourceManager &SM = PP.getSourceManager();
466  const LangOptions &LOpts = PP.getLangOptions();
467
468  for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
469       E = SM.fileinfo_end(); I != E; ++I) {
470    const SrcMgr::ContentCache &C = *I->second;
471    const FileEntry *FE = C.Entry;
472
473    // FIXME: Handle files with non-absolute paths.
474    llvm::sys::Path P(FE->getName());
475    if (!P.isAbsolute())
476      continue;
477
478    const llvm::MemoryBuffer *B = C.getBuffer(PP.getDiagnostics());
479    if (!B) continue;
480
481    FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
482    const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
483    Lexer L(FID, FromFile, SM, LOpts);
484    PM.insert(FE, LexTokens(L));
485  }
486
487  // Write out the identifier table.
488  const std::pair<Offset,Offset> &IdTableOff = EmitIdentifierTable();
489
490  // Write out the cached strings table.
491  Offset SpellingOff = EmitCachedSpellings();
492
493  // Write out the file table.
494  Offset FileTableOff = EmitFileTable();
495
496  // Finally, write the prologue.
497  Out.seek(PrologueOffset);
498  Emit32(IdTableOff.first);
499  Emit32(IdTableOff.second);
500  Emit32(FileTableOff);
501  Emit32(SpellingOff);
502}
503
504namespace {
505/// StatListener - A simple "interpose" object used to monitor stat calls
506/// invoked by FileManager while processing the original sources used
507/// as input to PTH generation.  StatListener populates the PTHWriter's
508/// file map with stat information for directories as well as negative stats.
509/// Stat information for files are populated elsewhere.
510class StatListener : public StatSysCallCache {
511  PTHMap &PM;
512public:
513  StatListener(PTHMap &pm) : PM(pm) {}
514  ~StatListener() {}
515
516  int stat(const char *path, struct stat *buf) {
517    int result = StatSysCallCache::stat(path, buf);
518
519    if (result != 0) // Failed 'stat'.
520      PM.insert(PTHEntryKeyVariant(path), PTHEntry());
521    else if (S_ISDIR(buf->st_mode)) {
522      // Only cache directories with absolute paths.
523      if (!llvm::sys::Path(path).isAbsolute())
524        return result;
525
526      PM.insert(PTHEntryKeyVariant(buf, path), PTHEntry());
527    }
528
529    return result;
530  }
531};
532} // end anonymous namespace
533
534
535void clang::CacheTokens(Preprocessor &PP, llvm::raw_fd_ostream* OS) {
536  // Get the name of the main file.
537  const SourceManager &SrcMgr = PP.getSourceManager();
538  const FileEntry *MainFile = SrcMgr.getFileEntryForID(SrcMgr.getMainFileID());
539  llvm::sys::Path MainFilePath(MainFile->getName());
540
541  MainFilePath.makeAbsolute();
542
543  // Create the PTHWriter.
544  PTHWriter PW(*OS, PP);
545
546  // Install the 'stat' system call listener in the FileManager.
547  StatListener *StatCache = new StatListener(PW.getPM());
548  PP.getFileManager().addStatCache(StatCache, /*AtBeginning=*/true);
549
550  // Lex through the entire file.  This will populate SourceManager with
551  // all of the header information.
552  Token Tok;
553  if (PP.EnterMainSourceFile())
554    return;
555  do { PP.Lex(Tok); } while (Tok.isNot(tok::eof));
556
557  // Generate the PTH file.
558  PP.getFileManager().removeStatCache(StatCache);
559  PW.GeneratePTH(MainFilePath.str());
560}
561
562//===----------------------------------------------------------------------===//
563
564namespace {
565class PTHIdKey {
566public:
567  const IdentifierInfo* II;
568  uint32_t FileOffset;
569};
570
571class PTHIdentifierTableTrait {
572public:
573  typedef PTHIdKey* key_type;
574  typedef key_type  key_type_ref;
575
576  typedef uint32_t  data_type;
577  typedef data_type data_type_ref;
578
579  static unsigned ComputeHash(PTHIdKey* key) {
580    return llvm::HashString(key->II->getName());
581  }
582
583  static std::pair<unsigned,unsigned>
584  EmitKeyDataLength(llvm::raw_ostream& Out, const PTHIdKey* key, uint32_t) {
585    unsigned n = key->II->getLength() + 1;
586    ::Emit16(Out, n);
587    return std::make_pair(n, sizeof(uint32_t));
588  }
589
590  static void EmitKey(llvm::raw_ostream& Out, PTHIdKey* key, unsigned n) {
591    // Record the location of the key data.  This is used when generating
592    // the mapping from persistent IDs to strings.
593    key->FileOffset = Out.tell();
594    Out.write(key->II->getNameStart(), n);
595  }
596
597  static void EmitData(llvm::raw_ostream& Out, PTHIdKey*, uint32_t pID,
598                       unsigned) {
599    ::Emit32(Out, pID);
600  }
601};
602} // end anonymous namespace
603
604/// EmitIdentifierTable - Emits two tables to the PTH file.  The first is
605///  a hashtable mapping from identifier strings to persistent IDs.  The second
606///  is a straight table mapping from persistent IDs to string data (the
607///  keys of the first table).
608///
609std::pair<Offset,Offset> PTHWriter::EmitIdentifierTable() {
610  // Build two maps:
611  //  (1) an inverse map from persistent IDs -> (IdentifierInfo*,Offset)
612  //  (2) a map from (IdentifierInfo*, Offset)* -> persistent IDs
613
614  // Note that we use 'calloc', so all the bytes are 0.
615  PTHIdKey *IIDMap = (PTHIdKey*)calloc(idcount, sizeof(PTHIdKey));
616
617  // Create the hashtable.
618  OnDiskChainedHashTableGenerator<PTHIdentifierTableTrait> IIOffMap;
619
620  // Generate mapping from persistent IDs -> IdentifierInfo*.
621  for (IDMap::iterator I = IM.begin(), E = IM.end(); I != E; ++I) {
622    // Decrement by 1 because we are using a vector for the lookup and
623    // 0 is reserved for NULL.
624    assert(I->second > 0);
625    assert(I->second-1 < idcount);
626    unsigned idx = I->second-1;
627
628    // Store the mapping from persistent ID to IdentifierInfo*
629    IIDMap[idx].II = I->first;
630
631    // Store the reverse mapping in a hashtable.
632    IIOffMap.insert(&IIDMap[idx], I->second);
633  }
634
635  // Write out the inverse map first.  This causes the PCIDKey entries to
636  // record PTH file offsets for the string data.  This is used to write
637  // the second table.
638  Offset StringTableOffset = IIOffMap.Emit(Out);
639
640  // Now emit the table mapping from persistent IDs to PTH file offsets.
641  Offset IDOff = Out.tell();
642  Emit32(idcount);  // Emit the number of identifiers.
643  for (unsigned i = 0 ; i < idcount; ++i)
644    Emit32(IIDMap[i].FileOffset);
645
646  // Finally, release the inverse map.
647  free(IIDMap);
648
649  return std::make_pair(IDOff, StringTableOffset);
650}
651