ASTWriter.cpp revision a015cab273705d1198d13e8389c2f4775f539a8b
1//===--- ASTWriter.cpp - AST File Writer ----------------------------------===// 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 AST files. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Serialization/ASTWriter.h" 15#include "ASTCommon.h" 16#include "clang/Sema/Sema.h" 17#include "clang/Sema/IdentifierResolver.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/Decl.h" 20#include "clang/AST/DeclContextInternals.h" 21#include "clang/AST/DeclTemplate.h" 22#include "clang/AST/DeclFriend.h" 23#include "clang/AST/Expr.h" 24#include "clang/AST/ExprCXX.h" 25#include "clang/AST/Type.h" 26#include "clang/AST/TypeLocVisitor.h" 27#include "clang/Serialization/ASTReader.h" 28#include "clang/Lex/MacroInfo.h" 29#include "clang/Lex/PreprocessingRecord.h" 30#include "clang/Lex/Preprocessor.h" 31#include "clang/Lex/HeaderSearch.h" 32#include "clang/Basic/FileManager.h" 33#include "clang/Basic/FileSystemStatCache.h" 34#include "clang/Basic/OnDiskHashTable.h" 35#include "clang/Basic/SourceManager.h" 36#include "clang/Basic/SourceManagerInternals.h" 37#include "clang/Basic/TargetInfo.h" 38#include "clang/Basic/Version.h" 39#include "clang/Basic/VersionTuple.h" 40#include "llvm/ADT/APFloat.h" 41#include "llvm/ADT/APInt.h" 42#include "llvm/ADT/StringExtras.h" 43#include "llvm/Bitcode/BitstreamWriter.h" 44#include "llvm/Support/FileSystem.h" 45#include "llvm/Support/MemoryBuffer.h" 46#include "llvm/Support/Path.h" 47#include <algorithm> 48#include <cstdio> 49#include <string.h> 50#include <utility> 51using namespace clang; 52using namespace clang::serialization; 53 54template <typename T, typename Allocator> 55static StringRef data(const std::vector<T, Allocator> &v) { 56 if (v.empty()) return StringRef(); 57 return StringRef(reinterpret_cast<const char*>(&v[0]), 58 sizeof(T) * v.size()); 59} 60 61template <typename T> 62static StringRef data(const SmallVectorImpl<T> &v) { 63 return StringRef(reinterpret_cast<const char*>(v.data()), 64 sizeof(T) * v.size()); 65} 66 67//===----------------------------------------------------------------------===// 68// Type serialization 69//===----------------------------------------------------------------------===// 70 71namespace { 72 class ASTTypeWriter { 73 ASTWriter &Writer; 74 ASTWriter::RecordDataImpl &Record; 75 76 public: 77 /// \brief Type code that corresponds to the record generated. 78 TypeCode Code; 79 80 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record) 81 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { } 82 83 void VisitArrayType(const ArrayType *T); 84 void VisitFunctionType(const FunctionType *T); 85 void VisitTagType(const TagType *T); 86 87#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T); 88#define ABSTRACT_TYPE(Class, Base) 89#include "clang/AST/TypeNodes.def" 90 }; 91} 92 93void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) { 94 llvm_unreachable("Built-in types are never serialized"); 95} 96 97void ASTTypeWriter::VisitComplexType(const ComplexType *T) { 98 Writer.AddTypeRef(T->getElementType(), Record); 99 Code = TYPE_COMPLEX; 100} 101 102void ASTTypeWriter::VisitPointerType(const PointerType *T) { 103 Writer.AddTypeRef(T->getPointeeType(), Record); 104 Code = TYPE_POINTER; 105} 106 107void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) { 108 Writer.AddTypeRef(T->getPointeeType(), Record); 109 Code = TYPE_BLOCK_POINTER; 110} 111 112void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) { 113 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record); 114 Record.push_back(T->isSpelledAsLValue()); 115 Code = TYPE_LVALUE_REFERENCE; 116} 117 118void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) { 119 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record); 120 Code = TYPE_RVALUE_REFERENCE; 121} 122 123void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) { 124 Writer.AddTypeRef(T->getPointeeType(), Record); 125 Writer.AddTypeRef(QualType(T->getClass(), 0), Record); 126 Code = TYPE_MEMBER_POINTER; 127} 128 129void ASTTypeWriter::VisitArrayType(const ArrayType *T) { 130 Writer.AddTypeRef(T->getElementType(), Record); 131 Record.push_back(T->getSizeModifier()); // FIXME: stable values 132 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values 133} 134 135void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) { 136 VisitArrayType(T); 137 Writer.AddAPInt(T->getSize(), Record); 138 Code = TYPE_CONSTANT_ARRAY; 139} 140 141void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) { 142 VisitArrayType(T); 143 Code = TYPE_INCOMPLETE_ARRAY; 144} 145 146void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) { 147 VisitArrayType(T); 148 Writer.AddSourceLocation(T->getLBracketLoc(), Record); 149 Writer.AddSourceLocation(T->getRBracketLoc(), Record); 150 Writer.AddStmt(T->getSizeExpr()); 151 Code = TYPE_VARIABLE_ARRAY; 152} 153 154void ASTTypeWriter::VisitVectorType(const VectorType *T) { 155 Writer.AddTypeRef(T->getElementType(), Record); 156 Record.push_back(T->getNumElements()); 157 Record.push_back(T->getVectorKind()); 158 Code = TYPE_VECTOR; 159} 160 161void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) { 162 VisitVectorType(T); 163 Code = TYPE_EXT_VECTOR; 164} 165 166void ASTTypeWriter::VisitFunctionType(const FunctionType *T) { 167 Writer.AddTypeRef(T->getResultType(), Record); 168 FunctionType::ExtInfo C = T->getExtInfo(); 169 Record.push_back(C.getNoReturn()); 170 Record.push_back(C.getHasRegParm()); 171 Record.push_back(C.getRegParm()); 172 // FIXME: need to stabilize encoding of calling convention... 173 Record.push_back(C.getCC()); 174 Record.push_back(C.getProducesResult()); 175} 176 177void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { 178 VisitFunctionType(T); 179 Code = TYPE_FUNCTION_NO_PROTO; 180} 181 182void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) { 183 VisitFunctionType(T); 184 Record.push_back(T->getNumArgs()); 185 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I) 186 Writer.AddTypeRef(T->getArgType(I), Record); 187 Record.push_back(T->isVariadic()); 188 Record.push_back(T->getTypeQuals()); 189 Record.push_back(static_cast<unsigned>(T->getRefQualifier())); 190 Record.push_back(T->getExceptionSpecType()); 191 if (T->getExceptionSpecType() == EST_Dynamic) { 192 Record.push_back(T->getNumExceptions()); 193 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I) 194 Writer.AddTypeRef(T->getExceptionType(I), Record); 195 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) { 196 Writer.AddStmt(T->getNoexceptExpr()); 197 } 198 Code = TYPE_FUNCTION_PROTO; 199} 200 201void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) { 202 Writer.AddDeclRef(T->getDecl(), Record); 203 Code = TYPE_UNRESOLVED_USING; 204} 205 206void ASTTypeWriter::VisitTypedefType(const TypedefType *T) { 207 Writer.AddDeclRef(T->getDecl(), Record); 208 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?"); 209 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record); 210 Code = TYPE_TYPEDEF; 211} 212 213void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) { 214 Writer.AddStmt(T->getUnderlyingExpr()); 215 Code = TYPE_TYPEOF_EXPR; 216} 217 218void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) { 219 Writer.AddTypeRef(T->getUnderlyingType(), Record); 220 Code = TYPE_TYPEOF; 221} 222 223void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) { 224 Writer.AddStmt(T->getUnderlyingExpr()); 225 Code = TYPE_DECLTYPE; 226} 227 228void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) { 229 Writer.AddTypeRef(T->getBaseType(), Record); 230 Writer.AddTypeRef(T->getUnderlyingType(), Record); 231 Record.push_back(T->getUTTKind()); 232 Code = TYPE_UNARY_TRANSFORM; 233} 234 235void ASTTypeWriter::VisitAutoType(const AutoType *T) { 236 Writer.AddTypeRef(T->getDeducedType(), Record); 237 Code = TYPE_AUTO; 238} 239 240void ASTTypeWriter::VisitTagType(const TagType *T) { 241 Record.push_back(T->isDependentType()); 242 Writer.AddDeclRef(T->getDecl(), Record); 243 assert(!T->isBeingDefined() && 244 "Cannot serialize in the middle of a type definition"); 245} 246 247void ASTTypeWriter::VisitRecordType(const RecordType *T) { 248 VisitTagType(T); 249 Code = TYPE_RECORD; 250} 251 252void ASTTypeWriter::VisitEnumType(const EnumType *T) { 253 VisitTagType(T); 254 Code = TYPE_ENUM; 255} 256 257void ASTTypeWriter::VisitAttributedType(const AttributedType *T) { 258 Writer.AddTypeRef(T->getModifiedType(), Record); 259 Writer.AddTypeRef(T->getEquivalentType(), Record); 260 Record.push_back(T->getAttrKind()); 261 Code = TYPE_ATTRIBUTED; 262} 263 264void 265ASTTypeWriter::VisitSubstTemplateTypeParmType( 266 const SubstTemplateTypeParmType *T) { 267 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record); 268 Writer.AddTypeRef(T->getReplacementType(), Record); 269 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM; 270} 271 272void 273ASTTypeWriter::VisitSubstTemplateTypeParmPackType( 274 const SubstTemplateTypeParmPackType *T) { 275 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record); 276 Writer.AddTemplateArgument(T->getArgumentPack(), Record); 277 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK; 278} 279 280void 281ASTTypeWriter::VisitTemplateSpecializationType( 282 const TemplateSpecializationType *T) { 283 Record.push_back(T->isDependentType()); 284 Writer.AddTemplateName(T->getTemplateName(), Record); 285 Record.push_back(T->getNumArgs()); 286 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end(); 287 ArgI != ArgE; ++ArgI) 288 Writer.AddTemplateArgument(*ArgI, Record); 289 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() : 290 T->isCanonicalUnqualified() ? QualType() 291 : T->getCanonicalTypeInternal(), 292 Record); 293 Code = TYPE_TEMPLATE_SPECIALIZATION; 294} 295 296void 297ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) { 298 VisitArrayType(T); 299 Writer.AddStmt(T->getSizeExpr()); 300 Writer.AddSourceRange(T->getBracketsRange(), Record); 301 Code = TYPE_DEPENDENT_SIZED_ARRAY; 302} 303 304void 305ASTTypeWriter::VisitDependentSizedExtVectorType( 306 const DependentSizedExtVectorType *T) { 307 // FIXME: Serialize this type (C++ only) 308 llvm_unreachable("Cannot serialize dependent sized extended vector types"); 309} 310 311void 312ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) { 313 Record.push_back(T->getDepth()); 314 Record.push_back(T->getIndex()); 315 Record.push_back(T->isParameterPack()); 316 Writer.AddDeclRef(T->getDecl(), Record); 317 Code = TYPE_TEMPLATE_TYPE_PARM; 318} 319 320void 321ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) { 322 Record.push_back(T->getKeyword()); 323 Writer.AddNestedNameSpecifier(T->getQualifier(), Record); 324 Writer.AddIdentifierRef(T->getIdentifier(), Record); 325 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType() 326 : T->getCanonicalTypeInternal(), 327 Record); 328 Code = TYPE_DEPENDENT_NAME; 329} 330 331void 332ASTTypeWriter::VisitDependentTemplateSpecializationType( 333 const DependentTemplateSpecializationType *T) { 334 Record.push_back(T->getKeyword()); 335 Writer.AddNestedNameSpecifier(T->getQualifier(), Record); 336 Writer.AddIdentifierRef(T->getIdentifier(), Record); 337 Record.push_back(T->getNumArgs()); 338 for (DependentTemplateSpecializationType::iterator 339 I = T->begin(), E = T->end(); I != E; ++I) 340 Writer.AddTemplateArgument(*I, Record); 341 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION; 342} 343 344void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) { 345 Writer.AddTypeRef(T->getPattern(), Record); 346 if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions()) 347 Record.push_back(*NumExpansions + 1); 348 else 349 Record.push_back(0); 350 Code = TYPE_PACK_EXPANSION; 351} 352 353void ASTTypeWriter::VisitParenType(const ParenType *T) { 354 Writer.AddTypeRef(T->getInnerType(), Record); 355 Code = TYPE_PAREN; 356} 357 358void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) { 359 Record.push_back(T->getKeyword()); 360 Writer.AddNestedNameSpecifier(T->getQualifier(), Record); 361 Writer.AddTypeRef(T->getNamedType(), Record); 362 Code = TYPE_ELABORATED; 363} 364 365void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) { 366 Writer.AddDeclRef(T->getDecl(), Record); 367 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record); 368 Code = TYPE_INJECTED_CLASS_NAME; 369} 370 371void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { 372 Writer.AddDeclRef(T->getDecl(), Record); 373 Code = TYPE_OBJC_INTERFACE; 374} 375 376void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) { 377 Writer.AddTypeRef(T->getBaseType(), Record); 378 Record.push_back(T->getNumProtocols()); 379 for (ObjCObjectType::qual_iterator I = T->qual_begin(), 380 E = T->qual_end(); I != E; ++I) 381 Writer.AddDeclRef(*I, Record); 382 Code = TYPE_OBJC_OBJECT; 383} 384 385void 386ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { 387 Writer.AddTypeRef(T->getPointeeType(), Record); 388 Code = TYPE_OBJC_OBJECT_POINTER; 389} 390 391void 392ASTTypeWriter::VisitAtomicType(const AtomicType *T) { 393 Writer.AddTypeRef(T->getValueType(), Record); 394 Code = TYPE_ATOMIC; 395} 396 397namespace { 398 399class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> { 400 ASTWriter &Writer; 401 ASTWriter::RecordDataImpl &Record; 402 403public: 404 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record) 405 : Writer(Writer), Record(Record) { } 406 407#define ABSTRACT_TYPELOC(CLASS, PARENT) 408#define TYPELOC(CLASS, PARENT) \ 409 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); 410#include "clang/AST/TypeLocNodes.def" 411 412 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc); 413 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc); 414}; 415 416} 417 418void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 419 // nothing to do 420} 421void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 422 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record); 423 if (TL.needsExtraLocalData()) { 424 Record.push_back(TL.getWrittenTypeSpec()); 425 Record.push_back(TL.getWrittenSignSpec()); 426 Record.push_back(TL.getWrittenWidthSpec()); 427 Record.push_back(TL.hasModeAttr()); 428 } 429} 430void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) { 431 Writer.AddSourceLocation(TL.getNameLoc(), Record); 432} 433void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) { 434 Writer.AddSourceLocation(TL.getStarLoc(), Record); 435} 436void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 437 Writer.AddSourceLocation(TL.getCaretLoc(), Record); 438} 439void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 440 Writer.AddSourceLocation(TL.getAmpLoc(), Record); 441} 442void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 443 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record); 444} 445void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 446 Writer.AddSourceLocation(TL.getStarLoc(), Record); 447 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record); 448} 449void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) { 450 Writer.AddSourceLocation(TL.getLBracketLoc(), Record); 451 Writer.AddSourceLocation(TL.getRBracketLoc(), Record); 452 Record.push_back(TL.getSizeExpr() ? 1 : 0); 453 if (TL.getSizeExpr()) 454 Writer.AddStmt(TL.getSizeExpr()); 455} 456void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { 457 VisitArrayTypeLoc(TL); 458} 459void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { 460 VisitArrayTypeLoc(TL); 461} 462void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { 463 VisitArrayTypeLoc(TL); 464} 465void TypeLocWriter::VisitDependentSizedArrayTypeLoc( 466 DependentSizedArrayTypeLoc TL) { 467 VisitArrayTypeLoc(TL); 468} 469void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc( 470 DependentSizedExtVectorTypeLoc TL) { 471 Writer.AddSourceLocation(TL.getNameLoc(), Record); 472} 473void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) { 474 Writer.AddSourceLocation(TL.getNameLoc(), Record); 475} 476void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 477 Writer.AddSourceLocation(TL.getNameLoc(), Record); 478} 479void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) { 480 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record); 481 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record); 482 Record.push_back(TL.getTrailingReturn()); 483 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 484 Writer.AddDeclRef(TL.getArg(i), Record); 485} 486void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { 487 VisitFunctionTypeLoc(TL); 488} 489void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { 490 VisitFunctionTypeLoc(TL); 491} 492void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 493 Writer.AddSourceLocation(TL.getNameLoc(), Record); 494} 495void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 496 Writer.AddSourceLocation(TL.getNameLoc(), Record); 497} 498void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 499 Writer.AddSourceLocation(TL.getTypeofLoc(), Record); 500 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 501 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 502} 503void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 504 Writer.AddSourceLocation(TL.getTypeofLoc(), Record); 505 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 506 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 507 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record); 508} 509void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 510 Writer.AddSourceLocation(TL.getNameLoc(), Record); 511} 512void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 513 Writer.AddSourceLocation(TL.getKWLoc(), Record); 514 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 515 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 516 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record); 517} 518void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) { 519 Writer.AddSourceLocation(TL.getNameLoc(), Record); 520} 521void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) { 522 Writer.AddSourceLocation(TL.getNameLoc(), Record); 523} 524void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) { 525 Writer.AddSourceLocation(TL.getNameLoc(), Record); 526} 527void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 528 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record); 529 if (TL.hasAttrOperand()) { 530 SourceRange range = TL.getAttrOperandParensRange(); 531 Writer.AddSourceLocation(range.getBegin(), Record); 532 Writer.AddSourceLocation(range.getEnd(), Record); 533 } 534 if (TL.hasAttrExprOperand()) { 535 Expr *operand = TL.getAttrExprOperand(); 536 Record.push_back(operand ? 1 : 0); 537 if (operand) Writer.AddStmt(operand); 538 } else if (TL.hasAttrEnumOperand()) { 539 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record); 540 } 541} 542void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 543 Writer.AddSourceLocation(TL.getNameLoc(), Record); 544} 545void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc( 546 SubstTemplateTypeParmTypeLoc TL) { 547 Writer.AddSourceLocation(TL.getNameLoc(), Record); 548} 549void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc( 550 SubstTemplateTypeParmPackTypeLoc TL) { 551 Writer.AddSourceLocation(TL.getNameLoc(), Record); 552} 553void TypeLocWriter::VisitTemplateSpecializationTypeLoc( 554 TemplateSpecializationTypeLoc TL) { 555 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record); 556 Writer.AddSourceLocation(TL.getLAngleLoc(), Record); 557 Writer.AddSourceLocation(TL.getRAngleLoc(), Record); 558 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 559 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(), 560 TL.getArgLoc(i).getLocInfo(), Record); 561} 562void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) { 563 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 564 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 565} 566void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 567 Writer.AddSourceLocation(TL.getKeywordLoc(), Record); 568 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record); 569} 570void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 571 Writer.AddSourceLocation(TL.getNameLoc(), Record); 572} 573void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 574 Writer.AddSourceLocation(TL.getKeywordLoc(), Record); 575 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record); 576 Writer.AddSourceLocation(TL.getNameLoc(), Record); 577} 578void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc( 579 DependentTemplateSpecializationTypeLoc TL) { 580 Writer.AddSourceLocation(TL.getKeywordLoc(), Record); 581 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record); 582 Writer.AddSourceLocation(TL.getNameLoc(), Record); 583 Writer.AddSourceLocation(TL.getLAngleLoc(), Record); 584 Writer.AddSourceLocation(TL.getRAngleLoc(), Record); 585 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) 586 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(), 587 TL.getArgLoc(I).getLocInfo(), Record); 588} 589void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 590 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record); 591} 592void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 593 Writer.AddSourceLocation(TL.getNameLoc(), Record); 594} 595void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 596 Record.push_back(TL.hasBaseTypeAsWritten()); 597 Writer.AddSourceLocation(TL.getLAngleLoc(), Record); 598 Writer.AddSourceLocation(TL.getRAngleLoc(), Record); 599 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 600 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record); 601} 602void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 603 Writer.AddSourceLocation(TL.getStarLoc(), Record); 604} 605void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 606 Writer.AddSourceLocation(TL.getKWLoc(), Record); 607 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 608 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 609} 610 611//===----------------------------------------------------------------------===// 612// ASTWriter Implementation 613//===----------------------------------------------------------------------===// 614 615static void EmitBlockID(unsigned ID, const char *Name, 616 llvm::BitstreamWriter &Stream, 617 ASTWriter::RecordDataImpl &Record) { 618 Record.clear(); 619 Record.push_back(ID); 620 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record); 621 622 // Emit the block name if present. 623 if (Name == 0 || Name[0] == 0) return; 624 Record.clear(); 625 while (*Name) 626 Record.push_back(*Name++); 627 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record); 628} 629 630static void EmitRecordID(unsigned ID, const char *Name, 631 llvm::BitstreamWriter &Stream, 632 ASTWriter::RecordDataImpl &Record) { 633 Record.clear(); 634 Record.push_back(ID); 635 while (*Name) 636 Record.push_back(*Name++); 637 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record); 638} 639 640static void AddStmtsExprs(llvm::BitstreamWriter &Stream, 641 ASTWriter::RecordDataImpl &Record) { 642#define RECORD(X) EmitRecordID(X, #X, Stream, Record) 643 RECORD(STMT_STOP); 644 RECORD(STMT_NULL_PTR); 645 RECORD(STMT_NULL); 646 RECORD(STMT_COMPOUND); 647 RECORD(STMT_CASE); 648 RECORD(STMT_DEFAULT); 649 RECORD(STMT_LABEL); 650 RECORD(STMT_IF); 651 RECORD(STMT_SWITCH); 652 RECORD(STMT_WHILE); 653 RECORD(STMT_DO); 654 RECORD(STMT_FOR); 655 RECORD(STMT_GOTO); 656 RECORD(STMT_INDIRECT_GOTO); 657 RECORD(STMT_CONTINUE); 658 RECORD(STMT_BREAK); 659 RECORD(STMT_RETURN); 660 RECORD(STMT_DECL); 661 RECORD(STMT_ASM); 662 RECORD(EXPR_PREDEFINED); 663 RECORD(EXPR_DECL_REF); 664 RECORD(EXPR_INTEGER_LITERAL); 665 RECORD(EXPR_FLOATING_LITERAL); 666 RECORD(EXPR_IMAGINARY_LITERAL); 667 RECORD(EXPR_STRING_LITERAL); 668 RECORD(EXPR_CHARACTER_LITERAL); 669 RECORD(EXPR_PAREN); 670 RECORD(EXPR_UNARY_OPERATOR); 671 RECORD(EXPR_SIZEOF_ALIGN_OF); 672 RECORD(EXPR_ARRAY_SUBSCRIPT); 673 RECORD(EXPR_CALL); 674 RECORD(EXPR_MEMBER); 675 RECORD(EXPR_BINARY_OPERATOR); 676 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR); 677 RECORD(EXPR_CONDITIONAL_OPERATOR); 678 RECORD(EXPR_IMPLICIT_CAST); 679 RECORD(EXPR_CSTYLE_CAST); 680 RECORD(EXPR_COMPOUND_LITERAL); 681 RECORD(EXPR_EXT_VECTOR_ELEMENT); 682 RECORD(EXPR_INIT_LIST); 683 RECORD(EXPR_DESIGNATED_INIT); 684 RECORD(EXPR_IMPLICIT_VALUE_INIT); 685 RECORD(EXPR_VA_ARG); 686 RECORD(EXPR_ADDR_LABEL); 687 RECORD(EXPR_STMT); 688 RECORD(EXPR_CHOOSE); 689 RECORD(EXPR_GNU_NULL); 690 RECORD(EXPR_SHUFFLE_VECTOR); 691 RECORD(EXPR_BLOCK); 692 RECORD(EXPR_BLOCK_DECL_REF); 693 RECORD(EXPR_GENERIC_SELECTION); 694 RECORD(EXPR_OBJC_STRING_LITERAL); 695 RECORD(EXPR_OBJC_ENCODE); 696 RECORD(EXPR_OBJC_SELECTOR_EXPR); 697 RECORD(EXPR_OBJC_PROTOCOL_EXPR); 698 RECORD(EXPR_OBJC_IVAR_REF_EXPR); 699 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR); 700 RECORD(EXPR_OBJC_KVC_REF_EXPR); 701 RECORD(EXPR_OBJC_MESSAGE_EXPR); 702 RECORD(STMT_OBJC_FOR_COLLECTION); 703 RECORD(STMT_OBJC_CATCH); 704 RECORD(STMT_OBJC_FINALLY); 705 RECORD(STMT_OBJC_AT_TRY); 706 RECORD(STMT_OBJC_AT_SYNCHRONIZED); 707 RECORD(STMT_OBJC_AT_THROW); 708 RECORD(EXPR_CXX_OPERATOR_CALL); 709 RECORD(EXPR_CXX_CONSTRUCT); 710 RECORD(EXPR_CXX_STATIC_CAST); 711 RECORD(EXPR_CXX_DYNAMIC_CAST); 712 RECORD(EXPR_CXX_REINTERPRET_CAST); 713 RECORD(EXPR_CXX_CONST_CAST); 714 RECORD(EXPR_CXX_FUNCTIONAL_CAST); 715 RECORD(EXPR_CXX_BOOL_LITERAL); 716 RECORD(EXPR_CXX_NULL_PTR_LITERAL); 717 RECORD(EXPR_CXX_TYPEID_EXPR); 718 RECORD(EXPR_CXX_TYPEID_TYPE); 719 RECORD(EXPR_CXX_UUIDOF_EXPR); 720 RECORD(EXPR_CXX_UUIDOF_TYPE); 721 RECORD(EXPR_CXX_THIS); 722 RECORD(EXPR_CXX_THROW); 723 RECORD(EXPR_CXX_DEFAULT_ARG); 724 RECORD(EXPR_CXX_BIND_TEMPORARY); 725 RECORD(EXPR_CXX_SCALAR_VALUE_INIT); 726 RECORD(EXPR_CXX_NEW); 727 RECORD(EXPR_CXX_DELETE); 728 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR); 729 RECORD(EXPR_EXPR_WITH_CLEANUPS); 730 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER); 731 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF); 732 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT); 733 RECORD(EXPR_CXX_UNRESOLVED_MEMBER); 734 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP); 735 RECORD(EXPR_CXX_UNARY_TYPE_TRAIT); 736 RECORD(EXPR_CXX_NOEXCEPT); 737 RECORD(EXPR_OPAQUE_VALUE); 738 RECORD(EXPR_BINARY_TYPE_TRAIT); 739 RECORD(EXPR_PACK_EXPANSION); 740 RECORD(EXPR_SIZEOF_PACK); 741 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK); 742 RECORD(EXPR_CUDA_KERNEL_CALL); 743#undef RECORD 744} 745 746void ASTWriter::WriteBlockInfoBlock() { 747 RecordData Record; 748 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3); 749 750#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record) 751#define RECORD(X) EmitRecordID(X, #X, Stream, Record) 752 753 // AST Top-Level Block. 754 BLOCK(AST_BLOCK); 755 RECORD(ORIGINAL_FILE_NAME); 756 RECORD(ORIGINAL_FILE_ID); 757 RECORD(TYPE_OFFSET); 758 RECORD(DECL_OFFSET); 759 RECORD(LANGUAGE_OPTIONS); 760 RECORD(METADATA); 761 RECORD(IDENTIFIER_OFFSET); 762 RECORD(IDENTIFIER_TABLE); 763 RECORD(EXTERNAL_DEFINITIONS); 764 RECORD(SPECIAL_TYPES); 765 RECORD(STATISTICS); 766 RECORD(TENTATIVE_DEFINITIONS); 767 RECORD(UNUSED_FILESCOPED_DECLS); 768 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS); 769 RECORD(SELECTOR_OFFSETS); 770 RECORD(METHOD_POOL); 771 RECORD(PP_COUNTER_VALUE); 772 RECORD(SOURCE_LOCATION_OFFSETS); 773 RECORD(SOURCE_LOCATION_PRELOADS); 774 RECORD(STAT_CACHE); 775 RECORD(EXT_VECTOR_DECLS); 776 RECORD(VERSION_CONTROL_BRANCH_REVISION); 777 RECORD(PPD_ENTITIES_OFFSETS); 778 RECORD(IMPORTS); 779 RECORD(REFERENCED_SELECTOR_POOL); 780 RECORD(TU_UPDATE_LEXICAL); 781 RECORD(REDECLS_UPDATE_LATEST); 782 RECORD(SEMA_DECL_REFS); 783 RECORD(WEAK_UNDECLARED_IDENTIFIERS); 784 RECORD(PENDING_IMPLICIT_INSTANTIATIONS); 785 RECORD(DECL_REPLACEMENTS); 786 RECORD(UPDATE_VISIBLE); 787 RECORD(DECL_UPDATE_OFFSETS); 788 RECORD(DECL_UPDATES); 789 RECORD(CXX_BASE_SPECIFIER_OFFSETS); 790 RECORD(DIAG_PRAGMA_MAPPINGS); 791 RECORD(CUDA_SPECIAL_DECL_REFS); 792 RECORD(HEADER_SEARCH_TABLE); 793 RECORD(ORIGINAL_PCH_DIR); 794 RECORD(FP_PRAGMA_OPTIONS); 795 RECORD(OPENCL_EXTENSIONS); 796 RECORD(DELEGATING_CTORS); 797 RECORD(FILE_SOURCE_LOCATION_OFFSETS); 798 RECORD(KNOWN_NAMESPACES); 799 RECORD(MODULE_OFFSET_MAP); 800 RECORD(SOURCE_MANAGER_LINE_TABLE); 801 802 // SourceManager Block. 803 BLOCK(SOURCE_MANAGER_BLOCK); 804 RECORD(SM_SLOC_FILE_ENTRY); 805 RECORD(SM_SLOC_BUFFER_ENTRY); 806 RECORD(SM_SLOC_BUFFER_BLOB); 807 RECORD(SM_SLOC_EXPANSION_ENTRY); 808 809 // Preprocessor Block. 810 BLOCK(PREPROCESSOR_BLOCK); 811 RECORD(PP_MACRO_OBJECT_LIKE); 812 RECORD(PP_MACRO_FUNCTION_LIKE); 813 RECORD(PP_TOKEN); 814 815 // Decls and Types block. 816 BLOCK(DECLTYPES_BLOCK); 817 RECORD(TYPE_EXT_QUAL); 818 RECORD(TYPE_COMPLEX); 819 RECORD(TYPE_POINTER); 820 RECORD(TYPE_BLOCK_POINTER); 821 RECORD(TYPE_LVALUE_REFERENCE); 822 RECORD(TYPE_RVALUE_REFERENCE); 823 RECORD(TYPE_MEMBER_POINTER); 824 RECORD(TYPE_CONSTANT_ARRAY); 825 RECORD(TYPE_INCOMPLETE_ARRAY); 826 RECORD(TYPE_VARIABLE_ARRAY); 827 RECORD(TYPE_VECTOR); 828 RECORD(TYPE_EXT_VECTOR); 829 RECORD(TYPE_FUNCTION_PROTO); 830 RECORD(TYPE_FUNCTION_NO_PROTO); 831 RECORD(TYPE_TYPEDEF); 832 RECORD(TYPE_TYPEOF_EXPR); 833 RECORD(TYPE_TYPEOF); 834 RECORD(TYPE_RECORD); 835 RECORD(TYPE_ENUM); 836 RECORD(TYPE_OBJC_INTERFACE); 837 RECORD(TYPE_OBJC_OBJECT); 838 RECORD(TYPE_OBJC_OBJECT_POINTER); 839 RECORD(TYPE_DECLTYPE); 840 RECORD(TYPE_ELABORATED); 841 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM); 842 RECORD(TYPE_UNRESOLVED_USING); 843 RECORD(TYPE_INJECTED_CLASS_NAME); 844 RECORD(TYPE_OBJC_OBJECT); 845 RECORD(TYPE_TEMPLATE_TYPE_PARM); 846 RECORD(TYPE_TEMPLATE_SPECIALIZATION); 847 RECORD(TYPE_DEPENDENT_NAME); 848 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION); 849 RECORD(TYPE_DEPENDENT_SIZED_ARRAY); 850 RECORD(TYPE_PAREN); 851 RECORD(TYPE_PACK_EXPANSION); 852 RECORD(TYPE_ATTRIBUTED); 853 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK); 854 RECORD(TYPE_ATOMIC); 855 RECORD(DECL_TYPEDEF); 856 RECORD(DECL_ENUM); 857 RECORD(DECL_RECORD); 858 RECORD(DECL_ENUM_CONSTANT); 859 RECORD(DECL_FUNCTION); 860 RECORD(DECL_OBJC_METHOD); 861 RECORD(DECL_OBJC_INTERFACE); 862 RECORD(DECL_OBJC_PROTOCOL); 863 RECORD(DECL_OBJC_IVAR); 864 RECORD(DECL_OBJC_AT_DEFS_FIELD); 865 RECORD(DECL_OBJC_CLASS); 866 RECORD(DECL_OBJC_FORWARD_PROTOCOL); 867 RECORD(DECL_OBJC_CATEGORY); 868 RECORD(DECL_OBJC_CATEGORY_IMPL); 869 RECORD(DECL_OBJC_IMPLEMENTATION); 870 RECORD(DECL_OBJC_COMPATIBLE_ALIAS); 871 RECORD(DECL_OBJC_PROPERTY); 872 RECORD(DECL_OBJC_PROPERTY_IMPL); 873 RECORD(DECL_FIELD); 874 RECORD(DECL_VAR); 875 RECORD(DECL_IMPLICIT_PARAM); 876 RECORD(DECL_PARM_VAR); 877 RECORD(DECL_FILE_SCOPE_ASM); 878 RECORD(DECL_BLOCK); 879 RECORD(DECL_CONTEXT_LEXICAL); 880 RECORD(DECL_CONTEXT_VISIBLE); 881 RECORD(DECL_NAMESPACE); 882 RECORD(DECL_NAMESPACE_ALIAS); 883 RECORD(DECL_USING); 884 RECORD(DECL_USING_SHADOW); 885 RECORD(DECL_USING_DIRECTIVE); 886 RECORD(DECL_UNRESOLVED_USING_VALUE); 887 RECORD(DECL_UNRESOLVED_USING_TYPENAME); 888 RECORD(DECL_LINKAGE_SPEC); 889 RECORD(DECL_CXX_RECORD); 890 RECORD(DECL_CXX_METHOD); 891 RECORD(DECL_CXX_CONSTRUCTOR); 892 RECORD(DECL_CXX_DESTRUCTOR); 893 RECORD(DECL_CXX_CONVERSION); 894 RECORD(DECL_ACCESS_SPEC); 895 RECORD(DECL_FRIEND); 896 RECORD(DECL_FRIEND_TEMPLATE); 897 RECORD(DECL_CLASS_TEMPLATE); 898 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION); 899 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION); 900 RECORD(DECL_FUNCTION_TEMPLATE); 901 RECORD(DECL_TEMPLATE_TYPE_PARM); 902 RECORD(DECL_NON_TYPE_TEMPLATE_PARM); 903 RECORD(DECL_TEMPLATE_TEMPLATE_PARM); 904 RECORD(DECL_STATIC_ASSERT); 905 RECORD(DECL_CXX_BASE_SPECIFIERS); 906 RECORD(DECL_INDIRECTFIELD); 907 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK); 908 909 // Statements and Exprs can occur in the Decls and Types block. 910 AddStmtsExprs(Stream, Record); 911 912 BLOCK(PREPROCESSOR_DETAIL_BLOCK); 913 RECORD(PPD_MACRO_EXPANSION); 914 RECORD(PPD_MACRO_DEFINITION); 915 RECORD(PPD_INCLUSION_DIRECTIVE); 916 917#undef RECORD 918#undef BLOCK 919 Stream.ExitBlock(); 920} 921 922/// \brief Adjusts the given filename to only write out the portion of the 923/// filename that is not part of the system root directory. 924/// 925/// \param Filename the file name to adjust. 926/// 927/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and 928/// the returned filename will be adjusted by this system root. 929/// 930/// \returns either the original filename (if it needs no adjustment) or the 931/// adjusted filename (which points into the @p Filename parameter). 932static const char * 933adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) { 934 assert(Filename && "No file name to adjust?"); 935 936 if (isysroot.empty()) 937 return Filename; 938 939 // Verify that the filename and the system root have the same prefix. 940 unsigned Pos = 0; 941 for (; Filename[Pos] && Pos < isysroot.size(); ++Pos) 942 if (Filename[Pos] != isysroot[Pos]) 943 return Filename; // Prefixes don't match. 944 945 // We hit the end of the filename before we hit the end of the system root. 946 if (!Filename[Pos]) 947 return Filename; 948 949 // If the file name has a '/' at the current position, skip over the '/'. 950 // We distinguish sysroot-based includes from absolute includes by the 951 // absence of '/' at the beginning of sysroot-based includes. 952 if (Filename[Pos] == '/') 953 ++Pos; 954 955 return Filename + Pos; 956} 957 958/// \brief Write the AST metadata (e.g., i686-apple-darwin9). 959void ASTWriter::WriteMetadata(ASTContext &Context, StringRef isysroot, 960 const std::string &OutputFile) { 961 using namespace llvm; 962 963 // Metadata 964 const TargetInfo &Target = Context.getTargetInfo(); 965 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev(); 966 MetaAbbrev->Add(BitCodeAbbrevOp(METADATA)); 967 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major 968 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor 969 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major 970 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor 971 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable 972 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple 973 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev); 974 975 RecordData Record; 976 Record.push_back(METADATA); 977 Record.push_back(VERSION_MAJOR); 978 Record.push_back(VERSION_MINOR); 979 Record.push_back(CLANG_VERSION_MAJOR); 980 Record.push_back(CLANG_VERSION_MINOR); 981 Record.push_back(!isysroot.empty()); 982 const std::string &Triple = Target.getTriple().getTriple(); 983 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple); 984 985 if (Chain) { 986 serialization::ModuleManager &Mgr = Chain->getModuleManager(); 987 llvm::SmallVector<char, 128> ModulePaths; 988 Record.clear(); 989 990 for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end(); 991 M != MEnd; ++M) { 992 // Skip modules that weren't directly imported. 993 if (!(*M)->isDirectlyImported()) 994 continue; 995 996 Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding 997 // FIXME: Write import location, once it matters. 998 // FIXME: This writes the absolute path for AST files we depend on. 999 const std::string &FileName = (*M)->FileName; 1000 Record.push_back(FileName.size()); 1001 Record.append(FileName.begin(), FileName.end()); 1002 } 1003 Stream.EmitRecord(IMPORTS, Record); 1004 } 1005 1006 // Original file name and file ID 1007 SourceManager &SM = Context.getSourceManager(); 1008 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 1009 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev(); 1010 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME)); 1011 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1012 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev); 1013 1014 llvm::SmallString<128> MainFilePath(MainFile->getName()); 1015 1016 llvm::sys::fs::make_absolute(MainFilePath); 1017 1018 const char *MainFileNameStr = MainFilePath.c_str(); 1019 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr, 1020 isysroot); 1021 RecordData Record; 1022 Record.push_back(ORIGINAL_FILE_NAME); 1023 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr); 1024 1025 Record.clear(); 1026 Record.push_back(SM.getMainFileID().getOpaqueValue()); 1027 Stream.EmitRecord(ORIGINAL_FILE_ID, Record); 1028 } 1029 1030 // Original PCH directory 1031 if (!OutputFile.empty() && OutputFile != "-") { 1032 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1033 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR)); 1034 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1035 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev); 1036 1037 llvm::SmallString<128> OutputPath(OutputFile); 1038 1039 llvm::sys::fs::make_absolute(OutputPath); 1040 StringRef origDir = llvm::sys::path::parent_path(OutputPath); 1041 1042 RecordData Record; 1043 Record.push_back(ORIGINAL_PCH_DIR); 1044 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir); 1045 } 1046 1047 // Repository branch/version information. 1048 BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev(); 1049 RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION)); 1050 RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag 1051 unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev); 1052 Record.clear(); 1053 Record.push_back(VERSION_CONTROL_BRANCH_REVISION); 1054 Stream.EmitRecordWithBlob(RepoAbbrevCode, Record, 1055 getClangFullRepositoryVersion()); 1056} 1057 1058/// \brief Write the LangOptions structure. 1059void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) { 1060 RecordData Record; 1061#define LANGOPT(Name, Bits, Default, Description) \ 1062 Record.push_back(LangOpts.Name); 1063#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 1064 Record.push_back(static_cast<unsigned>(LangOpts.get##Name())); 1065#include "clang/Basic/LangOptions.def" 1066 1067 Record.push_back(LangOpts.CurrentModule.size()); 1068 Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end()); 1069 Stream.EmitRecord(LANGUAGE_OPTIONS, Record); 1070} 1071 1072//===----------------------------------------------------------------------===// 1073// stat cache Serialization 1074//===----------------------------------------------------------------------===// 1075 1076namespace { 1077// Trait used for the on-disk hash table of stat cache results. 1078class ASTStatCacheTrait { 1079public: 1080 typedef const char * key_type; 1081 typedef key_type key_type_ref; 1082 1083 typedef struct stat data_type; 1084 typedef const data_type &data_type_ref; 1085 1086 static unsigned ComputeHash(const char *path) { 1087 return llvm::HashString(path); 1088 } 1089 1090 std::pair<unsigned,unsigned> 1091 EmitKeyDataLength(raw_ostream& Out, const char *path, 1092 data_type_ref Data) { 1093 unsigned StrLen = strlen(path); 1094 clang::io::Emit16(Out, StrLen); 1095 unsigned DataLen = 4 + 4 + 2 + 8 + 8; 1096 clang::io::Emit8(Out, DataLen); 1097 return std::make_pair(StrLen + 1, DataLen); 1098 } 1099 1100 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) { 1101 Out.write(path, KeyLen); 1102 } 1103 1104 void EmitData(raw_ostream &Out, key_type_ref, 1105 data_type_ref Data, unsigned DataLen) { 1106 using namespace clang::io; 1107 uint64_t Start = Out.tell(); (void)Start; 1108 1109 Emit32(Out, (uint32_t) Data.st_ino); 1110 Emit32(Out, (uint32_t) Data.st_dev); 1111 Emit16(Out, (uint16_t) Data.st_mode); 1112 Emit64(Out, (uint64_t) Data.st_mtime); 1113 Emit64(Out, (uint64_t) Data.st_size); 1114 1115 assert(Out.tell() - Start == DataLen && "Wrong data length"); 1116 } 1117}; 1118} // end anonymous namespace 1119 1120/// \brief Write the stat() system call cache to the AST file. 1121void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) { 1122 // Build the on-disk hash table containing information about every 1123 // stat() call. 1124 OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator; 1125 unsigned NumStatEntries = 0; 1126 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(), 1127 StatEnd = StatCalls.end(); 1128 Stat != StatEnd; ++Stat, ++NumStatEntries) { 1129 StringRef Filename = Stat->first(); 1130 Generator.insert(Filename.data(), Stat->second); 1131 } 1132 1133 // Create the on-disk hash table in a buffer. 1134 llvm::SmallString<4096> StatCacheData; 1135 uint32_t BucketOffset; 1136 { 1137 llvm::raw_svector_ostream Out(StatCacheData); 1138 // Make sure that no bucket is at offset 0 1139 clang::io::Emit32(Out, 0); 1140 BucketOffset = Generator.Emit(Out); 1141 } 1142 1143 // Create a blob abbreviation 1144 using namespace llvm; 1145 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1146 Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE)); 1147 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1148 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1149 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1150 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev); 1151 1152 // Write the stat cache 1153 RecordData Record; 1154 Record.push_back(STAT_CACHE); 1155 Record.push_back(BucketOffset); 1156 Record.push_back(NumStatEntries); 1157 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str()); 1158} 1159 1160//===----------------------------------------------------------------------===// 1161// Source Manager Serialization 1162//===----------------------------------------------------------------------===// 1163 1164/// \brief Create an abbreviation for the SLocEntry that refers to a 1165/// file. 1166static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) { 1167 using namespace llvm; 1168 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1169 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY)); 1170 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1171 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1172 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 1173 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1174 // FileEntry fields. 1175 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size 1176 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time 1177 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // BufferOverridden 1178 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs 1179 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex 1180 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls 1181 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1182 return Stream.EmitAbbrev(Abbrev); 1183} 1184 1185/// \brief Create an abbreviation for the SLocEntry that refers to a 1186/// buffer. 1187static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) { 1188 using namespace llvm; 1189 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1190 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY)); 1191 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1192 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1193 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 1194 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1195 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob 1196 return Stream.EmitAbbrev(Abbrev); 1197} 1198 1199/// \brief Create an abbreviation for the SLocEntry that refers to a 1200/// buffer's blob. 1201static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) { 1202 using namespace llvm; 1203 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1204 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB)); 1205 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob 1206 return Stream.EmitAbbrev(Abbrev); 1207} 1208 1209/// \brief Create an abbreviation for the SLocEntry that refers to a macro 1210/// expansion. 1211static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) { 1212 using namespace llvm; 1213 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1214 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY)); 1215 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1216 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location 1217 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location 1218 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location 1219 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length 1220 return Stream.EmitAbbrev(Abbrev); 1221} 1222 1223namespace { 1224 // Trait used for the on-disk hash table of header search information. 1225 class HeaderFileInfoTrait { 1226 ASTWriter &Writer; 1227 const HeaderSearch &HS; 1228 1229 // Keep track of the framework names we've used during serialization. 1230 SmallVector<char, 128> FrameworkStringData; 1231 llvm::StringMap<unsigned> FrameworkNameOffset; 1232 1233 public: 1234 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS) 1235 : Writer(Writer), HS(HS) { } 1236 1237 typedef const char *key_type; 1238 typedef key_type key_type_ref; 1239 1240 typedef HeaderFileInfo data_type; 1241 typedef const data_type &data_type_ref; 1242 1243 static unsigned ComputeHash(const char *path) { 1244 // The hash is based only on the filename portion of the key, so that the 1245 // reader can match based on filenames when symlinking or excess path 1246 // elements ("foo/../", "../") change the form of the name. However, 1247 // complete path is still the key. 1248 return llvm::HashString(llvm::sys::path::filename(path)); 1249 } 1250 1251 std::pair<unsigned,unsigned> 1252 EmitKeyDataLength(raw_ostream& Out, const char *path, 1253 data_type_ref Data) { 1254 unsigned StrLen = strlen(path); 1255 clang::io::Emit16(Out, StrLen); 1256 unsigned DataLen = 1 + 2 + 4 + 4; 1257 clang::io::Emit8(Out, DataLen); 1258 return std::make_pair(StrLen + 1, DataLen); 1259 } 1260 1261 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) { 1262 Out.write(path, KeyLen); 1263 } 1264 1265 void EmitData(raw_ostream &Out, key_type_ref, 1266 data_type_ref Data, unsigned DataLen) { 1267 using namespace clang::io; 1268 uint64_t Start = Out.tell(); (void)Start; 1269 1270 unsigned char Flags = (Data.isImport << 5) 1271 | (Data.isPragmaOnce << 4) 1272 | (Data.DirInfo << 2) 1273 | (Data.Resolved << 1) 1274 | Data.IndexHeaderMapHeader; 1275 Emit8(Out, (uint8_t)Flags); 1276 Emit16(Out, (uint16_t) Data.NumIncludes); 1277 1278 if (!Data.ControllingMacro) 1279 Emit32(Out, (uint32_t)Data.ControllingMacroID); 1280 else 1281 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro)); 1282 1283 unsigned Offset = 0; 1284 if (!Data.Framework.empty()) { 1285 // If this header refers into a framework, save the framework name. 1286 llvm::StringMap<unsigned>::iterator Pos 1287 = FrameworkNameOffset.find(Data.Framework); 1288 if (Pos == FrameworkNameOffset.end()) { 1289 Offset = FrameworkStringData.size() + 1; 1290 FrameworkStringData.append(Data.Framework.begin(), 1291 Data.Framework.end()); 1292 FrameworkStringData.push_back(0); 1293 1294 FrameworkNameOffset[Data.Framework] = Offset; 1295 } else 1296 Offset = Pos->second; 1297 } 1298 Emit32(Out, Offset); 1299 1300 assert(Out.tell() - Start == DataLen && "Wrong data length"); 1301 } 1302 1303 const char *strings_begin() const { return FrameworkStringData.begin(); } 1304 const char *strings_end() const { return FrameworkStringData.end(); } 1305 }; 1306} // end anonymous namespace 1307 1308/// \brief Write the header search block for the list of files that 1309/// 1310/// \param HS The header search structure to save. 1311/// 1312/// \param Chain Whether we're creating a chained AST file. 1313void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) { 1314 SmallVector<const FileEntry *, 16> FilesByUID; 1315 HS.getFileMgr().GetUniqueIDMapping(FilesByUID); 1316 1317 if (FilesByUID.size() > HS.header_file_size()) 1318 FilesByUID.resize(HS.header_file_size()); 1319 1320 HeaderFileInfoTrait GeneratorTrait(*this, HS); 1321 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator; 1322 SmallVector<const char *, 4> SavedStrings; 1323 unsigned NumHeaderSearchEntries = 0; 1324 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) { 1325 const FileEntry *File = FilesByUID[UID]; 1326 if (!File) 1327 continue; 1328 1329 // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo 1330 // from the external source if it was not provided already. 1331 const HeaderFileInfo &HFI = HS.getFileInfo(File); 1332 if (HFI.External && Chain) 1333 continue; 1334 1335 // Turn the file name into an absolute path, if it isn't already. 1336 const char *Filename = File->getName(); 1337 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1338 1339 // If we performed any translation on the file name at all, we need to 1340 // save this string, since the generator will refer to it later. 1341 if (Filename != File->getName()) { 1342 Filename = strdup(Filename); 1343 SavedStrings.push_back(Filename); 1344 } 1345 1346 Generator.insert(Filename, HFI, GeneratorTrait); 1347 ++NumHeaderSearchEntries; 1348 } 1349 1350 // Create the on-disk hash table in a buffer. 1351 llvm::SmallString<4096> TableData; 1352 uint32_t BucketOffset; 1353 { 1354 llvm::raw_svector_ostream Out(TableData); 1355 // Make sure that no bucket is at offset 0 1356 clang::io::Emit32(Out, 0); 1357 BucketOffset = Generator.Emit(Out, GeneratorTrait); 1358 } 1359 1360 // Create a blob abbreviation 1361 using namespace llvm; 1362 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1363 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE)); 1364 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1365 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1366 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1367 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1368 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev); 1369 1370 // Write the header search table 1371 RecordData Record; 1372 Record.push_back(HEADER_SEARCH_TABLE); 1373 Record.push_back(BucketOffset); 1374 Record.push_back(NumHeaderSearchEntries); 1375 Record.push_back(TableData.size()); 1376 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end()); 1377 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str()); 1378 1379 // Free all of the strings we had to duplicate. 1380 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I) 1381 free((void*)SavedStrings[I]); 1382} 1383 1384/// \brief Writes the block containing the serialized form of the 1385/// source manager. 1386/// 1387/// TODO: We should probably use an on-disk hash table (stored in a 1388/// blob), indexed based on the file name, so that we only create 1389/// entries for files that we actually need. In the common case (no 1390/// errors), we probably won't have to create file entries for any of 1391/// the files in the AST. 1392void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, 1393 const Preprocessor &PP, 1394 StringRef isysroot) { 1395 RecordData Record; 1396 1397 // Enter the source manager block. 1398 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3); 1399 1400 // Abbreviations for the various kinds of source-location entries. 1401 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream); 1402 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream); 1403 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream); 1404 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream); 1405 1406 // Write out the source location entry table. We skip the first 1407 // entry, which is always the same dummy entry. 1408 std::vector<uint32_t> SLocEntryOffsets; 1409 // Write out the offsets of only source location file entries. 1410 // We will go through them in ASTReader::validateFileEntries(). 1411 std::vector<uint32_t> SLocFileEntryOffsets; 1412 RecordData PreloadSLocs; 1413 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1); 1414 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); 1415 I != N; ++I) { 1416 // Get this source location entry. 1417 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I); 1418 1419 // Record the offset of this source-location entry. 1420 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo()); 1421 1422 // Figure out which record code to use. 1423 unsigned Code; 1424 if (SLoc->isFile()) { 1425 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache(); 1426 if (Cache->OrigEntry) { 1427 Code = SM_SLOC_FILE_ENTRY; 1428 SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo()); 1429 } else 1430 Code = SM_SLOC_BUFFER_ENTRY; 1431 } else 1432 Code = SM_SLOC_EXPANSION_ENTRY; 1433 Record.clear(); 1434 Record.push_back(Code); 1435 1436 // Starting offset of this entry within this module, so skip the dummy. 1437 Record.push_back(SLoc->getOffset() - 2); 1438 if (SLoc->isFile()) { 1439 const SrcMgr::FileInfo &File = SLoc->getFile(); 1440 Record.push_back(File.getIncludeLoc().getRawEncoding()); 1441 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding 1442 Record.push_back(File.hasLineDirectives()); 1443 1444 const SrcMgr::ContentCache *Content = File.getContentCache(); 1445 if (Content->OrigEntry) { 1446 assert(Content->OrigEntry == Content->ContentsEntry && 1447 "Writing to AST an overridden file is not supported"); 1448 1449 // The source location entry is a file. The blob associated 1450 // with this entry is the file name. 1451 1452 // Emit size/modification time for this file. 1453 Record.push_back(Content->OrigEntry->getSize()); 1454 Record.push_back(Content->OrigEntry->getModificationTime()); 1455 Record.push_back(Content->BufferOverridden); 1456 Record.push_back(File.NumCreatedFIDs); 1457 1458 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(SLoc); 1459 if (FDI != FileDeclIDs.end()) { 1460 Record.push_back(FDI->second->FirstDeclIndex); 1461 Record.push_back(FDI->second->DeclIDs.size()); 1462 } else { 1463 Record.push_back(0); 1464 Record.push_back(0); 1465 } 1466 1467 // Turn the file name into an absolute path, if it isn't already. 1468 const char *Filename = Content->OrigEntry->getName(); 1469 llvm::SmallString<128> FilePath(Filename); 1470 1471 // Ask the file manager to fixup the relative path for us. This will 1472 // honor the working directory. 1473 SourceMgr.getFileManager().FixupRelativePath(FilePath); 1474 1475 // FIXME: This call to make_absolute shouldn't be necessary, the 1476 // call to FixupRelativePath should always return an absolute path. 1477 llvm::sys::fs::make_absolute(FilePath); 1478 Filename = FilePath.c_str(); 1479 1480 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1481 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename); 1482 1483 if (Content->BufferOverridden) { 1484 Record.clear(); 1485 Record.push_back(SM_SLOC_BUFFER_BLOB); 1486 const llvm::MemoryBuffer *Buffer 1487 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager()); 1488 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, 1489 StringRef(Buffer->getBufferStart(), 1490 Buffer->getBufferSize() + 1)); 1491 } 1492 } else { 1493 // The source location entry is a buffer. The blob associated 1494 // with this entry contains the contents of the buffer. 1495 1496 // We add one to the size so that we capture the trailing NULL 1497 // that is required by llvm::MemoryBuffer::getMemBuffer (on 1498 // the reader side). 1499 const llvm::MemoryBuffer *Buffer 1500 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager()); 1501 const char *Name = Buffer->getBufferIdentifier(); 1502 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, 1503 StringRef(Name, strlen(Name) + 1)); 1504 Record.clear(); 1505 Record.push_back(SM_SLOC_BUFFER_BLOB); 1506 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, 1507 StringRef(Buffer->getBufferStart(), 1508 Buffer->getBufferSize() + 1)); 1509 1510 if (strcmp(Name, "<built-in>") == 0) { 1511 PreloadSLocs.push_back(SLocEntryOffsets.size()); 1512 } 1513 } 1514 } else { 1515 // The source location entry is a macro expansion. 1516 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion(); 1517 Record.push_back(Expansion.getSpellingLoc().getRawEncoding()); 1518 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding()); 1519 Record.push_back(Expansion.isMacroArgExpansion() ? 0 1520 : Expansion.getExpansionLocEnd().getRawEncoding()); 1521 1522 // Compute the token length for this macro expansion. 1523 unsigned NextOffset = SourceMgr.getNextLocalOffset(); 1524 if (I + 1 != N) 1525 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset(); 1526 Record.push_back(NextOffset - SLoc->getOffset() - 1); 1527 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record); 1528 } 1529 } 1530 1531 Stream.ExitBlock(); 1532 1533 if (SLocEntryOffsets.empty()) 1534 return; 1535 1536 // Write the source-location offsets table into the AST block. This 1537 // table is used for lazily loading source-location information. 1538 using namespace llvm; 1539 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1540 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS)); 1541 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 1542 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size 1543 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 1544 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); 1545 1546 Record.clear(); 1547 Record.push_back(SOURCE_LOCATION_OFFSETS); 1548 Record.push_back(SLocEntryOffsets.size()); 1549 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy 1550 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets)); 1551 1552 Abbrev = new BitCodeAbbrev(); 1553 Abbrev->Add(BitCodeAbbrevOp(FILE_SOURCE_LOCATION_OFFSETS)); 1554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 1555 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 1556 unsigned SLocFileOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); 1557 1558 Record.clear(); 1559 Record.push_back(FILE_SOURCE_LOCATION_OFFSETS); 1560 Record.push_back(SLocFileEntryOffsets.size()); 1561 Stream.EmitRecordWithBlob(SLocFileOffsetsAbbrev, Record, 1562 data(SLocFileEntryOffsets)); 1563 1564 // Write the source location entry preloads array, telling the AST 1565 // reader which source locations entries it should load eagerly. 1566 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs); 1567 1568 // Write the line table. It depends on remapping working, so it must come 1569 // after the source location offsets. 1570 if (SourceMgr.hasLineTable()) { 1571 LineTableInfo &LineTable = SourceMgr.getLineTable(); 1572 1573 Record.clear(); 1574 // Emit the file names 1575 Record.push_back(LineTable.getNumFilenames()); 1576 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) { 1577 // Emit the file name 1578 const char *Filename = LineTable.getFilename(I); 1579 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1580 unsigned FilenameLen = Filename? strlen(Filename) : 0; 1581 Record.push_back(FilenameLen); 1582 if (FilenameLen) 1583 Record.insert(Record.end(), Filename, Filename + FilenameLen); 1584 } 1585 1586 // Emit the line entries 1587 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end(); 1588 L != LEnd; ++L) { 1589 // Only emit entries for local files. 1590 if (L->first < 0) 1591 continue; 1592 1593 // Emit the file ID 1594 Record.push_back(L->first); 1595 1596 // Emit the line entries 1597 Record.push_back(L->second.size()); 1598 for (std::vector<LineEntry>::iterator LE = L->second.begin(), 1599 LEEnd = L->second.end(); 1600 LE != LEEnd; ++LE) { 1601 Record.push_back(LE->FileOffset); 1602 Record.push_back(LE->LineNo); 1603 Record.push_back(LE->FilenameID); 1604 Record.push_back((unsigned)LE->FileKind); 1605 Record.push_back(LE->IncludeOffset); 1606 } 1607 } 1608 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record); 1609 } 1610} 1611 1612//===----------------------------------------------------------------------===// 1613// Preprocessor Serialization 1614//===----------------------------------------------------------------------===// 1615 1616static int compareMacroDefinitions(const void *XPtr, const void *YPtr) { 1617 const std::pair<const IdentifierInfo *, MacroInfo *> &X = 1618 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr; 1619 const std::pair<const IdentifierInfo *, MacroInfo *> &Y = 1620 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr; 1621 return X.first->getName().compare(Y.first->getName()); 1622} 1623 1624/// \brief Writes the block containing the serialized form of the 1625/// preprocessor. 1626/// 1627void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) { 1628 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 1629 if (PPRec) 1630 WritePreprocessorDetail(*PPRec); 1631 1632 RecordData Record; 1633 1634 // If the preprocessor __COUNTER__ value has been bumped, remember it. 1635 if (PP.getCounterValue() != 0) { 1636 Record.push_back(PP.getCounterValue()); 1637 Stream.EmitRecord(PP_COUNTER_VALUE, Record); 1638 Record.clear(); 1639 } 1640 1641 // Enter the preprocessor block. 1642 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3); 1643 1644 // If the AST file contains __DATE__ or __TIME__ emit a warning about this. 1645 // FIXME: use diagnostics subsystem for localization etc. 1646 if (PP.SawDateOrTime()) 1647 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n"); 1648 1649 1650 // Loop over all the macro definitions that are live at the end of the file, 1651 // emitting each to the PP section. 1652 1653 // Construct the list of macro definitions that need to be serialized. 1654 SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2> 1655 MacrosToEmit; 1656 llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen; 1657 for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0), 1658 E = PP.macro_end(Chain == 0); 1659 I != E; ++I) { 1660 if (!IsModule || I->second->isPublic()) { 1661 MacroDefinitionsSeen.insert(I->first); 1662 MacrosToEmit.push_back(std::make_pair(I->first, I->second)); 1663 } 1664 } 1665 1666 // Sort the set of macro definitions that need to be serialized by the 1667 // name of the macro, to provide a stable ordering. 1668 llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(), 1669 &compareMacroDefinitions); 1670 1671 // Resolve any identifiers that defined macros at the time they were 1672 // deserialized, adding them to the list of macros to emit (if appropriate). 1673 for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) { 1674 IdentifierInfo *Name 1675 = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]); 1676 if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name)) 1677 MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name))); 1678 } 1679 1680 for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) { 1681 const IdentifierInfo *Name = MacrosToEmit[I].first; 1682 MacroInfo *MI = MacrosToEmit[I].second; 1683 if (!MI) 1684 continue; 1685 1686 // Don't emit builtin macros like __LINE__ to the AST file unless they have 1687 // been redefined by the header (in which case they are not isBuiltinMacro). 1688 // Also skip macros from a AST file if we're chaining. 1689 1690 // FIXME: There is a (probably minor) optimization we could do here, if 1691 // the macro comes from the original PCH but the identifier comes from a 1692 // chained PCH, by storing the offset into the original PCH rather than 1693 // writing the macro definition a second time. 1694 if (MI->isBuiltinMacro() || 1695 (Chain && 1696 Name->isFromAST() && !Name->hasChangedSinceDeserialization() && 1697 MI->isFromAST() && !MI->hasChangedAfterLoad())) 1698 continue; 1699 1700 AddIdentifierRef(Name, Record); 1701 MacroOffsets[Name] = Stream.GetCurrentBitNo(); 1702 Record.push_back(MI->getDefinitionLoc().getRawEncoding()); 1703 Record.push_back(MI->isUsed()); 1704 Record.push_back(MI->isPublic()); 1705 AddSourceLocation(MI->getVisibilityLocation(), Record); 1706 unsigned Code; 1707 if (MI->isObjectLike()) { 1708 Code = PP_MACRO_OBJECT_LIKE; 1709 } else { 1710 Code = PP_MACRO_FUNCTION_LIKE; 1711 1712 Record.push_back(MI->isC99Varargs()); 1713 Record.push_back(MI->isGNUVarargs()); 1714 Record.push_back(MI->getNumArgs()); 1715 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); 1716 I != E; ++I) 1717 AddIdentifierRef(*I, Record); 1718 } 1719 1720 // If we have a detailed preprocessing record, record the macro definition 1721 // ID that corresponds to this macro. 1722 if (PPRec) 1723 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]); 1724 1725 Stream.EmitRecord(Code, Record); 1726 Record.clear(); 1727 1728 // Emit the tokens array. 1729 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) { 1730 // Note that we know that the preprocessor does not have any annotation 1731 // tokens in it because they are created by the parser, and thus can't be 1732 // in a macro definition. 1733 const Token &Tok = MI->getReplacementToken(TokNo); 1734 1735 Record.push_back(Tok.getLocation().getRawEncoding()); 1736 Record.push_back(Tok.getLength()); 1737 1738 // FIXME: When reading literal tokens, reconstruct the literal pointer if 1739 // it is needed. 1740 AddIdentifierRef(Tok.getIdentifierInfo(), Record); 1741 // FIXME: Should translate token kind to a stable encoding. 1742 Record.push_back(Tok.getKind()); 1743 // FIXME: Should translate token flags to a stable encoding. 1744 Record.push_back(Tok.getFlags()); 1745 1746 Stream.EmitRecord(PP_TOKEN, Record); 1747 Record.clear(); 1748 } 1749 ++NumMacros; 1750 } 1751 Stream.ExitBlock(); 1752} 1753 1754void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) { 1755 if (PPRec.local_begin() == PPRec.local_end()) 1756 return; 1757 1758 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets; 1759 1760 // Enter the preprocessor block. 1761 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3); 1762 1763 // If the preprocessor has a preprocessing record, emit it. 1764 unsigned NumPreprocessingRecords = 0; 1765 using namespace llvm; 1766 1767 // Set up the abbreviation for 1768 unsigned InclusionAbbrev = 0; 1769 { 1770 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1771 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE)); 1772 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length 1773 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes 1774 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind 1775 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1776 InclusionAbbrev = Stream.EmitAbbrev(Abbrev); 1777 } 1778 1779 unsigned FirstPreprocessorEntityID 1780 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0) 1781 + NUM_PREDEF_PP_ENTITY_IDS; 1782 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID; 1783 RecordData Record; 1784 for (PreprocessingRecord::iterator E = PPRec.local_begin(), 1785 EEnd = PPRec.local_end(); 1786 E != EEnd; 1787 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) { 1788 Record.clear(); 1789 1790 PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(), 1791 Stream.GetCurrentBitNo())); 1792 1793 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) { 1794 // Record this macro definition's ID. 1795 MacroDefinitions[MD] = NextPreprocessorEntityID; 1796 1797 AddIdentifierRef(MD->getName(), Record); 1798 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record); 1799 continue; 1800 } 1801 1802 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) { 1803 Record.push_back(ME->isBuiltinMacro()); 1804 if (ME->isBuiltinMacro()) 1805 AddIdentifierRef(ME->getName(), Record); 1806 else 1807 Record.push_back(MacroDefinitions[ME->getDefinition()]); 1808 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record); 1809 continue; 1810 } 1811 1812 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) { 1813 Record.push_back(PPD_INCLUSION_DIRECTIVE); 1814 Record.push_back(ID->getFileName().size()); 1815 Record.push_back(ID->wasInQuotes()); 1816 Record.push_back(static_cast<unsigned>(ID->getKind())); 1817 llvm::SmallString<64> Buffer; 1818 Buffer += ID->getFileName(); 1819 Buffer += ID->getFile()->getName(); 1820 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer); 1821 continue; 1822 } 1823 1824 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter"); 1825 } 1826 Stream.ExitBlock(); 1827 1828 // Write the offsets table for the preprocessing record. 1829 if (NumPreprocessingRecords > 0) { 1830 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords); 1831 1832 // Write the offsets table for identifier IDs. 1833 using namespace llvm; 1834 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1835 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS)); 1836 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity 1837 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1838 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1839 1840 Record.clear(); 1841 Record.push_back(PPD_ENTITIES_OFFSETS); 1842 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS); 1843 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record, 1844 data(PreprocessedEntityOffsets)); 1845 } 1846} 1847 1848/// \brief Compute the number of modules within the given tree (including the 1849/// given module). 1850static unsigned getNumberOfModules(Module *Mod) { 1851 unsigned ChildModules = 0; 1852 for (llvm::StringMap<Module *>::iterator Sub = Mod->SubModules.begin(), 1853 SubEnd = Mod->SubModules.end(); 1854 Sub != SubEnd; ++Sub) 1855 ChildModules += getNumberOfModules(Sub->getValue()); 1856 1857 return ChildModules + 1; 1858} 1859 1860void ASTWriter::WriteSubmodules(Module *WritingModule) { 1861 // Enter the submodule description block. 1862 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 1863 1864 // Write the abbreviations needed for the submodules block. 1865 using namespace llvm; 1866 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1867 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION)); 1868 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent 1869 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework 1870 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit 1871 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1872 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev); 1873 1874 Abbrev = new BitCodeAbbrev(); 1875 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA)); 1876 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1877 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev); 1878 1879 Abbrev = new BitCodeAbbrev(); 1880 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER)); 1881 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1882 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev); 1883 1884 // Write the submodule metadata block. 1885 RecordData Record; 1886 Record.push_back(getNumberOfModules(WritingModule)); 1887 Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS); 1888 Stream.EmitRecord(SUBMODULE_METADATA, Record); 1889 1890 // Write all of the submodules. 1891 std::queue<Module *> Q; 1892 Q.push(WritingModule); 1893 while (!Q.empty()) { 1894 Module *Mod = Q.front(); 1895 Q.pop(); 1896 SubmoduleIDs[Mod] = NextSubmoduleID++; 1897 1898 // Emit the definition of the block. 1899 Record.clear(); 1900 Record.push_back(SUBMODULE_DEFINITION); 1901 if (Mod->Parent) { 1902 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?"); 1903 Record.push_back(SubmoduleIDs[Mod->Parent]); 1904 } else { 1905 Record.push_back(0); 1906 } 1907 Record.push_back(Mod->IsFramework); 1908 Record.push_back(Mod->IsExplicit); 1909 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name); 1910 1911 // Emit the umbrella header, if there is one. 1912 if (Mod->UmbrellaHeader) { 1913 Record.clear(); 1914 Record.push_back(SUBMODULE_UMBRELLA); 1915 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record, 1916 Mod->UmbrellaHeader->getName()); 1917 } 1918 1919 // Emit the headers. 1920 for (unsigned I = 0, N = Mod->Headers.size(); I != N; ++I) { 1921 Record.clear(); 1922 Record.push_back(SUBMODULE_HEADER); 1923 Stream.EmitRecordWithBlob(HeaderAbbrev, Record, 1924 Mod->Headers[I]->getName()); 1925 } 1926 1927 // Queue up the submodules of this module. 1928 llvm::SmallVector<StringRef, 2> SubModules; 1929 1930 // Sort the submodules first, so we get a predictable ordering in the AST 1931 // file. 1932 for (llvm::StringMap<Module *>::iterator 1933 Sub = Mod->SubModules.begin(), 1934 SubEnd = Mod->SubModules.end(); 1935 Sub != SubEnd; ++Sub) 1936 SubModules.push_back(Sub->getKey()); 1937 llvm::array_pod_sort(SubModules.begin(), SubModules.end()); 1938 1939 for (unsigned I = 0, N = SubModules.size(); I != N; ++I) 1940 Q.push(Mod->SubModules[SubModules[I]]); 1941 } 1942 1943 Stream.ExitBlock(); 1944} 1945 1946serialization::SubmoduleID 1947ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) { 1948 if (Loc.isInvalid() || SubmoduleIDs.empty()) 1949 return 0; // No submodule 1950 1951 // Use the expansion location to determine which module we're in. 1952 SourceManager &SrcMgr = PP->getSourceManager(); 1953 SourceLocation ExpansionLoc = SrcMgr.getExpansionLoc(Loc); 1954 if (!ExpansionLoc.isFileID()) 1955 return 0; 1956 1957 1958 FileID ExpansionFileID = SrcMgr.getFileID(ExpansionLoc); 1959 const FileEntry *ExpansionFile = SrcMgr.getFileEntryForID(ExpansionFileID); 1960 if (!ExpansionFile) 1961 return 0; 1962 1963 // Find the module that owns this header. 1964 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap(); 1965 Module *OwningMod = ModMap.findModuleForHeader(ExpansionFile); 1966 if (!OwningMod) 1967 return 0; 1968 1969 // Check whether we known about this submodule. 1970 llvm::DenseMap<Module *, unsigned>::iterator Known 1971 = SubmoduleIDs.find(OwningMod); 1972 if (Known == SubmoduleIDs.end()) 1973 return 0; 1974 1975 return Known->second; 1976} 1977 1978void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag) { 1979 RecordData Record; 1980 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator 1981 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end(); 1982 I != E; ++I) { 1983 const DiagnosticsEngine::DiagStatePoint &point = *I; 1984 if (point.Loc.isInvalid()) 1985 continue; 1986 1987 Record.push_back(point.Loc.getRawEncoding()); 1988 for (DiagnosticsEngine::DiagState::const_iterator 1989 I = point.State->begin(), E = point.State->end(); I != E; ++I) { 1990 if (I->second.isPragma()) { 1991 Record.push_back(I->first); 1992 Record.push_back(I->second.getMapping()); 1993 } 1994 } 1995 Record.push_back(-1); // mark the end of the diag/map pairs for this 1996 // location. 1997 } 1998 1999 if (!Record.empty()) 2000 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record); 2001} 2002 2003void ASTWriter::WriteCXXBaseSpecifiersOffsets() { 2004 if (CXXBaseSpecifiersOffsets.empty()) 2005 return; 2006 2007 RecordData Record; 2008 2009 // Create a blob abbreviation for the C++ base specifiers offsets. 2010 using namespace llvm; 2011 2012 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2013 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS)); 2014 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 2015 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2016 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2017 2018 // Write the base specifier offsets table. 2019 Record.clear(); 2020 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS); 2021 Record.push_back(CXXBaseSpecifiersOffsets.size()); 2022 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record, 2023 data(CXXBaseSpecifiersOffsets)); 2024} 2025 2026//===----------------------------------------------------------------------===// 2027// Type Serialization 2028//===----------------------------------------------------------------------===// 2029 2030/// \brief Write the representation of a type to the AST stream. 2031void ASTWriter::WriteType(QualType T) { 2032 TypeIdx &Idx = TypeIdxs[T]; 2033 if (Idx.getIndex() == 0) // we haven't seen this type before. 2034 Idx = TypeIdx(NextTypeID++); 2035 2036 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST"); 2037 2038 // Record the offset for this type. 2039 unsigned Index = Idx.getIndex() - FirstTypeID; 2040 if (TypeOffsets.size() == Index) 2041 TypeOffsets.push_back(Stream.GetCurrentBitNo()); 2042 else if (TypeOffsets.size() < Index) { 2043 TypeOffsets.resize(Index + 1); 2044 TypeOffsets[Index] = Stream.GetCurrentBitNo(); 2045 } 2046 2047 RecordData Record; 2048 2049 // Emit the type's representation. 2050 ASTTypeWriter W(*this, Record); 2051 2052 if (T.hasLocalNonFastQualifiers()) { 2053 Qualifiers Qs = T.getLocalQualifiers(); 2054 AddTypeRef(T.getLocalUnqualifiedType(), Record); 2055 Record.push_back(Qs.getAsOpaqueValue()); 2056 W.Code = TYPE_EXT_QUAL; 2057 } else { 2058 switch (T->getTypeClass()) { 2059 // For all of the concrete, non-dependent types, call the 2060 // appropriate visitor function. 2061#define TYPE(Class, Base) \ 2062 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break; 2063#define ABSTRACT_TYPE(Class, Base) 2064#include "clang/AST/TypeNodes.def" 2065 } 2066 } 2067 2068 // Emit the serialized record. 2069 Stream.EmitRecord(W.Code, Record); 2070 2071 // Flush any expressions that were written as part of this type. 2072 FlushStmts(); 2073} 2074 2075//===----------------------------------------------------------------------===// 2076// Declaration Serialization 2077//===----------------------------------------------------------------------===// 2078 2079/// \brief Write the block containing all of the declaration IDs 2080/// lexically declared within the given DeclContext. 2081/// 2082/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the 2083/// bistream, or 0 if no block was written. 2084uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context, 2085 DeclContext *DC) { 2086 if (DC->decls_empty()) 2087 return 0; 2088 2089 uint64_t Offset = Stream.GetCurrentBitNo(); 2090 RecordData Record; 2091 Record.push_back(DECL_CONTEXT_LEXICAL); 2092 SmallVector<KindDeclIDPair, 64> Decls; 2093 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end(); 2094 D != DEnd; ++D) 2095 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D))); 2096 2097 ++NumLexicalDeclContexts; 2098 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls)); 2099 return Offset; 2100} 2101 2102void ASTWriter::WriteTypeDeclOffsets() { 2103 using namespace llvm; 2104 RecordData Record; 2105 2106 // Write the type offsets array 2107 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2108 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET)); 2109 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types 2110 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index 2111 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block 2112 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2113 Record.clear(); 2114 Record.push_back(TYPE_OFFSET); 2115 Record.push_back(TypeOffsets.size()); 2116 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS); 2117 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets)); 2118 2119 // Write the declaration offsets array 2120 Abbrev = new BitCodeAbbrev(); 2121 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET)); 2122 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations 2123 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID 2124 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block 2125 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2126 Record.clear(); 2127 Record.push_back(DECL_OFFSET); 2128 Record.push_back(DeclOffsets.size()); 2129 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS); 2130 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets)); 2131} 2132 2133void ASTWriter::WriteFileDeclIDsMap() { 2134 using namespace llvm; 2135 RecordData Record; 2136 2137 // Join the vectors of DeclIDs from all files. 2138 SmallVector<DeclID, 256> FileSortedIDs; 2139 for (FileDeclIDsTy::iterator 2140 FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) { 2141 DeclIDInFileInfo &Info = *FI->second; 2142 Info.FirstDeclIndex = FileSortedIDs.size(); 2143 for (LocDeclIDsTy::iterator 2144 DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI) 2145 FileSortedIDs.push_back(DI->second); 2146 } 2147 2148 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2149 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS)); 2150 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2151 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev); 2152 Record.push_back(FILE_SORTED_DECLS); 2153 Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs)); 2154} 2155 2156//===----------------------------------------------------------------------===// 2157// Global Method Pool and Selector Serialization 2158//===----------------------------------------------------------------------===// 2159 2160namespace { 2161// Trait used for the on-disk hash table used in the method pool. 2162class ASTMethodPoolTrait { 2163 ASTWriter &Writer; 2164 2165public: 2166 typedef Selector key_type; 2167 typedef key_type key_type_ref; 2168 2169 struct data_type { 2170 SelectorID ID; 2171 ObjCMethodList Instance, Factory; 2172 }; 2173 typedef const data_type& data_type_ref; 2174 2175 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { } 2176 2177 static unsigned ComputeHash(Selector Sel) { 2178 return serialization::ComputeHash(Sel); 2179 } 2180 2181 std::pair<unsigned,unsigned> 2182 EmitKeyDataLength(raw_ostream& Out, Selector Sel, 2183 data_type_ref Methods) { 2184 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4); 2185 clang::io::Emit16(Out, KeyLen); 2186 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts 2187 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2188 Method = Method->Next) 2189 if (Method->Method) 2190 DataLen += 4; 2191 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2192 Method = Method->Next) 2193 if (Method->Method) 2194 DataLen += 4; 2195 clang::io::Emit16(Out, DataLen); 2196 return std::make_pair(KeyLen, DataLen); 2197 } 2198 2199 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) { 2200 uint64_t Start = Out.tell(); 2201 assert((Start >> 32) == 0 && "Selector key offset too large"); 2202 Writer.SetSelectorOffset(Sel, Start); 2203 unsigned N = Sel.getNumArgs(); 2204 clang::io::Emit16(Out, N); 2205 if (N == 0) 2206 N = 1; 2207 for (unsigned I = 0; I != N; ++I) 2208 clang::io::Emit32(Out, 2209 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I))); 2210 } 2211 2212 void EmitData(raw_ostream& Out, key_type_ref, 2213 data_type_ref Methods, unsigned DataLen) { 2214 uint64_t Start = Out.tell(); (void)Start; 2215 clang::io::Emit32(Out, Methods.ID); 2216 unsigned NumInstanceMethods = 0; 2217 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2218 Method = Method->Next) 2219 if (Method->Method) 2220 ++NumInstanceMethods; 2221 2222 unsigned NumFactoryMethods = 0; 2223 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2224 Method = Method->Next) 2225 if (Method->Method) 2226 ++NumFactoryMethods; 2227 2228 clang::io::Emit16(Out, NumInstanceMethods); 2229 clang::io::Emit16(Out, NumFactoryMethods); 2230 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2231 Method = Method->Next) 2232 if (Method->Method) 2233 clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); 2234 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2235 Method = Method->Next) 2236 if (Method->Method) 2237 clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); 2238 2239 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 2240 } 2241}; 2242} // end anonymous namespace 2243 2244/// \brief Write ObjC data: selectors and the method pool. 2245/// 2246/// The method pool contains both instance and factory methods, stored 2247/// in an on-disk hash table indexed by the selector. The hash table also 2248/// contains an empty entry for every other selector known to Sema. 2249void ASTWriter::WriteSelectors(Sema &SemaRef) { 2250 using namespace llvm; 2251 2252 // Do we have to do anything at all? 2253 if (SemaRef.MethodPool.empty() && SelectorIDs.empty()) 2254 return; 2255 unsigned NumTableEntries = 0; 2256 // Create and write out the blob that contains selectors and the method pool. 2257 { 2258 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator; 2259 ASTMethodPoolTrait Trait(*this); 2260 2261 // Create the on-disk hash table representation. We walk through every 2262 // selector we've seen and look it up in the method pool. 2263 SelectorOffsets.resize(NextSelectorID - FirstSelectorID); 2264 for (llvm::DenseMap<Selector, SelectorID>::iterator 2265 I = SelectorIDs.begin(), E = SelectorIDs.end(); 2266 I != E; ++I) { 2267 Selector S = I->first; 2268 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S); 2269 ASTMethodPoolTrait::data_type Data = { 2270 I->second, 2271 ObjCMethodList(), 2272 ObjCMethodList() 2273 }; 2274 if (F != SemaRef.MethodPool.end()) { 2275 Data.Instance = F->second.first; 2276 Data.Factory = F->second.second; 2277 } 2278 // Only write this selector if it's not in an existing AST or something 2279 // changed. 2280 if (Chain && I->second < FirstSelectorID) { 2281 // Selector already exists. Did it change? 2282 bool changed = false; 2283 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method; 2284 M = M->Next) { 2285 if (!M->Method->isFromASTFile()) 2286 changed = true; 2287 } 2288 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method; 2289 M = M->Next) { 2290 if (!M->Method->isFromASTFile()) 2291 changed = true; 2292 } 2293 if (!changed) 2294 continue; 2295 } else if (Data.Instance.Method || Data.Factory.Method) { 2296 // A new method pool entry. 2297 ++NumTableEntries; 2298 } 2299 Generator.insert(S, Data, Trait); 2300 } 2301 2302 // Create the on-disk hash table in a buffer. 2303 llvm::SmallString<4096> MethodPool; 2304 uint32_t BucketOffset; 2305 { 2306 ASTMethodPoolTrait Trait(*this); 2307 llvm::raw_svector_ostream Out(MethodPool); 2308 // Make sure that no bucket is at offset 0 2309 clang::io::Emit32(Out, 0); 2310 BucketOffset = Generator.Emit(Out, Trait); 2311 } 2312 2313 // Create a blob abbreviation 2314 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2315 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL)); 2316 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2317 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2318 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2319 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev); 2320 2321 // Write the method pool 2322 RecordData Record; 2323 Record.push_back(METHOD_POOL); 2324 Record.push_back(BucketOffset); 2325 Record.push_back(NumTableEntries); 2326 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str()); 2327 2328 // Create a blob abbreviation for the selector table offsets. 2329 Abbrev = new BitCodeAbbrev(); 2330 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS)); 2331 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 2332 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 2333 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2334 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2335 2336 // Write the selector offsets table. 2337 Record.clear(); 2338 Record.push_back(SELECTOR_OFFSETS); 2339 Record.push_back(SelectorOffsets.size()); 2340 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS); 2341 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record, 2342 data(SelectorOffsets)); 2343 } 2344} 2345 2346/// \brief Write the selectors referenced in @selector expression into AST file. 2347void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) { 2348 using namespace llvm; 2349 if (SemaRef.ReferencedSelectors.empty()) 2350 return; 2351 2352 RecordData Record; 2353 2354 // Note: this writes out all references even for a dependent AST. But it is 2355 // very tricky to fix, and given that @selector shouldn't really appear in 2356 // headers, probably not worth it. It's not a correctness issue. 2357 for (DenseMap<Selector, SourceLocation>::iterator S = 2358 SemaRef.ReferencedSelectors.begin(), 2359 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) { 2360 Selector Sel = (*S).first; 2361 SourceLocation Loc = (*S).second; 2362 AddSelectorRef(Sel, Record); 2363 AddSourceLocation(Loc, Record); 2364 } 2365 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record); 2366} 2367 2368//===----------------------------------------------------------------------===// 2369// Identifier Table Serialization 2370//===----------------------------------------------------------------------===// 2371 2372namespace { 2373class ASTIdentifierTableTrait { 2374 ASTWriter &Writer; 2375 Preprocessor &PP; 2376 IdentifierResolver &IdResolver; 2377 bool IsModule; 2378 2379 /// \brief Determines whether this is an "interesting" identifier 2380 /// that needs a full IdentifierInfo structure written into the hash 2381 /// table. 2382 bool isInterestingIdentifier(IdentifierInfo *II, MacroInfo *&Macro) { 2383 if (II->isPoisoned() || 2384 II->isExtensionToken() || 2385 II->getObjCOrBuiltinID() || 2386 II->hasRevertedTokenIDToIdentifier() || 2387 II->getFETokenInfo<void>()) 2388 return true; 2389 2390 return hasMacroDefinition(II, Macro); 2391 } 2392 2393 bool hasMacroDefinition(IdentifierInfo *II, MacroInfo *&Macro) { 2394 if (!II->hasMacroDefinition()) 2395 return false; 2396 2397 if (Macro || (Macro = PP.getMacroInfo(II))) 2398 return !Macro->isBuiltinMacro() && (!IsModule || Macro->isPublic()); 2399 2400 return false; 2401 } 2402 2403public: 2404 typedef IdentifierInfo* key_type; 2405 typedef key_type key_type_ref; 2406 2407 typedef IdentID data_type; 2408 typedef data_type data_type_ref; 2409 2410 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP, 2411 IdentifierResolver &IdResolver, bool IsModule) 2412 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { } 2413 2414 static unsigned ComputeHash(const IdentifierInfo* II) { 2415 return llvm::HashString(II->getName()); 2416 } 2417 2418 std::pair<unsigned,unsigned> 2419 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) { 2420 unsigned KeyLen = II->getLength() + 1; 2421 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1 2422 MacroInfo *Macro = 0; 2423 if (isInterestingIdentifier(II, Macro)) { 2424 DataLen += 2; // 2 bytes for builtin ID, flags 2425 if (hasMacroDefinition(II, Macro)) 2426 DataLen += 8; 2427 2428 for (IdentifierResolver::iterator D = IdResolver.begin(II), 2429 DEnd = IdResolver.end(); 2430 D != DEnd; ++D) 2431 DataLen += sizeof(DeclID); 2432 } 2433 clang::io::Emit16(Out, DataLen); 2434 // We emit the key length after the data length so that every 2435 // string is preceded by a 16-bit length. This matches the PTH 2436 // format for storing identifiers. 2437 clang::io::Emit16(Out, KeyLen); 2438 return std::make_pair(KeyLen, DataLen); 2439 } 2440 2441 void EmitKey(raw_ostream& Out, const IdentifierInfo* II, 2442 unsigned KeyLen) { 2443 // Record the location of the key data. This is used when generating 2444 // the mapping from persistent IDs to strings. 2445 Writer.SetIdentifierOffset(II, Out.tell()); 2446 Out.write(II->getNameStart(), KeyLen); 2447 } 2448 2449 void EmitData(raw_ostream& Out, IdentifierInfo* II, 2450 IdentID ID, unsigned) { 2451 MacroInfo *Macro = 0; 2452 if (!isInterestingIdentifier(II, Macro)) { 2453 clang::io::Emit32(Out, ID << 1); 2454 return; 2455 } 2456 2457 clang::io::Emit32(Out, (ID << 1) | 0x01); 2458 uint32_t Bits = 0; 2459 bool HasMacroDefinition = hasMacroDefinition(II, Macro); 2460 Bits = (uint32_t)II->getObjCOrBuiltinID(); 2461 Bits = (Bits << 1) | unsigned(HasMacroDefinition); 2462 Bits = (Bits << 1) | unsigned(II->isExtensionToken()); 2463 Bits = (Bits << 1) | unsigned(II->isPoisoned()); 2464 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier()); 2465 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword()); 2466 clang::io::Emit16(Out, Bits); 2467 2468 if (HasMacroDefinition) { 2469 clang::io::Emit32(Out, Writer.getMacroOffset(II)); 2470 clang::io::Emit32(Out, 2471 Writer.inferSubmoduleIDFromLocation(Macro->getDefinitionLoc())); 2472 } 2473 2474 // Emit the declaration IDs in reverse order, because the 2475 // IdentifierResolver provides the declarations as they would be 2476 // visible (e.g., the function "stat" would come before the struct 2477 // "stat"), but the ASTReader adds declarations to the end of the list 2478 // (so we need to see the struct "status" before the function "status"). 2479 // Only emit declarations that aren't from a chained PCH, though. 2480 SmallVector<Decl *, 16> Decls(IdResolver.begin(II), 2481 IdResolver.end()); 2482 for (SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(), 2483 DEnd = Decls.rend(); 2484 D != DEnd; ++D) 2485 clang::io::Emit32(Out, Writer.getDeclID(*D)); 2486 } 2487}; 2488} // end anonymous namespace 2489 2490/// \brief Write the identifier table into the AST file. 2491/// 2492/// The identifier table consists of a blob containing string data 2493/// (the actual identifiers themselves) and a separate "offsets" index 2494/// that maps identifier IDs to locations within the blob. 2495void ASTWriter::WriteIdentifierTable(Preprocessor &PP, 2496 IdentifierResolver &IdResolver, 2497 bool IsModule) { 2498 using namespace llvm; 2499 2500 // Create and write out the blob that contains the identifier 2501 // strings. 2502 { 2503 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator; 2504 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule); 2505 2506 // Look for any identifiers that were named while processing the 2507 // headers, but are otherwise not needed. We add these to the hash 2508 // table to enable checking of the predefines buffer in the case 2509 // where the user adds new macro definitions when building the AST 2510 // file. 2511 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 2512 IDEnd = PP.getIdentifierTable().end(); 2513 ID != IDEnd; ++ID) 2514 getIdentifierRef(ID->second); 2515 2516 // Create the on-disk hash table representation. We only store offsets 2517 // for identifiers that appear here for the first time. 2518 IdentifierOffsets.resize(NextIdentID - FirstIdentID); 2519 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator 2520 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end(); 2521 ID != IDEnd; ++ID) { 2522 assert(ID->first && "NULL identifier in identifier table"); 2523 if (!Chain || !ID->first->isFromAST() || 2524 ID->first->hasChangedSinceDeserialization()) 2525 Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second, 2526 Trait); 2527 } 2528 2529 // Create the on-disk hash table in a buffer. 2530 llvm::SmallString<4096> IdentifierTable; 2531 uint32_t BucketOffset; 2532 { 2533 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule); 2534 llvm::raw_svector_ostream Out(IdentifierTable); 2535 // Make sure that no bucket is at offset 0 2536 clang::io::Emit32(Out, 0); 2537 BucketOffset = Generator.Emit(Out, Trait); 2538 } 2539 2540 // Create a blob abbreviation 2541 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2542 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE)); 2543 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2544 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2545 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev); 2546 2547 // Write the identifier table 2548 RecordData Record; 2549 Record.push_back(IDENTIFIER_TABLE); 2550 Record.push_back(BucketOffset); 2551 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str()); 2552 } 2553 2554 // Write the offsets table for identifier IDs. 2555 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2556 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET)); 2557 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers 2558 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 2559 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2560 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2561 2562 RecordData Record; 2563 Record.push_back(IDENTIFIER_OFFSET); 2564 Record.push_back(IdentifierOffsets.size()); 2565 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS); 2566 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record, 2567 data(IdentifierOffsets)); 2568} 2569 2570//===----------------------------------------------------------------------===// 2571// DeclContext's Name Lookup Table Serialization 2572//===----------------------------------------------------------------------===// 2573 2574namespace { 2575// Trait used for the on-disk hash table used in the method pool. 2576class ASTDeclContextNameLookupTrait { 2577 ASTWriter &Writer; 2578 2579public: 2580 typedef DeclarationName key_type; 2581 typedef key_type key_type_ref; 2582 2583 typedef DeclContext::lookup_result data_type; 2584 typedef const data_type& data_type_ref; 2585 2586 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { } 2587 2588 unsigned ComputeHash(DeclarationName Name) { 2589 llvm::FoldingSetNodeID ID; 2590 ID.AddInteger(Name.getNameKind()); 2591 2592 switch (Name.getNameKind()) { 2593 case DeclarationName::Identifier: 2594 ID.AddString(Name.getAsIdentifierInfo()->getName()); 2595 break; 2596 case DeclarationName::ObjCZeroArgSelector: 2597 case DeclarationName::ObjCOneArgSelector: 2598 case DeclarationName::ObjCMultiArgSelector: 2599 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector())); 2600 break; 2601 case DeclarationName::CXXConstructorName: 2602 case DeclarationName::CXXDestructorName: 2603 case DeclarationName::CXXConversionFunctionName: 2604 break; 2605 case DeclarationName::CXXOperatorName: 2606 ID.AddInteger(Name.getCXXOverloadedOperator()); 2607 break; 2608 case DeclarationName::CXXLiteralOperatorName: 2609 ID.AddString(Name.getCXXLiteralIdentifier()->getName()); 2610 case DeclarationName::CXXUsingDirective: 2611 break; 2612 } 2613 2614 return ID.ComputeHash(); 2615 } 2616 2617 std::pair<unsigned,unsigned> 2618 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name, 2619 data_type_ref Lookup) { 2620 unsigned KeyLen = 1; 2621 switch (Name.getNameKind()) { 2622 case DeclarationName::Identifier: 2623 case DeclarationName::ObjCZeroArgSelector: 2624 case DeclarationName::ObjCOneArgSelector: 2625 case DeclarationName::ObjCMultiArgSelector: 2626 case DeclarationName::CXXLiteralOperatorName: 2627 KeyLen += 4; 2628 break; 2629 case DeclarationName::CXXOperatorName: 2630 KeyLen += 1; 2631 break; 2632 case DeclarationName::CXXConstructorName: 2633 case DeclarationName::CXXDestructorName: 2634 case DeclarationName::CXXConversionFunctionName: 2635 case DeclarationName::CXXUsingDirective: 2636 break; 2637 } 2638 clang::io::Emit16(Out, KeyLen); 2639 2640 // 2 bytes for num of decls and 4 for each DeclID. 2641 unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first); 2642 clang::io::Emit16(Out, DataLen); 2643 2644 return std::make_pair(KeyLen, DataLen); 2645 } 2646 2647 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) { 2648 using namespace clang::io; 2649 2650 assert(Name.getNameKind() < 0x100 && "Invalid name kind ?"); 2651 Emit8(Out, Name.getNameKind()); 2652 switch (Name.getNameKind()) { 2653 case DeclarationName::Identifier: 2654 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo())); 2655 break; 2656 case DeclarationName::ObjCZeroArgSelector: 2657 case DeclarationName::ObjCOneArgSelector: 2658 case DeclarationName::ObjCMultiArgSelector: 2659 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector())); 2660 break; 2661 case DeclarationName::CXXOperatorName: 2662 assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?"); 2663 Emit8(Out, Name.getCXXOverloadedOperator()); 2664 break; 2665 case DeclarationName::CXXLiteralOperatorName: 2666 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier())); 2667 break; 2668 case DeclarationName::CXXConstructorName: 2669 case DeclarationName::CXXDestructorName: 2670 case DeclarationName::CXXConversionFunctionName: 2671 case DeclarationName::CXXUsingDirective: 2672 break; 2673 } 2674 } 2675 2676 void EmitData(raw_ostream& Out, key_type_ref, 2677 data_type Lookup, unsigned DataLen) { 2678 uint64_t Start = Out.tell(); (void)Start; 2679 clang::io::Emit16(Out, Lookup.second - Lookup.first); 2680 for (; Lookup.first != Lookup.second; ++Lookup.first) 2681 clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first)); 2682 2683 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 2684 } 2685}; 2686} // end anonymous namespace 2687 2688/// \brief Write the block containing all of the declaration IDs 2689/// visible from the given DeclContext. 2690/// 2691/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the 2692/// bitstream, or 0 if no block was written. 2693uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context, 2694 DeclContext *DC) { 2695 if (DC->getPrimaryContext() != DC) 2696 return 0; 2697 2698 // Since there is no name lookup into functions or methods, don't bother to 2699 // build a visible-declarations table for these entities. 2700 if (DC->isFunctionOrMethod()) 2701 return 0; 2702 2703 // If not in C++, we perform name lookup for the translation unit via the 2704 // IdentifierInfo chains, don't bother to build a visible-declarations table. 2705 // FIXME: In C++ we need the visible declarations in order to "see" the 2706 // friend declarations, is there a way to do this without writing the table ? 2707 if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus) 2708 return 0; 2709 2710 // Force the DeclContext to build a its name-lookup table. 2711 if (!DC->hasExternalVisibleStorage()) 2712 DC->lookup(DeclarationName()); 2713 2714 // Serialize the contents of the mapping used for lookup. Note that, 2715 // although we have two very different code paths, the serialized 2716 // representation is the same for both cases: a declaration name, 2717 // followed by a size, followed by references to the visible 2718 // declarations that have that name. 2719 uint64_t Offset = Stream.GetCurrentBitNo(); 2720 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr()); 2721 if (!Map || Map->empty()) 2722 return 0; 2723 2724 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator; 2725 ASTDeclContextNameLookupTrait Trait(*this); 2726 2727 // Create the on-disk hash table representation. 2728 DeclarationName ConversionName; 2729 llvm::SmallVector<NamedDecl *, 4> ConversionDecls; 2730 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); 2731 D != DEnd; ++D) { 2732 DeclarationName Name = D->first; 2733 DeclContext::lookup_result Result = D->second.getLookupResult(); 2734 if (Result.first != Result.second) { 2735 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2736 // Hash all conversion function names to the same name. The actual 2737 // type information in conversion function name is not used in the 2738 // key (since such type information is not stable across different 2739 // modules), so the intended effect is to coalesce all of the conversion 2740 // functions under a single key. 2741 if (!ConversionName) 2742 ConversionName = Name; 2743 ConversionDecls.append(Result.first, Result.second); 2744 continue; 2745 } 2746 2747 Generator.insert(Name, Result, Trait); 2748 } 2749 } 2750 2751 // Add the conversion functions 2752 if (!ConversionDecls.empty()) { 2753 Generator.insert(ConversionName, 2754 DeclContext::lookup_result(ConversionDecls.begin(), 2755 ConversionDecls.end()), 2756 Trait); 2757 } 2758 2759 // Create the on-disk hash table in a buffer. 2760 llvm::SmallString<4096> LookupTable; 2761 uint32_t BucketOffset; 2762 { 2763 llvm::raw_svector_ostream Out(LookupTable); 2764 // Make sure that no bucket is at offset 0 2765 clang::io::Emit32(Out, 0); 2766 BucketOffset = Generator.Emit(Out, Trait); 2767 } 2768 2769 // Write the lookup table 2770 RecordData Record; 2771 Record.push_back(DECL_CONTEXT_VISIBLE); 2772 Record.push_back(BucketOffset); 2773 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record, 2774 LookupTable.str()); 2775 2776 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record); 2777 ++NumVisibleDeclContexts; 2778 return Offset; 2779} 2780 2781/// \brief Write an UPDATE_VISIBLE block for the given context. 2782/// 2783/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing 2784/// DeclContext in a dependent AST file. As such, they only exist for the TU 2785/// (in C++) and for namespaces. 2786void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) { 2787 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr()); 2788 if (!Map || Map->empty()) 2789 return; 2790 2791 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator; 2792 ASTDeclContextNameLookupTrait Trait(*this); 2793 2794 // Create the hash table. 2795 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); 2796 D != DEnd; ++D) { 2797 DeclarationName Name = D->first; 2798 DeclContext::lookup_result Result = D->second.getLookupResult(); 2799 // For any name that appears in this table, the results are complete, i.e. 2800 // they overwrite results from previous PCHs. Merging is always a mess. 2801 if (Result.first != Result.second) 2802 Generator.insert(Name, Result, Trait); 2803 } 2804 2805 // Create the on-disk hash table in a buffer. 2806 llvm::SmallString<4096> LookupTable; 2807 uint32_t BucketOffset; 2808 { 2809 llvm::raw_svector_ostream Out(LookupTable); 2810 // Make sure that no bucket is at offset 0 2811 clang::io::Emit32(Out, 0); 2812 BucketOffset = Generator.Emit(Out, Trait); 2813 } 2814 2815 // Write the lookup table 2816 RecordData Record; 2817 Record.push_back(UPDATE_VISIBLE); 2818 Record.push_back(getDeclID(cast<Decl>(DC))); 2819 Record.push_back(BucketOffset); 2820 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str()); 2821} 2822 2823/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions. 2824void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) { 2825 RecordData Record; 2826 Record.push_back(Opts.fp_contract); 2827 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record); 2828} 2829 2830/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions. 2831void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) { 2832 if (!SemaRef.Context.getLangOptions().OpenCL) 2833 return; 2834 2835 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions(); 2836 RecordData Record; 2837#define OPENCLEXT(nm) Record.push_back(Opts.nm); 2838#include "clang/Basic/OpenCLExtensions.def" 2839 Stream.EmitRecord(OPENCL_EXTENSIONS, Record); 2840} 2841 2842//===----------------------------------------------------------------------===// 2843// General Serialization Routines 2844//===----------------------------------------------------------------------===// 2845 2846/// \brief Write a record containing the given attributes. 2847void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) { 2848 Record.push_back(Attrs.size()); 2849 for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){ 2850 const Attr * A = *i; 2851 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs 2852 AddSourceRange(A->getRange(), Record); 2853 2854#include "clang/Serialization/AttrPCHWrite.inc" 2855 2856 } 2857} 2858 2859void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) { 2860 Record.push_back(Str.size()); 2861 Record.insert(Record.end(), Str.begin(), Str.end()); 2862} 2863 2864void ASTWriter::AddVersionTuple(const VersionTuple &Version, 2865 RecordDataImpl &Record) { 2866 Record.push_back(Version.getMajor()); 2867 if (llvm::Optional<unsigned> Minor = Version.getMinor()) 2868 Record.push_back(*Minor + 1); 2869 else 2870 Record.push_back(0); 2871 if (llvm::Optional<unsigned> Subminor = Version.getSubminor()) 2872 Record.push_back(*Subminor + 1); 2873 else 2874 Record.push_back(0); 2875} 2876 2877/// \brief Note that the identifier II occurs at the given offset 2878/// within the identifier table. 2879void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) { 2880 IdentID ID = IdentifierIDs[II]; 2881 // Only store offsets new to this AST file. Other identifier names are looked 2882 // up earlier in the chain and thus don't need an offset. 2883 if (ID >= FirstIdentID) 2884 IdentifierOffsets[ID - FirstIdentID] = Offset; 2885} 2886 2887/// \brief Note that the selector Sel occurs at the given offset 2888/// within the method pool/selector table. 2889void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { 2890 unsigned ID = SelectorIDs[Sel]; 2891 assert(ID && "Unknown selector"); 2892 // Don't record offsets for selectors that are also available in a different 2893 // file. 2894 if (ID < FirstSelectorID) 2895 return; 2896 SelectorOffsets[ID - FirstSelectorID] = Offset; 2897} 2898 2899ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream) 2900 : Stream(Stream), Context(0), PP(0), Chain(0), WritingAST(false), 2901 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID), 2902 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID), 2903 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID), 2904 FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS), 2905 NextSubmoduleID(FirstSubmoduleID), 2906 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID), 2907 CollectedStmts(&StmtsToEmit), 2908 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0), 2909 NumVisibleDeclContexts(0), 2910 NextCXXBaseSpecifiersID(1), 2911 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0), 2912 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0), 2913 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0), 2914 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0), 2915 DeclTypedefAbbrev(0), 2916 DeclVarAbbrev(0), DeclFieldAbbrev(0), 2917 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0) 2918{ 2919} 2920 2921ASTWriter::~ASTWriter() { 2922 for (FileDeclIDsTy::iterator 2923 I = FileDeclIDs.begin(), E = FileDeclIDs.end(); I != E; ++I) 2924 delete I->second; 2925} 2926 2927void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls, 2928 const std::string &OutputFile, 2929 Module *WritingModule, StringRef isysroot) { 2930 WritingAST = true; 2931 2932 // Emit the file header. 2933 Stream.Emit((unsigned)'C', 8); 2934 Stream.Emit((unsigned)'P', 8); 2935 Stream.Emit((unsigned)'C', 8); 2936 Stream.Emit((unsigned)'H', 8); 2937 2938 WriteBlockInfoBlock(); 2939 2940 Context = &SemaRef.Context; 2941 PP = &SemaRef.PP; 2942 WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile, WritingModule); 2943 Context = 0; 2944 PP = 0; 2945 2946 WritingAST = false; 2947} 2948 2949template<typename Vector> 2950static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, 2951 ASTWriter::RecordData &Record) { 2952 for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end(); 2953 I != E; ++I) { 2954 Writer.AddDeclRef(*I, Record); 2955 } 2956} 2957 2958void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls, 2959 StringRef isysroot, 2960 const std::string &OutputFile, 2961 Module *WritingModule) { 2962 using namespace llvm; 2963 2964 // Make sure that the AST reader knows to finalize itself. 2965 if (Chain) 2966 Chain->finalizeForWriting(); 2967 2968 ASTContext &Context = SemaRef.Context; 2969 Preprocessor &PP = SemaRef.PP; 2970 2971 // Set up predefined declaration IDs. 2972 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID; 2973 if (Context.ObjCIdDecl) 2974 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID; 2975 if (Context.ObjCSelDecl) 2976 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID; 2977 if (Context.ObjCClassDecl) 2978 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID; 2979 if (Context.Int128Decl) 2980 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID; 2981 if (Context.UInt128Decl) 2982 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID; 2983 if (Context.ObjCInstanceTypeDecl) 2984 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID; 2985 2986 if (!Chain) { 2987 // Make sure that we emit IdentifierInfos (and any attached 2988 // declarations) for builtins. We don't need to do this when we're 2989 // emitting chained PCH files, because all of the builtins will be 2990 // in the original PCH file. 2991 // FIXME: Modules won't like this at all. 2992 IdentifierTable &Table = PP.getIdentifierTable(); 2993 SmallVector<const char *, 32> BuiltinNames; 2994 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames, 2995 Context.getLangOptions().NoBuiltin); 2996 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I) 2997 getIdentifierRef(&Table.get(BuiltinNames[I])); 2998 } 2999 3000 // If there are any out-of-date identifiers, bring them up to date. 3001 if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) { 3002 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 3003 IDEnd = PP.getIdentifierTable().end(); 3004 ID != IDEnd; ++ID) 3005 if (ID->second->isOutOfDate()) 3006 ExtSource->updateOutOfDateIdentifier(*ID->second); 3007 } 3008 3009 // Build a record containing all of the tentative definitions in this file, in 3010 // TentativeDefinitions order. Generally, this record will be empty for 3011 // headers. 3012 RecordData TentativeDefinitions; 3013 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions); 3014 3015 // Build a record containing all of the file scoped decls in this file. 3016 RecordData UnusedFileScopedDecls; 3017 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls, 3018 UnusedFileScopedDecls); 3019 3020 // Build a record containing all of the delegating constructors we still need 3021 // to resolve. 3022 RecordData DelegatingCtorDecls; 3023 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls); 3024 3025 // Write the set of weak, undeclared identifiers. We always write the 3026 // entire table, since later PCH files in a PCH chain are only interested in 3027 // the results at the end of the chain. 3028 RecordData WeakUndeclaredIdentifiers; 3029 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) { 3030 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 3031 I = SemaRef.WeakUndeclaredIdentifiers.begin(), 3032 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) { 3033 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers); 3034 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers); 3035 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers); 3036 WeakUndeclaredIdentifiers.push_back(I->second.getUsed()); 3037 } 3038 } 3039 3040 // Build a record containing all of the locally-scoped external 3041 // declarations in this header file. Generally, this record will be 3042 // empty. 3043 RecordData LocallyScopedExternalDecls; 3044 // FIXME: This is filling in the AST file in densemap order which is 3045 // nondeterminstic! 3046 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 3047 TD = SemaRef.LocallyScopedExternalDecls.begin(), 3048 TDEnd = SemaRef.LocallyScopedExternalDecls.end(); 3049 TD != TDEnd; ++TD) { 3050 if (!TD->second->isFromASTFile()) 3051 AddDeclRef(TD->second, LocallyScopedExternalDecls); 3052 } 3053 3054 // Build a record containing all of the ext_vector declarations. 3055 RecordData ExtVectorDecls; 3056 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls); 3057 3058 // Build a record containing all of the VTable uses information. 3059 RecordData VTableUses; 3060 if (!SemaRef.VTableUses.empty()) { 3061 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 3062 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 3063 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 3064 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 3065 } 3066 } 3067 3068 // Build a record containing all of dynamic classes declarations. 3069 RecordData DynamicClasses; 3070 AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses); 3071 3072 // Build a record containing all of pending implicit instantiations. 3073 RecordData PendingInstantiations; 3074 for (std::deque<Sema::PendingImplicitInstantiation>::iterator 3075 I = SemaRef.PendingInstantiations.begin(), 3076 N = SemaRef.PendingInstantiations.end(); I != N; ++I) { 3077 AddDeclRef(I->first, PendingInstantiations); 3078 AddSourceLocation(I->second, PendingInstantiations); 3079 } 3080 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 3081 "There are local ones at end of translation unit!"); 3082 3083 // Build a record containing some declaration references. 3084 RecordData SemaDeclRefs; 3085 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) { 3086 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 3087 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 3088 } 3089 3090 RecordData CUDASpecialDeclRefs; 3091 if (Context.getcudaConfigureCallDecl()) { 3092 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs); 3093 } 3094 3095 // Build a record containing all of the known namespaces. 3096 RecordData KnownNamespaces; 3097 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator 3098 I = SemaRef.KnownNamespaces.begin(), 3099 IEnd = SemaRef.KnownNamespaces.end(); 3100 I != IEnd; ++I) { 3101 if (!I->second) 3102 AddDeclRef(I->first, KnownNamespaces); 3103 } 3104 3105 // Write the remaining AST contents. 3106 RecordData Record; 3107 Stream.EnterSubblock(AST_BLOCK_ID, 5); 3108 WriteMetadata(Context, isysroot, OutputFile); 3109 WriteLanguageOptions(Context.getLangOptions()); 3110 if (StatCalls && isysroot.empty()) 3111 WriteStatCache(*StatCalls); 3112 3113 // Create a lexical update block containing all of the declarations in the 3114 // translation unit that do not come from other AST files. 3115 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 3116 SmallVector<KindDeclIDPair, 64> NewGlobalDecls; 3117 for (DeclContext::decl_iterator I = TU->noload_decls_begin(), 3118 E = TU->noload_decls_end(); 3119 I != E; ++I) { 3120 if (!(*I)->isFromASTFile()) 3121 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I))); 3122 } 3123 3124 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev(); 3125 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL)); 3126 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 3127 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv); 3128 Record.clear(); 3129 Record.push_back(TU_UPDATE_LEXICAL); 3130 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, 3131 data(NewGlobalDecls)); 3132 3133 // And a visible updates block for the translation unit. 3134 Abv = new llvm::BitCodeAbbrev(); 3135 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE)); 3136 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 3137 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32)); 3138 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 3139 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv); 3140 WriteDeclContextVisibleUpdate(TU); 3141 3142 // If the translation unit has an anonymous namespace, and we don't already 3143 // have an update block for it, write it as an update block. 3144 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) { 3145 ASTWriter::UpdateRecord &Record = DeclUpdates[TU]; 3146 if (Record.empty()) { 3147 Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE); 3148 Record.push_back(reinterpret_cast<uint64_t>(NS)); 3149 } 3150 } 3151 3152 // Resolve any declaration pointers within the declaration updates block. 3153 ResolveDeclUpdatesBlocks(); 3154 3155 // Form the record of special types. 3156 RecordData SpecialTypes; 3157 AddTypeRef(Context.getBuiltinVaListType(), SpecialTypes); 3158 AddTypeRef(Context.ObjCProtoType, SpecialTypes); 3159 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes); 3160 AddTypeRef(Context.getFILEType(), SpecialTypes); 3161 AddTypeRef(Context.getjmp_bufType(), SpecialTypes); 3162 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes); 3163 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes); 3164 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes); 3165 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes); 3166 AddTypeRef(Context.getucontext_tType(), SpecialTypes); 3167 3168 // If we're emitting a module, write out the submodule information. 3169 if (WritingModule) 3170 WriteSubmodules(WritingModule); 3171 3172 // Keep writing types and declarations until all types and 3173 // declarations have been written. 3174 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 3175 WriteDeclsBlockAbbrevs(); 3176 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(), 3177 E = DeclsToRewrite.end(); 3178 I != E; ++I) 3179 DeclTypesToEmit.push(const_cast<Decl*>(*I)); 3180 while (!DeclTypesToEmit.empty()) { 3181 DeclOrType DOT = DeclTypesToEmit.front(); 3182 DeclTypesToEmit.pop(); 3183 if (DOT.isType()) 3184 WriteType(DOT.getType()); 3185 else 3186 WriteDecl(Context, DOT.getDecl()); 3187 } 3188 Stream.ExitBlock(); 3189 3190 WriteFileDeclIDsMap(); 3191 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot); 3192 3193 if (Chain) { 3194 // Write the mapping information describing our module dependencies and how 3195 // each of those modules were mapped into our own offset/ID space, so that 3196 // the reader can build the appropriate mapping to its own offset/ID space. 3197 // The map consists solely of a blob with the following format: 3198 // *(module-name-len:i16 module-name:len*i8 3199 // source-location-offset:i32 3200 // identifier-id:i32 3201 // preprocessed-entity-id:i32 3202 // macro-definition-id:i32 3203 // submodule-id:i32 3204 // selector-id:i32 3205 // declaration-id:i32 3206 // c++-base-specifiers-id:i32 3207 // type-id:i32) 3208 // 3209 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 3210 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP)); 3211 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3212 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev); 3213 llvm::SmallString<2048> Buffer; 3214 { 3215 llvm::raw_svector_ostream Out(Buffer); 3216 for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(), 3217 MEnd = Chain->ModuleMgr.end(); 3218 M != MEnd; ++M) { 3219 StringRef FileName = (*M)->FileName; 3220 io::Emit16(Out, FileName.size()); 3221 Out.write(FileName.data(), FileName.size()); 3222 io::Emit32(Out, (*M)->SLocEntryBaseOffset); 3223 io::Emit32(Out, (*M)->BaseIdentifierID); 3224 io::Emit32(Out, (*M)->BasePreprocessedEntityID); 3225 io::Emit32(Out, (*M)->BaseSubmoduleID); 3226 io::Emit32(Out, (*M)->BaseSelectorID); 3227 io::Emit32(Out, (*M)->BaseDeclID); 3228 io::Emit32(Out, (*M)->BaseTypeIndex); 3229 } 3230 } 3231 Record.clear(); 3232 Record.push_back(MODULE_OFFSET_MAP); 3233 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record, 3234 Buffer.data(), Buffer.size()); 3235 } 3236 WritePreprocessor(PP, WritingModule != 0); 3237 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot); 3238 WriteSelectors(SemaRef); 3239 WriteReferencedSelectorsPool(SemaRef); 3240 WriteIdentifierTable(PP, SemaRef.IdResolver, WritingModule != 0); 3241 WriteFPPragmaOptions(SemaRef.getFPOptions()); 3242 WriteOpenCLExtensions(SemaRef); 3243 3244 WriteTypeDeclOffsets(); 3245 WritePragmaDiagnosticMappings(Context.getDiagnostics()); 3246 3247 WriteCXXBaseSpecifiersOffsets(); 3248 3249 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes); 3250 3251 /// Build a record containing first declarations from a chained PCH and the 3252 /// most recent declarations in this AST that they point to. 3253 RecordData FirstLatestDeclIDs; 3254 for (FirstLatestDeclMap::iterator I = FirstLatestDecls.begin(), 3255 E = FirstLatestDecls.end(); 3256 I != E; ++I) { 3257 AddDeclRef(I->first, FirstLatestDeclIDs); 3258 AddDeclRef(I->second, FirstLatestDeclIDs); 3259 } 3260 3261 if (!FirstLatestDeclIDs.empty()) 3262 Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs); 3263 3264 // Write the record containing external, unnamed definitions. 3265 if (!ExternalDefinitions.empty()) 3266 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions); 3267 3268 // Write the record containing tentative definitions. 3269 if (!TentativeDefinitions.empty()) 3270 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 3271 3272 // Write the record containing unused file scoped decls. 3273 if (!UnusedFileScopedDecls.empty()) 3274 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 3275 3276 // Write the record containing weak undeclared identifiers. 3277 if (!WeakUndeclaredIdentifiers.empty()) 3278 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 3279 WeakUndeclaredIdentifiers); 3280 3281 // Write the record containing locally-scoped external definitions. 3282 if (!LocallyScopedExternalDecls.empty()) 3283 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS, 3284 LocallyScopedExternalDecls); 3285 3286 // Write the record containing ext_vector type names. 3287 if (!ExtVectorDecls.empty()) 3288 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 3289 3290 // Write the record containing VTable uses information. 3291 if (!VTableUses.empty()) 3292 Stream.EmitRecord(VTABLE_USES, VTableUses); 3293 3294 // Write the record containing dynamic classes declarations. 3295 if (!DynamicClasses.empty()) 3296 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses); 3297 3298 // Write the record containing pending implicit instantiations. 3299 if (!PendingInstantiations.empty()) 3300 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 3301 3302 // Write the record containing declaration references of Sema. 3303 if (!SemaDeclRefs.empty()) 3304 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 3305 3306 // Write the record containing CUDA-specific declaration references. 3307 if (!CUDASpecialDeclRefs.empty()) 3308 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs); 3309 3310 // Write the delegating constructors. 3311 if (!DelegatingCtorDecls.empty()) 3312 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls); 3313 3314 // Write the known namespaces. 3315 if (!KnownNamespaces.empty()) 3316 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces); 3317 3318 // Write the visible updates to DeclContexts. 3319 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator 3320 I = UpdatedDeclContexts.begin(), 3321 E = UpdatedDeclContexts.end(); 3322 I != E; ++I) 3323 WriteDeclContextVisibleUpdate(*I); 3324 3325 WriteDeclUpdatesBlocks(); 3326 WriteDeclReplacementsBlock(); 3327 WriteChainedObjCCategories(); 3328 3329 // Some simple statistics 3330 Record.clear(); 3331 Record.push_back(NumStatements); 3332 Record.push_back(NumMacros); 3333 Record.push_back(NumLexicalDeclContexts); 3334 Record.push_back(NumVisibleDeclContexts); 3335 Stream.EmitRecord(STATISTICS, Record); 3336 Stream.ExitBlock(); 3337} 3338 3339/// \brief Go through the declaration update blocks and resolve declaration 3340/// pointers into declaration IDs. 3341void ASTWriter::ResolveDeclUpdatesBlocks() { 3342 for (DeclUpdateMap::iterator 3343 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) { 3344 const Decl *D = I->first; 3345 UpdateRecord &URec = I->second; 3346 3347 if (isRewritten(D)) 3348 continue; // The decl will be written completely 3349 3350 unsigned Idx = 0, N = URec.size(); 3351 while (Idx < N) { 3352 switch ((DeclUpdateKind)URec[Idx++]) { 3353 case UPD_CXX_SET_DEFINITIONDATA: 3354 case UPD_CXX_ADDED_IMPLICIT_MEMBER: 3355 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: 3356 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: 3357 URec[Idx] = GetDeclRef(reinterpret_cast<Decl *>(URec[Idx])); 3358 ++Idx; 3359 break; 3360 3361 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER: 3362 ++Idx; 3363 break; 3364 } 3365 } 3366 } 3367} 3368 3369void ASTWriter::WriteDeclUpdatesBlocks() { 3370 if (DeclUpdates.empty()) 3371 return; 3372 3373 RecordData OffsetsRecord; 3374 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 3375 for (DeclUpdateMap::iterator 3376 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) { 3377 const Decl *D = I->first; 3378 UpdateRecord &URec = I->second; 3379 3380 if (isRewritten(D)) 3381 continue; // The decl will be written completely,no need to store updates. 3382 3383 uint64_t Offset = Stream.GetCurrentBitNo(); 3384 Stream.EmitRecord(DECL_UPDATES, URec); 3385 3386 OffsetsRecord.push_back(GetDeclRef(D)); 3387 OffsetsRecord.push_back(Offset); 3388 } 3389 Stream.ExitBlock(); 3390 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord); 3391} 3392 3393void ASTWriter::WriteDeclReplacementsBlock() { 3394 if (ReplacedDecls.empty()) 3395 return; 3396 3397 RecordData Record; 3398 for (SmallVector<ReplacedDeclInfo, 16>::iterator 3399 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) { 3400 Record.push_back(I->ID); 3401 Record.push_back(I->Offset); 3402 Record.push_back(I->Loc); 3403 } 3404 Stream.EmitRecord(DECL_REPLACEMENTS, Record); 3405} 3406 3407void ASTWriter::WriteChainedObjCCategories() { 3408 if (LocalChainedObjCCategories.empty()) 3409 return; 3410 3411 RecordData Record; 3412 for (SmallVector<ChainedObjCCategoriesData, 16>::iterator 3413 I = LocalChainedObjCCategories.begin(), 3414 E = LocalChainedObjCCategories.end(); I != E; ++I) { 3415 ChainedObjCCategoriesData &Data = *I; 3416 if (isRewritten(Data.Interface)) 3417 continue; 3418 3419 assert(Data.Interface->getCategoryList()); 3420 serialization::DeclID 3421 HeadCatID = getDeclID(Data.Interface->getCategoryList()); 3422 3423 Record.push_back(getDeclID(Data.Interface)); 3424 Record.push_back(HeadCatID); 3425 Record.push_back(getDeclID(Data.TailCategory)); 3426 } 3427 Stream.EmitRecord(OBJC_CHAINED_CATEGORIES, Record); 3428} 3429 3430void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) { 3431 Record.push_back(Loc.getRawEncoding()); 3432} 3433 3434void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) { 3435 AddSourceLocation(Range.getBegin(), Record); 3436 AddSourceLocation(Range.getEnd(), Record); 3437} 3438 3439void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) { 3440 Record.push_back(Value.getBitWidth()); 3441 const uint64_t *Words = Value.getRawData(); 3442 Record.append(Words, Words + Value.getNumWords()); 3443} 3444 3445void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) { 3446 Record.push_back(Value.isUnsigned()); 3447 AddAPInt(Value, Record); 3448} 3449 3450void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) { 3451 AddAPInt(Value.bitcastToAPInt(), Record); 3452} 3453 3454void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) { 3455 Record.push_back(getIdentifierRef(II)); 3456} 3457 3458IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) { 3459 if (II == 0) 3460 return 0; 3461 3462 IdentID &ID = IdentifierIDs[II]; 3463 if (ID == 0) 3464 ID = NextIdentID++; 3465 return ID; 3466} 3467 3468void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) { 3469 Record.push_back(getSelectorRef(SelRef)); 3470} 3471 3472SelectorID ASTWriter::getSelectorRef(Selector Sel) { 3473 if (Sel.getAsOpaquePtr() == 0) { 3474 return 0; 3475 } 3476 3477 SelectorID &SID = SelectorIDs[Sel]; 3478 if (SID == 0 && Chain) { 3479 // This might trigger a ReadSelector callback, which will set the ID for 3480 // this selector. 3481 Chain->LoadSelector(Sel); 3482 } 3483 if (SID == 0) { 3484 SID = NextSelectorID++; 3485 } 3486 return SID; 3487} 3488 3489void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) { 3490 AddDeclRef(Temp->getDestructor(), Record); 3491} 3492 3493void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases, 3494 CXXBaseSpecifier const *BasesEnd, 3495 RecordDataImpl &Record) { 3496 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded"); 3497 CXXBaseSpecifiersToWrite.push_back( 3498 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID, 3499 Bases, BasesEnd)); 3500 Record.push_back(NextCXXBaseSpecifiersID++); 3501} 3502 3503void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind, 3504 const TemplateArgumentLocInfo &Arg, 3505 RecordDataImpl &Record) { 3506 switch (Kind) { 3507 case TemplateArgument::Expression: 3508 AddStmt(Arg.getAsExpr()); 3509 break; 3510 case TemplateArgument::Type: 3511 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record); 3512 break; 3513 case TemplateArgument::Template: 3514 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record); 3515 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 3516 break; 3517 case TemplateArgument::TemplateExpansion: 3518 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record); 3519 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 3520 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record); 3521 break; 3522 case TemplateArgument::Null: 3523 case TemplateArgument::Integral: 3524 case TemplateArgument::Declaration: 3525 case TemplateArgument::Pack: 3526 break; 3527 } 3528} 3529 3530void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg, 3531 RecordDataImpl &Record) { 3532 AddTemplateArgument(Arg.getArgument(), Record); 3533 3534 if (Arg.getArgument().getKind() == TemplateArgument::Expression) { 3535 bool InfoHasSameExpr 3536 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr(); 3537 Record.push_back(InfoHasSameExpr); 3538 if (InfoHasSameExpr) 3539 return; // Avoid storing the same expr twice. 3540 } 3541 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(), 3542 Record); 3543} 3544 3545void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo, 3546 RecordDataImpl &Record) { 3547 if (TInfo == 0) { 3548 AddTypeRef(QualType(), Record); 3549 return; 3550 } 3551 3552 AddTypeLoc(TInfo->getTypeLoc(), Record); 3553} 3554 3555void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) { 3556 AddTypeRef(TL.getType(), Record); 3557 3558 TypeLocWriter TLW(*this, Record); 3559 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 3560 TLW.Visit(TL); 3561} 3562 3563void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) { 3564 Record.push_back(GetOrCreateTypeID(T)); 3565} 3566 3567TypeID ASTWriter::GetOrCreateTypeID( QualType T) { 3568 return MakeTypeID(*Context, T, 3569 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this)); 3570} 3571 3572TypeID ASTWriter::getTypeID(QualType T) const { 3573 return MakeTypeID(*Context, T, 3574 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this)); 3575} 3576 3577TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) { 3578 if (T.isNull()) 3579 return TypeIdx(); 3580 assert(!T.getLocalFastQualifiers()); 3581 3582 TypeIdx &Idx = TypeIdxs[T]; 3583 if (Idx.getIndex() == 0) { 3584 // We haven't seen this type before. Assign it a new ID and put it 3585 // into the queue of types to emit. 3586 Idx = TypeIdx(NextTypeID++); 3587 DeclTypesToEmit.push(T); 3588 } 3589 return Idx; 3590} 3591 3592TypeIdx ASTWriter::getTypeIdx(QualType T) const { 3593 if (T.isNull()) 3594 return TypeIdx(); 3595 assert(!T.getLocalFastQualifiers()); 3596 3597 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 3598 assert(I != TypeIdxs.end() && "Type not emitted!"); 3599 return I->second; 3600} 3601 3602void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) { 3603 Record.push_back(GetDeclRef(D)); 3604} 3605 3606DeclID ASTWriter::GetDeclRef(const Decl *D) { 3607 assert(WritingAST && "Cannot request a declaration ID before AST writing"); 3608 3609 if (D == 0) { 3610 return 0; 3611 } 3612 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer"); 3613 DeclID &ID = DeclIDs[D]; 3614 if (ID == 0) { 3615 // We haven't seen this declaration before. Give it a new ID and 3616 // enqueue it in the list of declarations to emit. 3617 ID = NextDeclID++; 3618 DeclTypesToEmit.push(const_cast<Decl *>(D)); 3619 } 3620 3621 return ID; 3622} 3623 3624DeclID ASTWriter::getDeclID(const Decl *D) { 3625 if (D == 0) 3626 return 0; 3627 3628 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!"); 3629 return DeclIDs[D]; 3630} 3631 3632static inline bool compLocDecl(std::pair<unsigned, serialization::DeclID> L, 3633 std::pair<unsigned, serialization::DeclID> R) { 3634 return L.first < R.first; 3635} 3636 3637void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) { 3638 assert(ID); 3639 assert(D); 3640 3641 SourceLocation Loc = D->getLocation(); 3642 if (Loc.isInvalid()) 3643 return; 3644 3645 // We only keep track of the file-level declarations of each file. 3646 if (!D->getLexicalDeclContext()->isFileContext()) 3647 return; 3648 3649 SourceManager &SM = Context->getSourceManager(); 3650 SourceLocation FileLoc = SM.getFileLoc(Loc); 3651 assert(SM.isLocalSourceLocation(FileLoc)); 3652 FileID FID; 3653 unsigned Offset; 3654 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc); 3655 if (FID.isInvalid()) 3656 return; 3657 const SrcMgr::SLocEntry *Entry = &SM.getSLocEntry(FID); 3658 assert(Entry->isFile()); 3659 3660 DeclIDInFileInfo *&Info = FileDeclIDs[Entry]; 3661 if (!Info) 3662 Info = new DeclIDInFileInfo(); 3663 3664 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID); 3665 LocDeclIDsTy &Decls = Info->DeclIDs; 3666 3667 if (Decls.empty() || Decls.back().first <= Offset) { 3668 Decls.push_back(LocDecl); 3669 return; 3670 } 3671 3672 LocDeclIDsTy::iterator 3673 I = std::upper_bound(Decls.begin(), Decls.end(), LocDecl, compLocDecl); 3674 3675 Decls.insert(I, LocDecl); 3676} 3677 3678void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) { 3679 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc. 3680 Record.push_back(Name.getNameKind()); 3681 switch (Name.getNameKind()) { 3682 case DeclarationName::Identifier: 3683 AddIdentifierRef(Name.getAsIdentifierInfo(), Record); 3684 break; 3685 3686 case DeclarationName::ObjCZeroArgSelector: 3687 case DeclarationName::ObjCOneArgSelector: 3688 case DeclarationName::ObjCMultiArgSelector: 3689 AddSelectorRef(Name.getObjCSelector(), Record); 3690 break; 3691 3692 case DeclarationName::CXXConstructorName: 3693 case DeclarationName::CXXDestructorName: 3694 case DeclarationName::CXXConversionFunctionName: 3695 AddTypeRef(Name.getCXXNameType(), Record); 3696 break; 3697 3698 case DeclarationName::CXXOperatorName: 3699 Record.push_back(Name.getCXXOverloadedOperator()); 3700 break; 3701 3702 case DeclarationName::CXXLiteralOperatorName: 3703 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record); 3704 break; 3705 3706 case DeclarationName::CXXUsingDirective: 3707 // No extra data to emit 3708 break; 3709 } 3710} 3711 3712void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 3713 DeclarationName Name, RecordDataImpl &Record) { 3714 switch (Name.getNameKind()) { 3715 case DeclarationName::CXXConstructorName: 3716 case DeclarationName::CXXDestructorName: 3717 case DeclarationName::CXXConversionFunctionName: 3718 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record); 3719 break; 3720 3721 case DeclarationName::CXXOperatorName: 3722 AddSourceLocation( 3723 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc), 3724 Record); 3725 AddSourceLocation( 3726 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc), 3727 Record); 3728 break; 3729 3730 case DeclarationName::CXXLiteralOperatorName: 3731 AddSourceLocation( 3732 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc), 3733 Record); 3734 break; 3735 3736 case DeclarationName::Identifier: 3737 case DeclarationName::ObjCZeroArgSelector: 3738 case DeclarationName::ObjCOneArgSelector: 3739 case DeclarationName::ObjCMultiArgSelector: 3740 case DeclarationName::CXXUsingDirective: 3741 break; 3742 } 3743} 3744 3745void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 3746 RecordDataImpl &Record) { 3747 AddDeclarationName(NameInfo.getName(), Record); 3748 AddSourceLocation(NameInfo.getLoc(), Record); 3749 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record); 3750} 3751 3752void ASTWriter::AddQualifierInfo(const QualifierInfo &Info, 3753 RecordDataImpl &Record) { 3754 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record); 3755 Record.push_back(Info.NumTemplParamLists); 3756 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i) 3757 AddTemplateParameterList(Info.TemplParamLists[i], Record); 3758} 3759 3760void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS, 3761 RecordDataImpl &Record) { 3762 // Nested name specifiers usually aren't too long. I think that 8 would 3763 // typically accommodate the vast majority. 3764 SmallVector<NestedNameSpecifier *, 8> NestedNames; 3765 3766 // Push each of the NNS's onto a stack for serialization in reverse order. 3767 while (NNS) { 3768 NestedNames.push_back(NNS); 3769 NNS = NNS->getPrefix(); 3770 } 3771 3772 Record.push_back(NestedNames.size()); 3773 while(!NestedNames.empty()) { 3774 NNS = NestedNames.pop_back_val(); 3775 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind(); 3776 Record.push_back(Kind); 3777 switch (Kind) { 3778 case NestedNameSpecifier::Identifier: 3779 AddIdentifierRef(NNS->getAsIdentifier(), Record); 3780 break; 3781 3782 case NestedNameSpecifier::Namespace: 3783 AddDeclRef(NNS->getAsNamespace(), Record); 3784 break; 3785 3786 case NestedNameSpecifier::NamespaceAlias: 3787 AddDeclRef(NNS->getAsNamespaceAlias(), Record); 3788 break; 3789 3790 case NestedNameSpecifier::TypeSpec: 3791 case NestedNameSpecifier::TypeSpecWithTemplate: 3792 AddTypeRef(QualType(NNS->getAsType(), 0), Record); 3793 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 3794 break; 3795 3796 case NestedNameSpecifier::Global: 3797 // Don't need to write an associated value. 3798 break; 3799 } 3800 } 3801} 3802 3803void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 3804 RecordDataImpl &Record) { 3805 // Nested name specifiers usually aren't too long. I think that 8 would 3806 // typically accommodate the vast majority. 3807 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 3808 3809 // Push each of the nested-name-specifiers's onto a stack for 3810 // serialization in reverse order. 3811 while (NNS) { 3812 NestedNames.push_back(NNS); 3813 NNS = NNS.getPrefix(); 3814 } 3815 3816 Record.push_back(NestedNames.size()); 3817 while(!NestedNames.empty()) { 3818 NNS = NestedNames.pop_back_val(); 3819 NestedNameSpecifier::SpecifierKind Kind 3820 = NNS.getNestedNameSpecifier()->getKind(); 3821 Record.push_back(Kind); 3822 switch (Kind) { 3823 case NestedNameSpecifier::Identifier: 3824 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record); 3825 AddSourceRange(NNS.getLocalSourceRange(), Record); 3826 break; 3827 3828 case NestedNameSpecifier::Namespace: 3829 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record); 3830 AddSourceRange(NNS.getLocalSourceRange(), Record); 3831 break; 3832 3833 case NestedNameSpecifier::NamespaceAlias: 3834 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record); 3835 AddSourceRange(NNS.getLocalSourceRange(), Record); 3836 break; 3837 3838 case NestedNameSpecifier::TypeSpec: 3839 case NestedNameSpecifier::TypeSpecWithTemplate: 3840 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 3841 AddTypeLoc(NNS.getTypeLoc(), Record); 3842 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record); 3843 break; 3844 3845 case NestedNameSpecifier::Global: 3846 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record); 3847 break; 3848 } 3849 } 3850} 3851 3852void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) { 3853 TemplateName::NameKind Kind = Name.getKind(); 3854 Record.push_back(Kind); 3855 switch (Kind) { 3856 case TemplateName::Template: 3857 AddDeclRef(Name.getAsTemplateDecl(), Record); 3858 break; 3859 3860 case TemplateName::OverloadedTemplate: { 3861 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate(); 3862 Record.push_back(OvT->size()); 3863 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end(); 3864 I != E; ++I) 3865 AddDeclRef(*I, Record); 3866 break; 3867 } 3868 3869 case TemplateName::QualifiedTemplate: { 3870 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName(); 3871 AddNestedNameSpecifier(QualT->getQualifier(), Record); 3872 Record.push_back(QualT->hasTemplateKeyword()); 3873 AddDeclRef(QualT->getTemplateDecl(), Record); 3874 break; 3875 } 3876 3877 case TemplateName::DependentTemplate: { 3878 DependentTemplateName *DepT = Name.getAsDependentTemplateName(); 3879 AddNestedNameSpecifier(DepT->getQualifier(), Record); 3880 Record.push_back(DepT->isIdentifier()); 3881 if (DepT->isIdentifier()) 3882 AddIdentifierRef(DepT->getIdentifier(), Record); 3883 else 3884 Record.push_back(DepT->getOperator()); 3885 break; 3886 } 3887 3888 case TemplateName::SubstTemplateTemplateParm: { 3889 SubstTemplateTemplateParmStorage *subst 3890 = Name.getAsSubstTemplateTemplateParm(); 3891 AddDeclRef(subst->getParameter(), Record); 3892 AddTemplateName(subst->getReplacement(), Record); 3893 break; 3894 } 3895 3896 case TemplateName::SubstTemplateTemplateParmPack: { 3897 SubstTemplateTemplateParmPackStorage *SubstPack 3898 = Name.getAsSubstTemplateTemplateParmPack(); 3899 AddDeclRef(SubstPack->getParameterPack(), Record); 3900 AddTemplateArgument(SubstPack->getArgumentPack(), Record); 3901 break; 3902 } 3903 } 3904} 3905 3906void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg, 3907 RecordDataImpl &Record) { 3908 Record.push_back(Arg.getKind()); 3909 switch (Arg.getKind()) { 3910 case TemplateArgument::Null: 3911 break; 3912 case TemplateArgument::Type: 3913 AddTypeRef(Arg.getAsType(), Record); 3914 break; 3915 case TemplateArgument::Declaration: 3916 AddDeclRef(Arg.getAsDecl(), Record); 3917 break; 3918 case TemplateArgument::Integral: 3919 AddAPSInt(*Arg.getAsIntegral(), Record); 3920 AddTypeRef(Arg.getIntegralType(), Record); 3921 break; 3922 case TemplateArgument::Template: 3923 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 3924 break; 3925 case TemplateArgument::TemplateExpansion: 3926 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 3927 if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions()) 3928 Record.push_back(*NumExpansions + 1); 3929 else 3930 Record.push_back(0); 3931 break; 3932 case TemplateArgument::Expression: 3933 AddStmt(Arg.getAsExpr()); 3934 break; 3935 case TemplateArgument::Pack: 3936 Record.push_back(Arg.pack_size()); 3937 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end(); 3938 I != E; ++I) 3939 AddTemplateArgument(*I, Record); 3940 break; 3941 } 3942} 3943 3944void 3945ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams, 3946 RecordDataImpl &Record) { 3947 assert(TemplateParams && "No TemplateParams!"); 3948 AddSourceLocation(TemplateParams->getTemplateLoc(), Record); 3949 AddSourceLocation(TemplateParams->getLAngleLoc(), Record); 3950 AddSourceLocation(TemplateParams->getRAngleLoc(), Record); 3951 Record.push_back(TemplateParams->size()); 3952 for (TemplateParameterList::const_iterator 3953 P = TemplateParams->begin(), PEnd = TemplateParams->end(); 3954 P != PEnd; ++P) 3955 AddDeclRef(*P, Record); 3956} 3957 3958/// \brief Emit a template argument list. 3959void 3960ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs, 3961 RecordDataImpl &Record) { 3962 assert(TemplateArgs && "No TemplateArgs!"); 3963 Record.push_back(TemplateArgs->size()); 3964 for (int i=0, e = TemplateArgs->size(); i != e; ++i) 3965 AddTemplateArgument(TemplateArgs->get(i), Record); 3966} 3967 3968 3969void 3970ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) { 3971 Record.push_back(Set.size()); 3972 for (UnresolvedSetImpl::const_iterator 3973 I = Set.begin(), E = Set.end(); I != E; ++I) { 3974 AddDeclRef(I.getDecl(), Record); 3975 Record.push_back(I.getAccess()); 3976 } 3977} 3978 3979void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base, 3980 RecordDataImpl &Record) { 3981 Record.push_back(Base.isVirtual()); 3982 Record.push_back(Base.isBaseOfClass()); 3983 Record.push_back(Base.getAccessSpecifierAsWritten()); 3984 Record.push_back(Base.getInheritConstructors()); 3985 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record); 3986 AddSourceRange(Base.getSourceRange(), Record); 3987 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 3988 : SourceLocation(), 3989 Record); 3990} 3991 3992void ASTWriter::FlushCXXBaseSpecifiers() { 3993 RecordData Record; 3994 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) { 3995 Record.clear(); 3996 3997 // Record the offset of this base-specifier set. 3998 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1; 3999 if (Index == CXXBaseSpecifiersOffsets.size()) 4000 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo()); 4001 else { 4002 if (Index > CXXBaseSpecifiersOffsets.size()) 4003 CXXBaseSpecifiersOffsets.resize(Index + 1); 4004 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo(); 4005 } 4006 4007 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases, 4008 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd; 4009 Record.push_back(BEnd - B); 4010 for (; B != BEnd; ++B) 4011 AddCXXBaseSpecifier(*B, Record); 4012 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record); 4013 4014 // Flush any expressions that were written as part of the base specifiers. 4015 FlushStmts(); 4016 } 4017 4018 CXXBaseSpecifiersToWrite.clear(); 4019} 4020 4021void ASTWriter::AddCXXCtorInitializers( 4022 const CXXCtorInitializer * const *CtorInitializers, 4023 unsigned NumCtorInitializers, 4024 RecordDataImpl &Record) { 4025 Record.push_back(NumCtorInitializers); 4026 for (unsigned i=0; i != NumCtorInitializers; ++i) { 4027 const CXXCtorInitializer *Init = CtorInitializers[i]; 4028 4029 if (Init->isBaseInitializer()) { 4030 Record.push_back(CTOR_INITIALIZER_BASE); 4031 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record); 4032 Record.push_back(Init->isBaseVirtual()); 4033 } else if (Init->isDelegatingInitializer()) { 4034 Record.push_back(CTOR_INITIALIZER_DELEGATING); 4035 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record); 4036 } else if (Init->isMemberInitializer()){ 4037 Record.push_back(CTOR_INITIALIZER_MEMBER); 4038 AddDeclRef(Init->getMember(), Record); 4039 } else { 4040 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER); 4041 AddDeclRef(Init->getIndirectMember(), Record); 4042 } 4043 4044 AddSourceLocation(Init->getMemberLocation(), Record); 4045 AddStmt(Init->getInit()); 4046 AddSourceLocation(Init->getLParenLoc(), Record); 4047 AddSourceLocation(Init->getRParenLoc(), Record); 4048 Record.push_back(Init->isWritten()); 4049 if (Init->isWritten()) { 4050 Record.push_back(Init->getSourceOrder()); 4051 } else { 4052 Record.push_back(Init->getNumArrayIndices()); 4053 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i) 4054 AddDeclRef(Init->getArrayIndex(i), Record); 4055 } 4056 } 4057} 4058 4059void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) { 4060 assert(D->DefinitionData); 4061 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData; 4062 Record.push_back(Data.UserDeclaredConstructor); 4063 Record.push_back(Data.UserDeclaredCopyConstructor); 4064 Record.push_back(Data.UserDeclaredMoveConstructor); 4065 Record.push_back(Data.UserDeclaredCopyAssignment); 4066 Record.push_back(Data.UserDeclaredMoveAssignment); 4067 Record.push_back(Data.UserDeclaredDestructor); 4068 Record.push_back(Data.Aggregate); 4069 Record.push_back(Data.PlainOldData); 4070 Record.push_back(Data.Empty); 4071 Record.push_back(Data.Polymorphic); 4072 Record.push_back(Data.Abstract); 4073 Record.push_back(Data.IsStandardLayout); 4074 Record.push_back(Data.HasNoNonEmptyBases); 4075 Record.push_back(Data.HasPrivateFields); 4076 Record.push_back(Data.HasProtectedFields); 4077 Record.push_back(Data.HasPublicFields); 4078 Record.push_back(Data.HasMutableFields); 4079 Record.push_back(Data.HasTrivialDefaultConstructor); 4080 Record.push_back(Data.HasConstexprNonCopyMoveConstructor); 4081 Record.push_back(Data.HasTrivialCopyConstructor); 4082 Record.push_back(Data.HasTrivialMoveConstructor); 4083 Record.push_back(Data.HasTrivialCopyAssignment); 4084 Record.push_back(Data.HasTrivialMoveAssignment); 4085 Record.push_back(Data.HasTrivialDestructor); 4086 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases); 4087 Record.push_back(Data.ComputedVisibleConversions); 4088 Record.push_back(Data.UserProvidedDefaultConstructor); 4089 Record.push_back(Data.DeclaredDefaultConstructor); 4090 Record.push_back(Data.DeclaredCopyConstructor); 4091 Record.push_back(Data.DeclaredMoveConstructor); 4092 Record.push_back(Data.DeclaredCopyAssignment); 4093 Record.push_back(Data.DeclaredMoveAssignment); 4094 Record.push_back(Data.DeclaredDestructor); 4095 Record.push_back(Data.FailedImplicitMoveConstructor); 4096 Record.push_back(Data.FailedImplicitMoveAssignment); 4097 4098 Record.push_back(Data.NumBases); 4099 if (Data.NumBases > 0) 4100 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases, 4101 Record); 4102 4103 // FIXME: Make VBases lazily computed when needed to avoid storing them. 4104 Record.push_back(Data.NumVBases); 4105 if (Data.NumVBases > 0) 4106 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases, 4107 Record); 4108 4109 AddUnresolvedSet(Data.Conversions, Record); 4110 AddUnresolvedSet(Data.VisibleConversions, Record); 4111 // Data.Definition is the owning decl, no need to write it. 4112 AddDeclRef(Data.FirstFriend, Record); 4113} 4114 4115void ASTWriter::ReaderInitialized(ASTReader *Reader) { 4116 assert(Reader && "Cannot remove chain"); 4117 assert((!Chain || Chain == Reader) && "Cannot replace chain"); 4118 assert(FirstDeclID == NextDeclID && 4119 FirstTypeID == NextTypeID && 4120 FirstIdentID == NextIdentID && 4121 FirstSubmoduleID == NextSubmoduleID && 4122 FirstSelectorID == NextSelectorID && 4123 "Setting chain after writing has started."); 4124 4125 Chain = Reader; 4126 4127 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls(); 4128 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes(); 4129 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers(); 4130 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules(); 4131 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors(); 4132 NextDeclID = FirstDeclID; 4133 NextTypeID = FirstTypeID; 4134 NextIdentID = FirstIdentID; 4135 NextSelectorID = FirstSelectorID; 4136 NextSubmoduleID = FirstSubmoduleID; 4137} 4138 4139void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) { 4140 IdentifierIDs[II] = ID; 4141 if (II->hasMacroDefinition()) 4142 DeserializedMacroNames.push_back(II); 4143} 4144 4145void ASTWriter::TypeRead(TypeIdx Idx, QualType T) { 4146 // Always take the highest-numbered type index. This copes with an interesting 4147 // case for chained AST writing where we schedule writing the type and then, 4148 // later, deserialize the type from another AST. In this case, we want to 4149 // keep the higher-numbered entry so that we can properly write it out to 4150 // the AST file. 4151 TypeIdx &StoredIdx = TypeIdxs[T]; 4152 if (Idx.getIndex() >= StoredIdx.getIndex()) 4153 StoredIdx = Idx; 4154} 4155 4156void ASTWriter::DeclRead(DeclID ID, const Decl *D) { 4157 DeclIDs[D] = ID; 4158} 4159 4160void ASTWriter::SelectorRead(SelectorID ID, Selector S) { 4161 SelectorIDs[S] = ID; 4162} 4163 4164void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID, 4165 MacroDefinition *MD) { 4166 assert(MacroDefinitions.find(MD) == MacroDefinitions.end()); 4167 MacroDefinitions[MD] = ID; 4168} 4169 4170void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) { 4171 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end()); 4172 SubmoduleIDs[Mod] = ID; 4173} 4174 4175void ASTWriter::CompletedTagDefinition(const TagDecl *D) { 4176 assert(D->isCompleteDefinition()); 4177 assert(!WritingAST && "Already writing the AST!"); 4178 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 4179 // We are interested when a PCH decl is modified. 4180 if (RD->isFromASTFile()) { 4181 // A forward reference was mutated into a definition. Rewrite it. 4182 // FIXME: This happens during template instantiation, should we 4183 // have created a new definition decl instead ? 4184 RewriteDecl(RD); 4185 } 4186 4187 for (CXXRecordDecl::redecl_iterator 4188 I = RD->redecls_begin(), E = RD->redecls_end(); I != E; ++I) { 4189 CXXRecordDecl *Redecl = cast<CXXRecordDecl>(*I); 4190 if (Redecl == RD) 4191 continue; 4192 4193 // We are interested when a PCH decl is modified. 4194 if (Redecl->isFromASTFile()) { 4195 UpdateRecord &Record = DeclUpdates[Redecl]; 4196 Record.push_back(UPD_CXX_SET_DEFINITIONDATA); 4197 assert(Redecl->DefinitionData); 4198 assert(Redecl->DefinitionData->Definition == D); 4199 Record.push_back(reinterpret_cast<uint64_t>(D)); // the DefinitionDecl 4200 } 4201 } 4202 } 4203} 4204void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) { 4205 assert(!WritingAST && "Already writing the AST!"); 4206 4207 // TU and namespaces are handled elsewhere. 4208 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC)) 4209 return; 4210 4211 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile())) 4212 return; // Not a source decl added to a DeclContext from PCH. 4213 4214 AddUpdatedDeclContext(DC); 4215} 4216 4217void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { 4218 assert(!WritingAST && "Already writing the AST!"); 4219 assert(D->isImplicit()); 4220 if (!(!D->isFromASTFile() && RD->isFromASTFile())) 4221 return; // Not a source member added to a class from PCH. 4222 if (!isa<CXXMethodDecl>(D)) 4223 return; // We are interested in lazily declared implicit methods. 4224 4225 // A decl coming from PCH was modified. 4226 assert(RD->isCompleteDefinition()); 4227 UpdateRecord &Record = DeclUpdates[RD]; 4228 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER); 4229 Record.push_back(reinterpret_cast<uint64_t>(D)); 4230} 4231 4232void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD, 4233 const ClassTemplateSpecializationDecl *D) { 4234 // The specializations set is kept in the canonical template. 4235 assert(!WritingAST && "Already writing the AST!"); 4236 TD = TD->getCanonicalDecl(); 4237 if (!(!D->isFromASTFile() && TD->isFromASTFile())) 4238 return; // Not a source specialization added to a template from PCH. 4239 4240 UpdateRecord &Record = DeclUpdates[TD]; 4241 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION); 4242 Record.push_back(reinterpret_cast<uint64_t>(D)); 4243} 4244 4245void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, 4246 const FunctionDecl *D) { 4247 // The specializations set is kept in the canonical template. 4248 assert(!WritingAST && "Already writing the AST!"); 4249 TD = TD->getCanonicalDecl(); 4250 if (!(!D->isFromASTFile() && TD->isFromASTFile())) 4251 return; // Not a source specialization added to a template from PCH. 4252 4253 UpdateRecord &Record = DeclUpdates[TD]; 4254 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION); 4255 Record.push_back(reinterpret_cast<uint64_t>(D)); 4256} 4257 4258void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) { 4259 assert(!WritingAST && "Already writing the AST!"); 4260 if (!D->isFromASTFile()) 4261 return; // Declaration not imported from PCH. 4262 4263 // Implicit decl from a PCH was defined. 4264 // FIXME: Should implicit definition be a separate FunctionDecl? 4265 RewriteDecl(D); 4266} 4267 4268void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) { 4269 assert(!WritingAST && "Already writing the AST!"); 4270 if (!D->isFromASTFile()) 4271 return; 4272 4273 // Since the actual instantiation is delayed, this really means that we need 4274 // to update the instantiation location. 4275 UpdateRecord &Record = DeclUpdates[D]; 4276 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER); 4277 AddSourceLocation( 4278 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record); 4279} 4280 4281void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, 4282 const ObjCInterfaceDecl *IFD) { 4283 assert(!WritingAST && "Already writing the AST!"); 4284 if (!IFD->isFromASTFile()) 4285 return; // Declaration not imported from PCH. 4286 if (CatD->getNextClassCategory() && 4287 !CatD->getNextClassCategory()->isFromASTFile()) 4288 return; // We already recorded that the tail of a category chain should be 4289 // attached to an interface. 4290 4291 ChainedObjCCategoriesData Data = { IFD, CatD }; 4292 LocalChainedObjCCategories.push_back(Data); 4293} 4294 4295void ASTWriter::CompletedObjCForwardRef(const ObjCContainerDecl *D) { 4296 assert(!WritingAST && "Already writing the AST!"); 4297 if (!D->isFromASTFile()) 4298 return; // Declaration not imported from PCH. 4299 4300 RewriteDecl(D); 4301} 4302 4303void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop, 4304 const ObjCPropertyDecl *OrigProp, 4305 const ObjCCategoryDecl *ClassExt) { 4306 const ObjCInterfaceDecl *D = ClassExt->getClassInterface(); 4307 if (!D) 4308 return; 4309 4310 assert(!WritingAST && "Already writing the AST!"); 4311 if (!D->isFromASTFile()) 4312 return; // Declaration not imported from PCH. 4313 4314 RewriteDecl(D); 4315} 4316 4317void ASTWriter::UpdatedAttributeList(const Decl *D) { 4318 assert(!WritingAST && "Already writing the AST!"); 4319 if (!D->isFromASTFile()) 4320 return; // Declaration not imported from PCH. 4321 4322 RewriteDecl(D); 4323} 4324