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