1 //===--- ASTWriter.h - AST File Writer --------------------------*- C++ -*-===// 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 file defines the ASTWriter class, which writes an AST file 11 // containing a serialized representation of a translation unit. 12 // 13 //===----------------------------------------------------------------------===// 14 #ifndef LLVM_CLANG_FRONTEND_AST_WRITER_H 15 #define LLVM_CLANG_FRONTEND_AST_WRITER_H 16 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclarationName.h" 20 #include "clang/AST/TemplateBase.h" 21 #include "clang/Sema/SemaConsumer.h" 22 #include "clang/Serialization/ASTBitCodes.h" 23 #include "clang/Serialization/ASTDeserializationListener.h" 24 #include "llvm/ADT/DenseMap.h" 25 #include "llvm/ADT/DenseSet.h" 26 #include "llvm/ADT/MapVector.h" 27 #include "llvm/ADT/SetVector.h" 28 #include "llvm/ADT/SmallPtrSet.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/Bitcode/BitstreamWriter.h" 31 #include <map> 32 #include <queue> 33 #include <vector> 34 35 namespace llvm { 36 class APFloat; 37 class APInt; 38 class BitstreamWriter; 39 } 40 41 namespace clang { 42 43 class ASTContext; 44 class NestedNameSpecifier; 45 class CXXBaseSpecifier; 46 class CXXCtorInitializer; 47 class FileEntry; 48 class FPOptions; 49 class HeaderSearch; 50 class HeaderSearchOptions; 51 class IdentifierResolver; 52 class MacroDefinition; 53 class MacroDirective; 54 class MacroInfo; 55 class OpaqueValueExpr; 56 class OpenCLOptions; 57 class ASTReader; 58 class Module; 59 class PreprocessedEntity; 60 class PreprocessingRecord; 61 class Preprocessor; 62 class Sema; 63 class SourceManager; 64 class SwitchCase; 65 class TargetInfo; 66 class Token; 67 class VersionTuple; 68 class ASTUnresolvedSet; 69 70 namespace SrcMgr { class SLocEntry; } 71 72 /// \brief Writes an AST file containing the contents of a translation unit. 73 /// 74 /// The ASTWriter class produces a bitstream containing the serialized 75 /// representation of a given abstract syntax tree and its supporting 76 /// data structures. This bitstream can be de-serialized via an 77 /// instance of the ASTReader class. 78 class ASTWriter : public ASTDeserializationListener, 79 public ASTMutationListener { 80 public: 81 typedef SmallVector<uint64_t, 64> RecordData; 82 typedef SmallVectorImpl<uint64_t> RecordDataImpl; 83 84 friend class ASTDeclWriter; 85 friend class ASTStmtWriter; 86 private: 87 /// \brief Map that provides the ID numbers of each type within the 88 /// output stream, plus those deserialized from a chained PCH. 89 /// 90 /// The ID numbers of types are consecutive (in order of discovery) 91 /// and start at 1. 0 is reserved for NULL. When types are actually 92 /// stored in the stream, the ID number is shifted by 2 bits to 93 /// allow for the const/volatile qualifiers. 94 /// 95 /// Keys in the map never have const/volatile qualifiers. 96 typedef llvm::DenseMap<QualType, serialization::TypeIdx, 97 serialization::UnsafeQualTypeDenseMapInfo> 98 TypeIdxMap; 99 100 /// \brief The bitstream writer used to emit this precompiled header. 101 llvm::BitstreamWriter &Stream; 102 103 /// \brief The ASTContext we're writing. 104 ASTContext *Context; 105 106 /// \brief The preprocessor we're writing. 107 Preprocessor *PP; 108 109 /// \brief The reader of existing AST files, if we're chaining. 110 ASTReader *Chain; 111 112 /// \brief The module we're currently writing, if any. 113 Module *WritingModule; 114 115 /// \brief Indicates when the AST writing is actively performing 116 /// serialization, rather than just queueing updates. 117 bool WritingAST; 118 119 /// \brief Indicates that we are done serializing the collection of decls 120 /// and types to emit. 121 bool DoneWritingDeclsAndTypes; 122 123 /// \brief Indicates that the AST contained compiler errors. 124 bool ASTHasCompilerErrors; 125 126 /// \brief Mapping from input file entries to the index into the 127 /// offset table where information about that input file is stored. 128 llvm::DenseMap<const FileEntry *, uint32_t> InputFileIDs; 129 130 /// \brief Stores a declaration or a type to be written to the AST file. 131 class DeclOrType { 132 public: 133 DeclOrType(Decl *D) : Stored(D), IsType(false) { } 134 DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { } 135 136 bool isType() const { return IsType; } 137 bool isDecl() const { return !IsType; } 138 139 QualType getType() const { 140 assert(isType() && "Not a type!"); 141 return QualType::getFromOpaquePtr(Stored); 142 } 143 144 Decl *getDecl() const { 145 assert(isDecl() && "Not a decl!"); 146 return static_cast<Decl *>(Stored); 147 } 148 149 private: 150 void *Stored; 151 bool IsType; 152 }; 153 154 /// \brief The declarations and types to emit. 155 std::queue<DeclOrType> DeclTypesToEmit; 156 157 /// \brief The first ID number we can use for our own declarations. 158 serialization::DeclID FirstDeclID; 159 160 /// \brief The decl ID that will be assigned to the next new decl. 161 serialization::DeclID NextDeclID; 162 163 /// \brief Map that provides the ID numbers of each declaration within 164 /// the output stream, as well as those deserialized from a chained PCH. 165 /// 166 /// The ID numbers of declarations are consecutive (in order of 167 /// discovery) and start at 2. 1 is reserved for the translation 168 /// unit, while 0 is reserved for NULL. 169 llvm::DenseMap<const Decl *, serialization::DeclID> DeclIDs; 170 171 /// \brief Offset of each declaration in the bitstream, indexed by 172 /// the declaration's ID. 173 std::vector<serialization::DeclOffset> DeclOffsets; 174 175 /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID. 176 typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64> 177 LocDeclIDsTy; 178 struct DeclIDInFileInfo { 179 LocDeclIDsTy DeclIDs; 180 /// \brief Set when the DeclIDs vectors from all files are joined, this 181 /// indicates the index that this particular vector has in the global one. 182 unsigned FirstDeclIndex; 183 }; 184 typedef llvm::DenseMap<FileID, DeclIDInFileInfo *> FileDeclIDsTy; 185 186 /// \brief Map from file SLocEntries to info about the file-level declarations 187 /// that it contains. 188 FileDeclIDsTy FileDeclIDs; 189 190 void associateDeclWithFile(const Decl *D, serialization::DeclID); 191 192 /// \brief The first ID number we can use for our own types. 193 serialization::TypeID FirstTypeID; 194 195 /// \brief The type ID that will be assigned to the next new type. 196 serialization::TypeID NextTypeID; 197 198 /// \brief Map that provides the ID numbers of each type within the 199 /// output stream, plus those deserialized from a chained PCH. 200 /// 201 /// The ID numbers of types are consecutive (in order of discovery) 202 /// and start at 1. 0 is reserved for NULL. When types are actually 203 /// stored in the stream, the ID number is shifted by 2 bits to 204 /// allow for the const/volatile qualifiers. 205 /// 206 /// Keys in the map never have const/volatile qualifiers. 207 TypeIdxMap TypeIdxs; 208 209 /// \brief Offset of each type in the bitstream, indexed by 210 /// the type's ID. 211 std::vector<uint32_t> TypeOffsets; 212 213 /// \brief The first ID number we can use for our own identifiers. 214 serialization::IdentID FirstIdentID; 215 216 /// \brief The identifier ID that will be assigned to the next new identifier. 217 serialization::IdentID NextIdentID; 218 219 /// \brief Map that provides the ID numbers of each identifier in 220 /// the output stream. 221 /// 222 /// The ID numbers for identifiers are consecutive (in order of 223 /// discovery), starting at 1. An ID of zero refers to a NULL 224 /// IdentifierInfo. 225 llvm::DenseMap<const IdentifierInfo *, serialization::IdentID> IdentifierIDs; 226 227 /// \brief The first ID number we can use for our own macros. 228 serialization::MacroID FirstMacroID; 229 230 /// \brief The identifier ID that will be assigned to the next new identifier. 231 serialization::MacroID NextMacroID; 232 233 /// \brief Map that provides the ID numbers of each macro. 234 llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs; 235 236 struct MacroInfoToEmitData { 237 const IdentifierInfo *Name; 238 MacroInfo *MI; 239 serialization::MacroID ID; 240 }; 241 /// \brief The macro infos to emit. 242 std::vector<MacroInfoToEmitData> MacroInfosToEmit; 243 244 llvm::DenseMap<const IdentifierInfo *, uint64_t> IdentMacroDirectivesOffsetMap; 245 246 /// @name FlushStmt Caches 247 /// @{ 248 249 /// \brief Set of parent Stmts for the currently serializing sub-stmt. 250 llvm::DenseSet<Stmt *> ParentStmts; 251 252 /// \brief Offsets of sub-stmts already serialized. The offset points 253 /// just after the stmt record. 254 llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries; 255 256 /// @} 257 258 /// \brief Offsets of each of the identifier IDs into the identifier 259 /// table. 260 std::vector<uint32_t> IdentifierOffsets; 261 262 /// \brief The first ID number we can use for our own submodules. 263 serialization::SubmoduleID FirstSubmoduleID; 264 265 /// \brief The submodule ID that will be assigned to the next new submodule. 266 serialization::SubmoduleID NextSubmoduleID; 267 268 /// \brief The first ID number we can use for our own selectors. 269 serialization::SelectorID FirstSelectorID; 270 271 /// \brief The selector ID that will be assigned to the next new selector. 272 serialization::SelectorID NextSelectorID; 273 274 /// \brief Map that provides the ID numbers of each Selector. 275 llvm::DenseMap<Selector, serialization::SelectorID> SelectorIDs; 276 277 /// \brief Offset of each selector within the method pool/selector 278 /// table, indexed by the Selector ID (-1). 279 std::vector<uint32_t> SelectorOffsets; 280 281 /// \brief Mapping from macro definitions (as they occur in the preprocessing 282 /// record) to the macro IDs. 283 llvm::DenseMap<const MacroDefinition *, serialization::PreprocessedEntityID> 284 MacroDefinitions; 285 286 /// An update to a Decl. 287 class DeclUpdate { 288 /// A DeclUpdateKind. 289 unsigned Kind; 290 union { 291 const Decl *Dcl; 292 void *Type; 293 unsigned Loc; 294 unsigned Val; 295 }; 296 297 public: 298 DeclUpdate(unsigned Kind) : Kind(Kind), Dcl(nullptr) {} 299 DeclUpdate(unsigned Kind, const Decl *Dcl) : Kind(Kind), Dcl(Dcl) {} 300 DeclUpdate(unsigned Kind, QualType Type) 301 : Kind(Kind), Type(Type.getAsOpaquePtr()) {} 302 DeclUpdate(unsigned Kind, SourceLocation Loc) 303 : Kind(Kind), Loc(Loc.getRawEncoding()) {} 304 DeclUpdate(unsigned Kind, unsigned Val) 305 : Kind(Kind), Val(Val) {} 306 307 unsigned getKind() const { return Kind; } 308 const Decl *getDecl() const { return Dcl; } 309 QualType getType() const { return QualType::getFromOpaquePtr(Type); } 310 SourceLocation getLoc() const { 311 return SourceLocation::getFromRawEncoding(Loc); 312 } 313 unsigned getNumber() const { return Val; } 314 }; 315 316 typedef SmallVector<DeclUpdate, 1> UpdateRecord; 317 typedef llvm::DenseMap<const Decl *, UpdateRecord> DeclUpdateMap; 318 /// \brief Mapping from declarations that came from a chained PCH to the 319 /// record containing modifications to them. 320 DeclUpdateMap DeclUpdates; 321 322 typedef llvm::DenseMap<Decl *, Decl *> FirstLatestDeclMap; 323 /// \brief Map of first declarations from a chained PCH that point to the 324 /// most recent declarations in another PCH. 325 FirstLatestDeclMap FirstLatestDecls; 326 327 /// \brief Declarations encountered that might be external 328 /// definitions. 329 /// 330 /// We keep track of external definitions and other 'interesting' declarations 331 /// as we are emitting declarations to the AST file. The AST file contains a 332 /// separate record for these declarations, which are provided to the AST 333 /// consumer by the AST reader. This is behavior is required to properly cope with, 334 /// e.g., tentative variable definitions that occur within 335 /// headers. The declarations themselves are stored as declaration 336 /// IDs, since they will be written out to an EAGERLY_DESERIALIZED_DECLS 337 /// record. 338 SmallVector<uint64_t, 16> EagerlyDeserializedDecls; 339 340 /// \brief DeclContexts that have received extensions since their serialized 341 /// form. 342 /// 343 /// For namespaces, when we're chaining and encountering a namespace, we check 344 /// if its primary namespace comes from the chain. If it does, we add the 345 /// primary to this set, so that we can write out lexical content updates for 346 /// it. 347 llvm::SmallPtrSet<const DeclContext *, 16> UpdatedDeclContexts; 348 349 /// \brief Keeps track of visible decls that were added in DeclContexts 350 /// coming from another AST file. 351 SmallVector<const Decl *, 16> UpdatingVisibleDecls; 352 353 typedef llvm::SmallPtrSet<const Decl *, 16> DeclsToRewriteTy; 354 /// \brief Decls that will be replaced in the current dependent AST file. 355 DeclsToRewriteTy DeclsToRewrite; 356 357 /// \brief The set of Objective-C class that have categories we 358 /// should serialize. 359 llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories; 360 361 struct ReplacedDeclInfo { 362 serialization::DeclID ID; 363 uint64_t Offset; 364 unsigned Loc; 365 366 ReplacedDeclInfo() : ID(0), Offset(0), Loc(0) {} 367 ReplacedDeclInfo(serialization::DeclID ID, uint64_t Offset, 368 SourceLocation Loc) 369 : ID(ID), Offset(Offset), Loc(Loc.getRawEncoding()) {} 370 }; 371 372 /// \brief Decls that have been replaced in the current dependent AST file. 373 /// 374 /// When a decl changes fundamentally after being deserialized (this shouldn't 375 /// happen, but the ObjC AST nodes are designed this way), it will be 376 /// serialized again. In this case, it is registered here, so that the reader 377 /// knows to read the updated version. 378 SmallVector<ReplacedDeclInfo, 16> ReplacedDecls; 379 380 /// \brief The set of declarations that may have redeclaration chains that 381 /// need to be serialized. 382 llvm::SetVector<Decl *, SmallVector<Decl *, 4>, 383 llvm::SmallPtrSet<Decl *, 4> > Redeclarations; 384 385 /// \brief Statements that we've encountered while serializing a 386 /// declaration or type. 387 SmallVector<Stmt *, 16> StmtsToEmit; 388 389 /// \brief Statements collection to use for ASTWriter::AddStmt(). 390 /// It will point to StmtsToEmit unless it is overriden. 391 SmallVector<Stmt *, 16> *CollectedStmts; 392 393 /// \brief Mapping from SwitchCase statements to IDs. 394 llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs; 395 396 /// \brief The number of statements written to the AST file. 397 unsigned NumStatements; 398 399 /// \brief The number of macros written to the AST file. 400 unsigned NumMacros; 401 402 /// \brief The number of lexical declcontexts written to the AST 403 /// file. 404 unsigned NumLexicalDeclContexts; 405 406 /// \brief The number of visible declcontexts written to the AST 407 /// file. 408 unsigned NumVisibleDeclContexts; 409 410 /// \brief The offset of each CXXBaseSpecifier set within the AST. 411 SmallVector<uint32_t, 4> CXXBaseSpecifiersOffsets; 412 413 /// \brief The first ID number we can use for our own base specifiers. 414 serialization::CXXBaseSpecifiersID FirstCXXBaseSpecifiersID; 415 416 /// \brief The base specifiers ID that will be assigned to the next new 417 /// set of C++ base specifiers. 418 serialization::CXXBaseSpecifiersID NextCXXBaseSpecifiersID; 419 420 /// \brief A set of C++ base specifiers that is queued to be written into the 421 /// AST file. 422 struct QueuedCXXBaseSpecifiers { 423 QueuedCXXBaseSpecifiers() : ID(), Bases(), BasesEnd() { } 424 425 QueuedCXXBaseSpecifiers(serialization::CXXBaseSpecifiersID ID, 426 CXXBaseSpecifier const *Bases, 427 CXXBaseSpecifier const *BasesEnd) 428 : ID(ID), Bases(Bases), BasesEnd(BasesEnd) { } 429 430 serialization::CXXBaseSpecifiersID ID; 431 CXXBaseSpecifier const * Bases; 432 CXXBaseSpecifier const * BasesEnd; 433 }; 434 435 /// \brief Queue of C++ base specifiers to be written to the AST file, 436 /// in the order they should be written. 437 SmallVector<QueuedCXXBaseSpecifiers, 2> CXXBaseSpecifiersToWrite; 438 439 /// \brief A mapping from each known submodule to its ID number, which will 440 /// be a positive integer. 441 llvm::DenseMap<Module *, unsigned> SubmoduleIDs; 442 443 /// \brief Retrieve or create a submodule ID for this module. 444 unsigned getSubmoduleID(Module *Mod); 445 446 /// \brief Write the given subexpression to the bitstream. 447 void WriteSubStmt(Stmt *S, 448 llvm::DenseMap<Stmt *, uint64_t> &SubStmtEntries, 449 llvm::DenseSet<Stmt *> &ParentStmts); 450 451 void WriteBlockInfoBlock(); 452 void WriteControlBlock(Preprocessor &PP, ASTContext &Context, 453 StringRef isysroot, const std::string &OutputFile); 454 void WriteInputFiles(SourceManager &SourceMgr, 455 HeaderSearchOptions &HSOpts, 456 StringRef isysroot, 457 bool Modules); 458 void WriteSourceManagerBlock(SourceManager &SourceMgr, 459 const Preprocessor &PP, 460 StringRef isysroot); 461 void WritePreprocessor(const Preprocessor &PP, bool IsModule); 462 void WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot); 463 void WritePreprocessorDetail(PreprocessingRecord &PPRec); 464 void WriteSubmodules(Module *WritingModule); 465 466 void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag, 467 bool isModule); 468 void WriteCXXBaseSpecifiersOffsets(); 469 void WriteType(QualType T); 470 uint32_t GenerateNameLookupTable(const DeclContext *DC, 471 llvm::SmallVectorImpl<char> &LookupTable); 472 uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC); 473 uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC); 474 void WriteTypeDeclOffsets(); 475 void WriteFileDeclIDsMap(); 476 void WriteComments(); 477 void WriteSelectors(Sema &SemaRef); 478 void WriteReferencedSelectorsPool(Sema &SemaRef); 479 void WriteIdentifierTable(Preprocessor &PP, IdentifierResolver &IdResolver, 480 bool IsModule); 481 void WriteAttributes(ArrayRef<const Attr*> Attrs, RecordDataImpl &Record); 482 void WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord); 483 void WriteDeclReplacementsBlock(); 484 void WriteDeclContextVisibleUpdate(const DeclContext *DC); 485 void WriteFPPragmaOptions(const FPOptions &Opts); 486 void WriteOpenCLExtensions(Sema &SemaRef); 487 void WriteObjCCategories(); 488 void WriteRedeclarations(); 489 void WriteMergedDecls(); 490 void WriteLateParsedTemplates(Sema &SemaRef); 491 void WriteOptimizePragmaOptions(Sema &SemaRef); 492 493 unsigned DeclParmVarAbbrev; 494 unsigned DeclContextLexicalAbbrev; 495 unsigned DeclContextVisibleLookupAbbrev; 496 unsigned UpdateVisibleAbbrev; 497 unsigned DeclRefExprAbbrev; 498 unsigned CharacterLiteralAbbrev; 499 unsigned DeclRecordAbbrev; 500 unsigned IntegerLiteralAbbrev; 501 unsigned DeclTypedefAbbrev; 502 unsigned DeclVarAbbrev; 503 unsigned DeclFieldAbbrev; 504 unsigned DeclEnumAbbrev; 505 unsigned DeclObjCIvarAbbrev; 506 507 void WriteDeclsBlockAbbrevs(); 508 void WriteDecl(ASTContext &Context, Decl *D); 509 void AddFunctionDefinition(const FunctionDecl *FD, RecordData &Record); 510 511 void WriteASTCore(Sema &SemaRef, 512 StringRef isysroot, const std::string &OutputFile, 513 Module *WritingModule); 514 515 public: 516 /// \brief Create a new precompiled header writer that outputs to 517 /// the given bitstream. 518 ASTWriter(llvm::BitstreamWriter &Stream); 519 ~ASTWriter(); 520 521 /// \brief Write a precompiled header for the given semantic analysis. 522 /// 523 /// \param SemaRef a reference to the semantic analysis object that processed 524 /// the AST to be written into the precompiled header. 525 /// 526 /// \param WritingModule The module that we are writing. If null, we are 527 /// writing a precompiled header. 528 /// 529 /// \param isysroot if non-empty, write a relocatable file whose headers 530 /// are relative to the given system root. 531 void WriteAST(Sema &SemaRef, 532 const std::string &OutputFile, 533 Module *WritingModule, StringRef isysroot, 534 bool hasErrors = false); 535 536 /// \brief Emit a token. 537 void AddToken(const Token &Tok, RecordDataImpl &Record); 538 539 /// \brief Emit a source location. 540 void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record); 541 542 /// \brief Emit a source range. 543 void AddSourceRange(SourceRange Range, RecordDataImpl &Record); 544 545 /// \brief Emit an integral value. 546 void AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record); 547 548 /// \brief Emit a signed integral value. 549 void AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record); 550 551 /// \brief Emit a floating-point value. 552 void AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record); 553 554 /// \brief Emit a reference to an identifier. 555 void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record); 556 557 /// \brief Emit a Selector (which is a smart pointer reference). 558 void AddSelectorRef(Selector, RecordDataImpl &Record); 559 560 /// \brief Emit a CXXTemporary. 561 void AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record); 562 563 /// \brief Emit a set of C++ base specifiers to the record. 564 void AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases, 565 CXXBaseSpecifier const *BasesEnd, 566 RecordDataImpl &Record); 567 568 /// \brief Get the unique number used to refer to the given selector. 569 serialization::SelectorID getSelectorRef(Selector Sel); 570 571 /// \brief Get the unique number used to refer to the given identifier. 572 serialization::IdentID getIdentifierRef(const IdentifierInfo *II); 573 574 /// \brief Get the unique number used to refer to the given macro. 575 serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name); 576 577 /// \brief Determine the ID of an already-emitted macro. 578 serialization::MacroID getMacroID(MacroInfo *MI); 579 580 uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name); 581 582 /// \brief Emit a reference to a type. 583 void AddTypeRef(QualType T, RecordDataImpl &Record); 584 585 /// \brief Force a type to be emitted and get its ID. 586 serialization::TypeID GetOrCreateTypeID(QualType T); 587 588 /// \brief Determine the type ID of an already-emitted type. 589 serialization::TypeID getTypeID(QualType T) const; 590 591 /// \brief Force a type to be emitted and get its index. 592 serialization::TypeIdx GetOrCreateTypeIdx( QualType T); 593 594 /// \brief Determine the type index of an already-emitted type. 595 serialization::TypeIdx getTypeIdx(QualType T) const; 596 597 /// \brief Emits a reference to a declarator info. 598 void AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordDataImpl &Record); 599 600 /// \brief Emits a type with source-location information. 601 void AddTypeLoc(TypeLoc TL, RecordDataImpl &Record); 602 603 /// \brief Emits a template argument location info. 604 void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind, 605 const TemplateArgumentLocInfo &Arg, 606 RecordDataImpl &Record); 607 608 /// \brief Emits a template argument location. 609 void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg, 610 RecordDataImpl &Record); 611 612 /// \brief Emits an AST template argument list info. 613 void AddASTTemplateArgumentListInfo( 614 const ASTTemplateArgumentListInfo *ASTTemplArgList, 615 RecordDataImpl &Record); 616 617 /// \brief Emit a reference to a declaration. 618 void AddDeclRef(const Decl *D, RecordDataImpl &Record); 619 620 621 /// \brief Force a declaration to be emitted and get its ID. 622 serialization::DeclID GetDeclRef(const Decl *D); 623 624 /// \brief Determine the declaration ID of an already-emitted 625 /// declaration. 626 serialization::DeclID getDeclID(const Decl *D); 627 628 /// \brief Emit a declaration name. 629 void AddDeclarationName(DeclarationName Name, RecordDataImpl &Record); 630 void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 631 DeclarationName Name, RecordDataImpl &Record); 632 void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 633 RecordDataImpl &Record); 634 635 void AddQualifierInfo(const QualifierInfo &Info, RecordDataImpl &Record); 636 637 /// \brief Emit a nested name specifier. 638 void AddNestedNameSpecifier(NestedNameSpecifier *NNS, RecordDataImpl &Record); 639 640 /// \brief Emit a nested name specifier with source-location information. 641 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 642 RecordDataImpl &Record); 643 644 /// \brief Emit a template name. 645 void AddTemplateName(TemplateName Name, RecordDataImpl &Record); 646 647 /// \brief Emit a template argument. 648 void AddTemplateArgument(const TemplateArgument &Arg, RecordDataImpl &Record); 649 650 /// \brief Emit a template parameter list. 651 void AddTemplateParameterList(const TemplateParameterList *TemplateParams, 652 RecordDataImpl &Record); 653 654 /// \brief Emit a template argument list. 655 void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs, 656 RecordDataImpl &Record); 657 658 /// \brief Emit a UnresolvedSet structure. 659 void AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record); 660 661 /// \brief Emit a C++ base specifier. 662 void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base, 663 RecordDataImpl &Record); 664 665 /// \brief Emit a CXXCtorInitializer array. 666 void AddCXXCtorInitializers( 667 const CXXCtorInitializer * const *CtorInitializers, 668 unsigned NumCtorInitializers, 669 RecordDataImpl &Record); 670 671 void AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record); 672 673 /// \brief Add a string to the given record. 674 void AddString(StringRef Str, RecordDataImpl &Record); 675 676 /// \brief Add a version tuple to the given record 677 void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record); 678 679 /// \brief Mark a declaration context as needing an update. 680 void AddUpdatedDeclContext(const DeclContext *DC); 681 682 void RewriteDecl(const Decl *D) { 683 DeclsToRewrite.insert(D); 684 } 685 686 bool isRewritten(const Decl *D) const { 687 return DeclsToRewrite.count(D); 688 } 689 690 /// \brief Infer the submodule ID that contains an entity at the given 691 /// source location. 692 serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc); 693 694 /// \brief Retrieve a submodule ID for this module. 695 /// Returns 0 If no ID has been associated with the module. 696 unsigned getExistingSubmoduleID(Module *Mod) const; 697 698 /// \brief Note that the identifier II occurs at the given offset 699 /// within the identifier table. 700 void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset); 701 702 /// \brief Note that the selector Sel occurs at the given offset 703 /// within the method pool/selector table. 704 void SetSelectorOffset(Selector Sel, uint32_t Offset); 705 706 /// \brief Add the given statement or expression to the queue of 707 /// statements to emit. 708 /// 709 /// This routine should be used when emitting types and declarations 710 /// that have expressions as part of their formulation. Once the 711 /// type or declaration has been written, call FlushStmts() to write 712 /// the corresponding statements just after the type or 713 /// declaration. 714 void AddStmt(Stmt *S) { 715 CollectedStmts->push_back(S); 716 } 717 718 /// \brief Flush all of the statements and expressions that have 719 /// been added to the queue via AddStmt(). 720 void FlushStmts(); 721 722 /// \brief Flush all of the C++ base specifier sets that have been added 723 /// via \c AddCXXBaseSpecifiersRef(). 724 void FlushCXXBaseSpecifiers(); 725 726 /// \brief Record an ID for the given switch-case statement. 727 unsigned RecordSwitchCaseID(SwitchCase *S); 728 729 /// \brief Retrieve the ID for the given switch-case statement. 730 unsigned getSwitchCaseID(SwitchCase *S); 731 732 void ClearSwitchCaseIDs(); 733 734 unsigned getDeclParmVarAbbrev() const { return DeclParmVarAbbrev; } 735 unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; } 736 unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; } 737 unsigned getDeclRecordAbbrev() const { return DeclRecordAbbrev; } 738 unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; } 739 unsigned getDeclTypedefAbbrev() const { return DeclTypedefAbbrev; } 740 unsigned getDeclVarAbbrev() const { return DeclVarAbbrev; } 741 unsigned getDeclFieldAbbrev() const { return DeclFieldAbbrev; } 742 unsigned getDeclEnumAbbrev() const { return DeclEnumAbbrev; } 743 unsigned getDeclObjCIvarAbbrev() const { return DeclObjCIvarAbbrev; } 744 745 bool hasChain() const { return Chain; } 746 747 // ASTDeserializationListener implementation 748 void ReaderInitialized(ASTReader *Reader) override; 749 void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II) override; 750 void MacroRead(serialization::MacroID ID, MacroInfo *MI) override; 751 void TypeRead(serialization::TypeIdx Idx, QualType T) override; 752 void SelectorRead(serialization::SelectorID ID, Selector Sel) override; 753 void MacroDefinitionRead(serialization::PreprocessedEntityID ID, 754 MacroDefinition *MD) override; 755 void ModuleRead(serialization::SubmoduleID ID, Module *Mod) override; 756 757 // ASTMutationListener implementation. 758 void CompletedTagDefinition(const TagDecl *D) override; 759 void AddedVisibleDecl(const DeclContext *DC, const Decl *D) override; 760 void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) override; 761 void AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD, 762 const ClassTemplateSpecializationDecl *D) override; 763 void AddedCXXTemplateSpecialization(const VarTemplateDecl *TD, 764 const VarTemplateSpecializationDecl *D) override; 765 void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, 766 const FunctionDecl *D) override; 767 void ResolvedExceptionSpec(const FunctionDecl *FD) override; 768 void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override; 769 void CompletedImplicitDefinition(const FunctionDecl *D) override; 770 void StaticDataMemberInstantiated(const VarDecl *D) override; 771 void FunctionDefinitionInstantiated(const FunctionDecl *D) override; 772 void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, 773 const ObjCInterfaceDecl *IFD) override; 774 void AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop, 775 const ObjCPropertyDecl *OrigProp, 776 const ObjCCategoryDecl *ClassExt) override; 777 void DeclarationMarkedUsed(const Decl *D) override; 778 }; 779 780 /// \brief AST and semantic-analysis consumer that generates a 781 /// precompiled header from the parsed source code. 782 class PCHGenerator : public SemaConsumer { 783 const Preprocessor &PP; 784 std::string OutputFile; 785 clang::Module *Module; 786 std::string isysroot; 787 raw_ostream *Out; 788 Sema *SemaPtr; 789 SmallVector<char, 128> Buffer; 790 llvm::BitstreamWriter Stream; 791 ASTWriter Writer; 792 bool AllowASTWithErrors; 793 bool HasEmittedPCH; 794 795 protected: 796 ASTWriter &getWriter() { return Writer; } 797 const ASTWriter &getWriter() const { return Writer; } 798 799 public: 800 PCHGenerator(const Preprocessor &PP, StringRef OutputFile, 801 clang::Module *Module, 802 StringRef isysroot, raw_ostream *Out, 803 bool AllowASTWithErrors = false); 804 ~PCHGenerator(); 805 void InitializeSema(Sema &S) override { SemaPtr = &S; } 806 void HandleTranslationUnit(ASTContext &Ctx) override; 807 ASTMutationListener *GetASTMutationListener() override; 808 ASTDeserializationListener *GetASTDeserializationListener() override; 809 810 bool hasEmittedPCH() const { return HasEmittedPCH; } 811 }; 812 813 } // end namespace clang 814 815 #endif 816