ASTWriter.cpp revision 10f3df54486385e6497c9e5f229ff816e5a6c511
13a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org//===--- ASTWriter.cpp - AST File Writer ----------------------------------===// 2760fd893ba809a7a5daa25c2749ff502f7186e83kbr@chromium.org// 33a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org// The LLVM Compiler Infrastructure 43a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org// 5760fd893ba809a7a5daa25c2749ff502f7186e83kbr@chromium.org// This file is distributed under the University of Illinois Open Source 63a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org// License. See LICENSE.TXT for details. 73a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org// 83a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org//===----------------------------------------------------------------------===// 93a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org// 103a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org// This file defines the ASTWriter class, which writes AST files. 113a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org// 123a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org//===----------------------------------------------------------------------===// 13760fd893ba809a7a5daa25c2749ff502f7186e83kbr@chromium.org 143a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/Serialization/ASTWriter.h" 153a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "ASTCommon.h" 163a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/Sema/Sema.h" 17760fd893ba809a7a5daa25c2749ff502f7186e83kbr@chromium.org#include "clang/Sema/IdentifierResolver.h" 183a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/AST/ASTContext.h" 193a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/AST/Decl.h" 203a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/AST/DeclContextInternals.h" 213a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/AST/DeclTemplate.h" 223a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/AST/DeclFriend.h" 233a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/AST/Expr.h" 243a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/AST/ExprCXX.h" 25760fd893ba809a7a5daa25c2749ff502f7186e83kbr@chromium.org#include "clang/AST/Type.h" 263a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/AST/TypeLocVisitor.h" 273a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/Serialization/ASTReader.h" 28760fd893ba809a7a5daa25c2749ff502f7186e83kbr@chromium.org#include "clang/Lex/MacroInfo.h" 29760fd893ba809a7a5daa25c2749ff502f7186e83kbr@chromium.org#include "clang/Lex/PreprocessingRecord.h" 30760fd893ba809a7a5daa25c2749ff502f7186e83kbr@chromium.org#include "clang/Lex/Preprocessor.h" 31760fd893ba809a7a5daa25c2749ff502f7186e83kbr@chromium.org#include "clang/Lex/HeaderSearch.h" 32760fd893ba809a7a5daa25c2749ff502f7186e83kbr@chromium.org#include "clang/Basic/FileManager.h" 333a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/Basic/FileSystemStatCache.h" 343a0db227ffe90888ad760c61a63226988c974e0apatrick@chromium.org#include "clang/Basic/OnDiskHashTable.h" 35760fd893ba809a7a5daa25c2749ff502f7186e83kbr@chromium.org#include "clang/Basic/SourceManager.h" 36760fd893ba809a7a5daa25c2749ff502f7186e83kbr@chromium.org#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 Stream.EmitRecord(LANGUAGE_OPTIONS, Record); 1067} 1068 1069//===----------------------------------------------------------------------===// 1070// stat cache Serialization 1071//===----------------------------------------------------------------------===// 1072 1073namespace { 1074// Trait used for the on-disk hash table of stat cache results. 1075class ASTStatCacheTrait { 1076public: 1077 typedef const char * key_type; 1078 typedef key_type key_type_ref; 1079 1080 typedef struct stat data_type; 1081 typedef const data_type &data_type_ref; 1082 1083 static unsigned ComputeHash(const char *path) { 1084 return llvm::HashString(path); 1085 } 1086 1087 std::pair<unsigned,unsigned> 1088 EmitKeyDataLength(raw_ostream& Out, const char *path, 1089 data_type_ref Data) { 1090 unsigned StrLen = strlen(path); 1091 clang::io::Emit16(Out, StrLen); 1092 unsigned DataLen = 4 + 4 + 2 + 8 + 8; 1093 clang::io::Emit8(Out, DataLen); 1094 return std::make_pair(StrLen + 1, DataLen); 1095 } 1096 1097 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) { 1098 Out.write(path, KeyLen); 1099 } 1100 1101 void EmitData(raw_ostream &Out, key_type_ref, 1102 data_type_ref Data, unsigned DataLen) { 1103 using namespace clang::io; 1104 uint64_t Start = Out.tell(); (void)Start; 1105 1106 Emit32(Out, (uint32_t) Data.st_ino); 1107 Emit32(Out, (uint32_t) Data.st_dev); 1108 Emit16(Out, (uint16_t) Data.st_mode); 1109 Emit64(Out, (uint64_t) Data.st_mtime); 1110 Emit64(Out, (uint64_t) Data.st_size); 1111 1112 assert(Out.tell() - Start == DataLen && "Wrong data length"); 1113 } 1114}; 1115} // end anonymous namespace 1116 1117/// \brief Write the stat() system call cache to the AST file. 1118void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) { 1119 // Build the on-disk hash table containing information about every 1120 // stat() call. 1121 OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator; 1122 unsigned NumStatEntries = 0; 1123 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(), 1124 StatEnd = StatCalls.end(); 1125 Stat != StatEnd; ++Stat, ++NumStatEntries) { 1126 StringRef Filename = Stat->first(); 1127 Generator.insert(Filename.data(), Stat->second); 1128 } 1129 1130 // Create the on-disk hash table in a buffer. 1131 llvm::SmallString<4096> StatCacheData; 1132 uint32_t BucketOffset; 1133 { 1134 llvm::raw_svector_ostream Out(StatCacheData); 1135 // Make sure that no bucket is at offset 0 1136 clang::io::Emit32(Out, 0); 1137 BucketOffset = Generator.Emit(Out); 1138 } 1139 1140 // Create a blob abbreviation 1141 using namespace llvm; 1142 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1143 Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE)); 1144 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1145 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1146 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1147 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev); 1148 1149 // Write the stat cache 1150 RecordData Record; 1151 Record.push_back(STAT_CACHE); 1152 Record.push_back(BucketOffset); 1153 Record.push_back(NumStatEntries); 1154 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str()); 1155} 1156 1157//===----------------------------------------------------------------------===// 1158// Source Manager Serialization 1159//===----------------------------------------------------------------------===// 1160 1161/// \brief Create an abbreviation for the SLocEntry that refers to a 1162/// file. 1163static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) { 1164 using namespace llvm; 1165 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1166 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY)); 1167 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1168 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1169 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 1170 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1171 // FileEntry fields. 1172 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size 1173 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time 1174 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs 1175 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex 1176 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls 1177 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1178 return Stream.EmitAbbrev(Abbrev); 1179} 1180 1181/// \brief Create an abbreviation for the SLocEntry that refers to a 1182/// buffer. 1183static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) { 1184 using namespace llvm; 1185 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1186 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY)); 1187 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1188 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1189 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 1190 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1191 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob 1192 return Stream.EmitAbbrev(Abbrev); 1193} 1194 1195/// \brief Create an abbreviation for the SLocEntry that refers to a 1196/// buffer's blob. 1197static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) { 1198 using namespace llvm; 1199 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1200 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB)); 1201 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob 1202 return Stream.EmitAbbrev(Abbrev); 1203} 1204 1205/// \brief Create an abbreviation for the SLocEntry that refers to a macro 1206/// expansion. 1207static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) { 1208 using namespace llvm; 1209 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1210 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY)); 1211 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1212 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location 1213 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location 1214 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location 1215 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length 1216 return Stream.EmitAbbrev(Abbrev); 1217} 1218 1219namespace { 1220 // Trait used for the on-disk hash table of header search information. 1221 class HeaderFileInfoTrait { 1222 ASTWriter &Writer; 1223 HeaderSearch &HS; 1224 1225 // Keep track of the framework names we've used during serialization. 1226 SmallVector<char, 128> FrameworkStringData; 1227 llvm::StringMap<unsigned> FrameworkNameOffset; 1228 1229 public: 1230 HeaderFileInfoTrait(ASTWriter &Writer, HeaderSearch &HS) 1231 : Writer(Writer), HS(HS) { } 1232 1233 typedef const char *key_type; 1234 typedef key_type key_type_ref; 1235 1236 typedef HeaderFileInfo data_type; 1237 typedef const data_type &data_type_ref; 1238 1239 static unsigned ComputeHash(const char *path) { 1240 // The hash is based only on the filename portion of the key, so that the 1241 // reader can match based on filenames when symlinking or excess path 1242 // elements ("foo/../", "../") change the form of the name. However, 1243 // complete path is still the key. 1244 return llvm::HashString(llvm::sys::path::filename(path)); 1245 } 1246 1247 std::pair<unsigned,unsigned> 1248 EmitKeyDataLength(raw_ostream& Out, const char *path, 1249 data_type_ref Data) { 1250 unsigned StrLen = strlen(path); 1251 clang::io::Emit16(Out, StrLen); 1252 unsigned DataLen = 1 + 2 + 4 + 4; 1253 clang::io::Emit8(Out, DataLen); 1254 return std::make_pair(StrLen + 1, DataLen); 1255 } 1256 1257 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) { 1258 Out.write(path, KeyLen); 1259 } 1260 1261 void EmitData(raw_ostream &Out, key_type_ref, 1262 data_type_ref Data, unsigned DataLen) { 1263 using namespace clang::io; 1264 uint64_t Start = Out.tell(); (void)Start; 1265 1266 unsigned char Flags = (Data.isImport << 5) 1267 | (Data.isPragmaOnce << 4) 1268 | (Data.DirInfo << 2) 1269 | (Data.Resolved << 1) 1270 | Data.IndexHeaderMapHeader; 1271 Emit8(Out, (uint8_t)Flags); 1272 Emit16(Out, (uint16_t) Data.NumIncludes); 1273 1274 if (!Data.ControllingMacro) 1275 Emit32(Out, (uint32_t)Data.ControllingMacroID); 1276 else 1277 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro)); 1278 1279 unsigned Offset = 0; 1280 if (!Data.Framework.empty()) { 1281 // If this header refers into a framework, save the framework name. 1282 llvm::StringMap<unsigned>::iterator Pos 1283 = FrameworkNameOffset.find(Data.Framework); 1284 if (Pos == FrameworkNameOffset.end()) { 1285 Offset = FrameworkStringData.size() + 1; 1286 FrameworkStringData.append(Data.Framework.begin(), 1287 Data.Framework.end()); 1288 FrameworkStringData.push_back(0); 1289 1290 FrameworkNameOffset[Data.Framework] = Offset; 1291 } else 1292 Offset = Pos->second; 1293 } 1294 Emit32(Out, Offset); 1295 1296 assert(Out.tell() - Start == DataLen && "Wrong data length"); 1297 } 1298 1299 const char *strings_begin() const { return FrameworkStringData.begin(); } 1300 const char *strings_end() const { return FrameworkStringData.end(); } 1301 }; 1302} // end anonymous namespace 1303 1304/// \brief Write the header search block for the list of files that 1305/// 1306/// \param HS The header search structure to save. 1307/// 1308/// \param Chain Whether we're creating a chained AST file. 1309void ASTWriter::WriteHeaderSearch(HeaderSearch &HS, StringRef isysroot) { 1310 SmallVector<const FileEntry *, 16> FilesByUID; 1311 HS.getFileMgr().GetUniqueIDMapping(FilesByUID); 1312 1313 if (FilesByUID.size() > HS.header_file_size()) 1314 FilesByUID.resize(HS.header_file_size()); 1315 1316 HeaderFileInfoTrait GeneratorTrait(*this, HS); 1317 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator; 1318 SmallVector<const char *, 4> SavedStrings; 1319 unsigned NumHeaderSearchEntries = 0; 1320 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) { 1321 const FileEntry *File = FilesByUID[UID]; 1322 if (!File) 1323 continue; 1324 1325 const HeaderFileInfo &HFI = HS.header_file_begin()[UID]; 1326 if (HFI.External && Chain) 1327 continue; 1328 1329 // Turn the file name into an absolute path, if it isn't already. 1330 const char *Filename = File->getName(); 1331 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1332 1333 // If we performed any translation on the file name at all, we need to 1334 // save this string, since the generator will refer to it later. 1335 if (Filename != File->getName()) { 1336 Filename = strdup(Filename); 1337 SavedStrings.push_back(Filename); 1338 } 1339 1340 Generator.insert(Filename, HFI, GeneratorTrait); 1341 ++NumHeaderSearchEntries; 1342 } 1343 1344 // Create the on-disk hash table in a buffer. 1345 llvm::SmallString<4096> TableData; 1346 uint32_t BucketOffset; 1347 { 1348 llvm::raw_svector_ostream Out(TableData); 1349 // Make sure that no bucket is at offset 0 1350 clang::io::Emit32(Out, 0); 1351 BucketOffset = Generator.Emit(Out, GeneratorTrait); 1352 } 1353 1354 // Create a blob abbreviation 1355 using namespace llvm; 1356 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1357 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE)); 1358 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1359 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1360 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1361 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1362 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev); 1363 1364 // Write the header search table 1365 RecordData Record; 1366 Record.push_back(HEADER_SEARCH_TABLE); 1367 Record.push_back(BucketOffset); 1368 Record.push_back(NumHeaderSearchEntries); 1369 Record.push_back(TableData.size()); 1370 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end()); 1371 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str()); 1372 1373 // Free all of the strings we had to duplicate. 1374 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I) 1375 free((void*)SavedStrings[I]); 1376} 1377 1378/// \brief Writes the block containing the serialized form of the 1379/// source manager. 1380/// 1381/// TODO: We should probably use an on-disk hash table (stored in a 1382/// blob), indexed based on the file name, so that we only create 1383/// entries for files that we actually need. In the common case (no 1384/// errors), we probably won't have to create file entries for any of 1385/// the files in the AST. 1386void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, 1387 const Preprocessor &PP, 1388 StringRef isysroot) { 1389 RecordData Record; 1390 1391 // Enter the source manager block. 1392 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3); 1393 1394 // Abbreviations for the various kinds of source-location entries. 1395 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream); 1396 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream); 1397 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream); 1398 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream); 1399 1400 // Write out the source location entry table. We skip the first 1401 // entry, which is always the same dummy entry. 1402 std::vector<uint32_t> SLocEntryOffsets; 1403 // Write out the offsets of only source location file entries. 1404 // We will go through them in ASTReader::validateFileEntries(). 1405 std::vector<uint32_t> SLocFileEntryOffsets; 1406 RecordData PreloadSLocs; 1407 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1); 1408 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); 1409 I != N; ++I) { 1410 // Get this source location entry. 1411 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I); 1412 1413 // Record the offset of this source-location entry. 1414 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo()); 1415 1416 // Figure out which record code to use. 1417 unsigned Code; 1418 if (SLoc->isFile()) { 1419 if (SLoc->getFile().getContentCache()->OrigEntry) { 1420 Code = SM_SLOC_FILE_ENTRY; 1421 SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo()); 1422 } else 1423 Code = SM_SLOC_BUFFER_ENTRY; 1424 } else 1425 Code = SM_SLOC_EXPANSION_ENTRY; 1426 Record.clear(); 1427 Record.push_back(Code); 1428 1429 // Starting offset of this entry within this module, so skip the dummy. 1430 Record.push_back(SLoc->getOffset() - 2); 1431 if (SLoc->isFile()) { 1432 const SrcMgr::FileInfo &File = SLoc->getFile(); 1433 Record.push_back(File.getIncludeLoc().getRawEncoding()); 1434 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding 1435 Record.push_back(File.hasLineDirectives()); 1436 1437 const SrcMgr::ContentCache *Content = File.getContentCache(); 1438 if (Content->OrigEntry) { 1439 assert(Content->OrigEntry == Content->ContentsEntry && 1440 "Writing to AST an overriden file is not supported"); 1441 1442 // The source location entry is a file. The blob associated 1443 // with this entry is the file name. 1444 1445 // Emit size/modification time for this file. 1446 Record.push_back(Content->OrigEntry->getSize()); 1447 Record.push_back(Content->OrigEntry->getModificationTime()); 1448 1449 Record.push_back(File.NumCreatedFIDs); 1450 1451 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(SLoc); 1452 if (FDI != FileDeclIDs.end()) { 1453 Record.push_back(FDI->second->FirstDeclIndex); 1454 Record.push_back(FDI->second->DeclIDs.size()); 1455 } else { 1456 Record.push_back(0); 1457 Record.push_back(0); 1458 } 1459 1460 // Turn the file name into an absolute path, if it isn't already. 1461 const char *Filename = Content->OrigEntry->getName(); 1462 llvm::SmallString<128> FilePath(Filename); 1463 1464 // Ask the file manager to fixup the relative path for us. This will 1465 // honor the working directory. 1466 SourceMgr.getFileManager().FixupRelativePath(FilePath); 1467 1468 // FIXME: This call to make_absolute shouldn't be necessary, the 1469 // call to FixupRelativePath should always return an absolute path. 1470 llvm::sys::fs::make_absolute(FilePath); 1471 Filename = FilePath.c_str(); 1472 1473 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1474 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename); 1475 } else { 1476 // The source location entry is a buffer. The blob associated 1477 // with this entry contains the contents of the buffer. 1478 1479 // We add one to the size so that we capture the trailing NULL 1480 // that is required by llvm::MemoryBuffer::getMemBuffer (on 1481 // the reader side). 1482 const llvm::MemoryBuffer *Buffer 1483 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager()); 1484 const char *Name = Buffer->getBufferIdentifier(); 1485 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, 1486 StringRef(Name, strlen(Name) + 1)); 1487 Record.clear(); 1488 Record.push_back(SM_SLOC_BUFFER_BLOB); 1489 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, 1490 StringRef(Buffer->getBufferStart(), 1491 Buffer->getBufferSize() + 1)); 1492 1493 if (strcmp(Name, "<built-in>") == 0) { 1494 PreloadSLocs.push_back(SLocEntryOffsets.size()); 1495 } 1496 } 1497 } else { 1498 // The source location entry is a macro expansion. 1499 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion(); 1500 Record.push_back(Expansion.getSpellingLoc().getRawEncoding()); 1501 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding()); 1502 Record.push_back(Expansion.isMacroArgExpansion() ? 0 1503 : Expansion.getExpansionLocEnd().getRawEncoding()); 1504 1505 // Compute the token length for this macro expansion. 1506 unsigned NextOffset = SourceMgr.getNextLocalOffset(); 1507 if (I + 1 != N) 1508 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset(); 1509 Record.push_back(NextOffset - SLoc->getOffset() - 1); 1510 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record); 1511 } 1512 } 1513 1514 Stream.ExitBlock(); 1515 1516 if (SLocEntryOffsets.empty()) 1517 return; 1518 1519 // Write the source-location offsets table into the AST block. This 1520 // table is used for lazily loading source-location information. 1521 using namespace llvm; 1522 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1523 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS)); 1524 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 1525 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size 1526 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 1527 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); 1528 1529 Record.clear(); 1530 Record.push_back(SOURCE_LOCATION_OFFSETS); 1531 Record.push_back(SLocEntryOffsets.size()); 1532 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy 1533 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets)); 1534 1535 Abbrev = new BitCodeAbbrev(); 1536 Abbrev->Add(BitCodeAbbrevOp(FILE_SOURCE_LOCATION_OFFSETS)); 1537 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 1538 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 1539 unsigned SLocFileOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); 1540 1541 Record.clear(); 1542 Record.push_back(FILE_SOURCE_LOCATION_OFFSETS); 1543 Record.push_back(SLocFileEntryOffsets.size()); 1544 Stream.EmitRecordWithBlob(SLocFileOffsetsAbbrev, Record, 1545 data(SLocFileEntryOffsets)); 1546 1547 // Write the source location entry preloads array, telling the AST 1548 // reader which source locations entries it should load eagerly. 1549 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs); 1550 1551 // Write the line table. It depends on remapping working, so it must come 1552 // after the source location offsets. 1553 if (SourceMgr.hasLineTable()) { 1554 LineTableInfo &LineTable = SourceMgr.getLineTable(); 1555 1556 Record.clear(); 1557 // Emit the file names 1558 Record.push_back(LineTable.getNumFilenames()); 1559 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) { 1560 // Emit the file name 1561 const char *Filename = LineTable.getFilename(I); 1562 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1563 unsigned FilenameLen = Filename? strlen(Filename) : 0; 1564 Record.push_back(FilenameLen); 1565 if (FilenameLen) 1566 Record.insert(Record.end(), Filename, Filename + FilenameLen); 1567 } 1568 1569 // Emit the line entries 1570 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end(); 1571 L != LEnd; ++L) { 1572 // Only emit entries for local files. 1573 if (L->first < 0) 1574 continue; 1575 1576 // Emit the file ID 1577 Record.push_back(L->first); 1578 1579 // Emit the line entries 1580 Record.push_back(L->second.size()); 1581 for (std::vector<LineEntry>::iterator LE = L->second.begin(), 1582 LEEnd = L->second.end(); 1583 LE != LEEnd; ++LE) { 1584 Record.push_back(LE->FileOffset); 1585 Record.push_back(LE->LineNo); 1586 Record.push_back(LE->FilenameID); 1587 Record.push_back((unsigned)LE->FileKind); 1588 Record.push_back(LE->IncludeOffset); 1589 } 1590 } 1591 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record); 1592 } 1593} 1594 1595//===----------------------------------------------------------------------===// 1596// Preprocessor Serialization 1597//===----------------------------------------------------------------------===// 1598 1599static int compareMacroDefinitions(const void *XPtr, const void *YPtr) { 1600 const std::pair<const IdentifierInfo *, MacroInfo *> &X = 1601 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr; 1602 const std::pair<const IdentifierInfo *, MacroInfo *> &Y = 1603 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr; 1604 return X.first->getName().compare(Y.first->getName()); 1605} 1606 1607/// \brief Writes the block containing the serialized form of the 1608/// preprocessor. 1609/// 1610void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) { 1611 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 1612 if (PPRec) 1613 WritePreprocessorDetail(*PPRec); 1614 1615 RecordData Record; 1616 1617 // If the preprocessor __COUNTER__ value has been bumped, remember it. 1618 if (PP.getCounterValue() != 0) { 1619 Record.push_back(PP.getCounterValue()); 1620 Stream.EmitRecord(PP_COUNTER_VALUE, Record); 1621 Record.clear(); 1622 } 1623 1624 // Enter the preprocessor block. 1625 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3); 1626 1627 // If the AST file contains __DATE__ or __TIME__ emit a warning about this. 1628 // FIXME: use diagnostics subsystem for localization etc. 1629 if (PP.SawDateOrTime()) 1630 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n"); 1631 1632 1633 // Loop over all the macro definitions that are live at the end of the file, 1634 // emitting each to the PP section. 1635 1636 // Construct the list of macro definitions that need to be serialized. 1637 SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2> 1638 MacrosToEmit; 1639 llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen; 1640 for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0), 1641 E = PP.macro_end(Chain == 0); 1642 I != E; ++I) { 1643 if (!IsModule || I->second->isPublic()) { 1644 MacroDefinitionsSeen.insert(I->first); 1645 MacrosToEmit.push_back(std::make_pair(I->first, I->second)); 1646 } 1647 } 1648 1649 // Sort the set of macro definitions that need to be serialized by the 1650 // name of the macro, to provide a stable ordering. 1651 llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(), 1652 &compareMacroDefinitions); 1653 1654 // Resolve any identifiers that defined macros at the time they were 1655 // deserialized, adding them to the list of macros to emit (if appropriate). 1656 for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) { 1657 IdentifierInfo *Name 1658 = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]); 1659 if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name)) 1660 MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name))); 1661 } 1662 1663 for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) { 1664 const IdentifierInfo *Name = MacrosToEmit[I].first; 1665 MacroInfo *MI = MacrosToEmit[I].second; 1666 if (!MI) 1667 continue; 1668 1669 // Don't emit builtin macros like __LINE__ to the AST file unless they have 1670 // been redefined by the header (in which case they are not isBuiltinMacro). 1671 // Also skip macros from a AST file if we're chaining. 1672 1673 // FIXME: There is a (probably minor) optimization we could do here, if 1674 // the macro comes from the original PCH but the identifier comes from a 1675 // chained PCH, by storing the offset into the original PCH rather than 1676 // writing the macro definition a second time. 1677 if (MI->isBuiltinMacro() || 1678 (Chain && 1679 Name->isFromAST() && !Name->hasChangedSinceDeserialization() && 1680 MI->isFromAST() && !MI->hasChangedAfterLoad())) 1681 continue; 1682 1683 AddIdentifierRef(Name, Record); 1684 MacroOffsets[Name] = Stream.GetCurrentBitNo(); 1685 Record.push_back(MI->getDefinitionLoc().getRawEncoding()); 1686 Record.push_back(MI->isUsed()); 1687 Record.push_back(MI->isPublic()); 1688 AddSourceLocation(MI->getVisibilityLocation(), Record); 1689 unsigned Code; 1690 if (MI->isObjectLike()) { 1691 Code = PP_MACRO_OBJECT_LIKE; 1692 } else { 1693 Code = PP_MACRO_FUNCTION_LIKE; 1694 1695 Record.push_back(MI->isC99Varargs()); 1696 Record.push_back(MI->isGNUVarargs()); 1697 Record.push_back(MI->getNumArgs()); 1698 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); 1699 I != E; ++I) 1700 AddIdentifierRef(*I, Record); 1701 } 1702 1703 // If we have a detailed preprocessing record, record the macro definition 1704 // ID that corresponds to this macro. 1705 if (PPRec) 1706 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]); 1707 1708 Stream.EmitRecord(Code, Record); 1709 Record.clear(); 1710 1711 // Emit the tokens array. 1712 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) { 1713 // Note that we know that the preprocessor does not have any annotation 1714 // tokens in it because they are created by the parser, and thus can't be 1715 // in a macro definition. 1716 const Token &Tok = MI->getReplacementToken(TokNo); 1717 1718 Record.push_back(Tok.getLocation().getRawEncoding()); 1719 Record.push_back(Tok.getLength()); 1720 1721 // FIXME: When reading literal tokens, reconstruct the literal pointer if 1722 // it is needed. 1723 AddIdentifierRef(Tok.getIdentifierInfo(), Record); 1724 // FIXME: Should translate token kind to a stable encoding. 1725 Record.push_back(Tok.getKind()); 1726 // FIXME: Should translate token flags to a stable encoding. 1727 Record.push_back(Tok.getFlags()); 1728 1729 Stream.EmitRecord(PP_TOKEN, Record); 1730 Record.clear(); 1731 } 1732 ++NumMacros; 1733 } 1734 Stream.ExitBlock(); 1735} 1736 1737void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) { 1738 if (PPRec.local_begin() == PPRec.local_end()) 1739 return; 1740 1741 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets; 1742 1743 // Enter the preprocessor block. 1744 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3); 1745 1746 // If the preprocessor has a preprocessing record, emit it. 1747 unsigned NumPreprocessingRecords = 0; 1748 using namespace llvm; 1749 1750 // Set up the abbreviation for 1751 unsigned InclusionAbbrev = 0; 1752 { 1753 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1754 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE)); 1755 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length 1756 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes 1757 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind 1758 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1759 InclusionAbbrev = Stream.EmitAbbrev(Abbrev); 1760 } 1761 1762 unsigned FirstPreprocessorEntityID 1763 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0) 1764 + NUM_PREDEF_PP_ENTITY_IDS; 1765 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID; 1766 RecordData Record; 1767 for (PreprocessingRecord::iterator E = PPRec.local_begin(), 1768 EEnd = PPRec.local_end(); 1769 E != EEnd; 1770 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) { 1771 Record.clear(); 1772 1773 PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(), 1774 Stream.GetCurrentBitNo())); 1775 1776 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) { 1777 // Record this macro definition's ID. 1778 MacroDefinitions[MD] = NextPreprocessorEntityID; 1779 1780 AddIdentifierRef(MD->getName(), Record); 1781 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record); 1782 continue; 1783 } 1784 1785 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) { 1786 Record.push_back(ME->isBuiltinMacro()); 1787 if (ME->isBuiltinMacro()) 1788 AddIdentifierRef(ME->getName(), Record); 1789 else 1790 Record.push_back(MacroDefinitions[ME->getDefinition()]); 1791 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record); 1792 continue; 1793 } 1794 1795 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) { 1796 Record.push_back(PPD_INCLUSION_DIRECTIVE); 1797 Record.push_back(ID->getFileName().size()); 1798 Record.push_back(ID->wasInQuotes()); 1799 Record.push_back(static_cast<unsigned>(ID->getKind())); 1800 llvm::SmallString<64> Buffer; 1801 Buffer += ID->getFileName(); 1802 Buffer += ID->getFile()->getName(); 1803 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer); 1804 continue; 1805 } 1806 1807 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter"); 1808 } 1809 Stream.ExitBlock(); 1810 1811 // Write the offsets table for the preprocessing record. 1812 if (NumPreprocessingRecords > 0) { 1813 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords); 1814 1815 // Write the offsets table for identifier IDs. 1816 using namespace llvm; 1817 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1818 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS)); 1819 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity 1820 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1821 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1822 1823 Record.clear(); 1824 Record.push_back(PPD_ENTITIES_OFFSETS); 1825 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS); 1826 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record, 1827 data(PreprocessedEntityOffsets)); 1828 } 1829} 1830 1831void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag) { 1832 RecordData Record; 1833 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator 1834 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end(); 1835 I != E; ++I) { 1836 const DiagnosticsEngine::DiagStatePoint &point = *I; 1837 if (point.Loc.isInvalid()) 1838 continue; 1839 1840 Record.push_back(point.Loc.getRawEncoding()); 1841 for (DiagnosticsEngine::DiagState::const_iterator 1842 I = point.State->begin(), E = point.State->end(); I != E; ++I) { 1843 if (I->second.isPragma()) { 1844 Record.push_back(I->first); 1845 Record.push_back(I->second.getMapping()); 1846 } 1847 } 1848 Record.push_back(-1); // mark the end of the diag/map pairs for this 1849 // location. 1850 } 1851 1852 if (!Record.empty()) 1853 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record); 1854} 1855 1856void ASTWriter::WriteCXXBaseSpecifiersOffsets() { 1857 if (CXXBaseSpecifiersOffsets.empty()) 1858 return; 1859 1860 RecordData Record; 1861 1862 // Create a blob abbreviation for the C++ base specifiers offsets. 1863 using namespace llvm; 1864 1865 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1866 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS)); 1867 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 1868 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1869 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1870 1871 // Write the base specifier offsets table. 1872 Record.clear(); 1873 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS); 1874 Record.push_back(CXXBaseSpecifiersOffsets.size()); 1875 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record, 1876 data(CXXBaseSpecifiersOffsets)); 1877} 1878 1879//===----------------------------------------------------------------------===// 1880// Type Serialization 1881//===----------------------------------------------------------------------===// 1882 1883/// \brief Write the representation of a type to the AST stream. 1884void ASTWriter::WriteType(QualType T) { 1885 TypeIdx &Idx = TypeIdxs[T]; 1886 if (Idx.getIndex() == 0) // we haven't seen this type before. 1887 Idx = TypeIdx(NextTypeID++); 1888 1889 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST"); 1890 1891 // Record the offset for this type. 1892 unsigned Index = Idx.getIndex() - FirstTypeID; 1893 if (TypeOffsets.size() == Index) 1894 TypeOffsets.push_back(Stream.GetCurrentBitNo()); 1895 else if (TypeOffsets.size() < Index) { 1896 TypeOffsets.resize(Index + 1); 1897 TypeOffsets[Index] = Stream.GetCurrentBitNo(); 1898 } 1899 1900 RecordData Record; 1901 1902 // Emit the type's representation. 1903 ASTTypeWriter W(*this, Record); 1904 1905 if (T.hasLocalNonFastQualifiers()) { 1906 Qualifiers Qs = T.getLocalQualifiers(); 1907 AddTypeRef(T.getLocalUnqualifiedType(), Record); 1908 Record.push_back(Qs.getAsOpaqueValue()); 1909 W.Code = TYPE_EXT_QUAL; 1910 } else { 1911 switch (T->getTypeClass()) { 1912 // For all of the concrete, non-dependent types, call the 1913 // appropriate visitor function. 1914#define TYPE(Class, Base) \ 1915 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break; 1916#define ABSTRACT_TYPE(Class, Base) 1917#include "clang/AST/TypeNodes.def" 1918 } 1919 } 1920 1921 // Emit the serialized record. 1922 Stream.EmitRecord(W.Code, Record); 1923 1924 // Flush any expressions that were written as part of this type. 1925 FlushStmts(); 1926} 1927 1928//===----------------------------------------------------------------------===// 1929// Declaration Serialization 1930//===----------------------------------------------------------------------===// 1931 1932/// \brief Write the block containing all of the declaration IDs 1933/// lexically declared within the given DeclContext. 1934/// 1935/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the 1936/// bistream, or 0 if no block was written. 1937uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context, 1938 DeclContext *DC) { 1939 if (DC->decls_empty()) 1940 return 0; 1941 1942 uint64_t Offset = Stream.GetCurrentBitNo(); 1943 RecordData Record; 1944 Record.push_back(DECL_CONTEXT_LEXICAL); 1945 SmallVector<KindDeclIDPair, 64> Decls; 1946 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end(); 1947 D != DEnd; ++D) 1948 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D))); 1949 1950 ++NumLexicalDeclContexts; 1951 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls)); 1952 return Offset; 1953} 1954 1955void ASTWriter::WriteTypeDeclOffsets() { 1956 using namespace llvm; 1957 RecordData Record; 1958 1959 // Write the type offsets array 1960 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1961 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET)); 1962 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types 1963 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index 1964 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block 1965 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1966 Record.clear(); 1967 Record.push_back(TYPE_OFFSET); 1968 Record.push_back(TypeOffsets.size()); 1969 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS); 1970 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets)); 1971 1972 // Write the declaration offsets array 1973 Abbrev = new BitCodeAbbrev(); 1974 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET)); 1975 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations 1976 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID 1977 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block 1978 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1979 Record.clear(); 1980 Record.push_back(DECL_OFFSET); 1981 Record.push_back(DeclOffsets.size()); 1982 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS); 1983 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets)); 1984} 1985 1986void ASTWriter::WriteFileDeclIDsMap() { 1987 using namespace llvm; 1988 RecordData Record; 1989 1990 // Join the vectors of DeclIDs from all files. 1991 SmallVector<DeclID, 256> FileSortedIDs; 1992 for (FileDeclIDsTy::iterator 1993 FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) { 1994 DeclIDInFileInfo &Info = *FI->second; 1995 Info.FirstDeclIndex = FileSortedIDs.size(); 1996 for (LocDeclIDsTy::iterator 1997 DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI) 1998 FileSortedIDs.push_back(DI->second); 1999 } 2000 2001 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2002 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS)); 2003 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2004 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev); 2005 Record.push_back(FILE_SORTED_DECLS); 2006 Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs)); 2007} 2008 2009//===----------------------------------------------------------------------===// 2010// Global Method Pool and Selector Serialization 2011//===----------------------------------------------------------------------===// 2012 2013namespace { 2014// Trait used for the on-disk hash table used in the method pool. 2015class ASTMethodPoolTrait { 2016 ASTWriter &Writer; 2017 2018public: 2019 typedef Selector key_type; 2020 typedef key_type key_type_ref; 2021 2022 struct data_type { 2023 SelectorID ID; 2024 ObjCMethodList Instance, Factory; 2025 }; 2026 typedef const data_type& data_type_ref; 2027 2028 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { } 2029 2030 static unsigned ComputeHash(Selector Sel) { 2031 return serialization::ComputeHash(Sel); 2032 } 2033 2034 std::pair<unsigned,unsigned> 2035 EmitKeyDataLength(raw_ostream& Out, Selector Sel, 2036 data_type_ref Methods) { 2037 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4); 2038 clang::io::Emit16(Out, KeyLen); 2039 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts 2040 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2041 Method = Method->Next) 2042 if (Method->Method) 2043 DataLen += 4; 2044 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2045 Method = Method->Next) 2046 if (Method->Method) 2047 DataLen += 4; 2048 clang::io::Emit16(Out, DataLen); 2049 return std::make_pair(KeyLen, DataLen); 2050 } 2051 2052 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) { 2053 uint64_t Start = Out.tell(); 2054 assert((Start >> 32) == 0 && "Selector key offset too large"); 2055 Writer.SetSelectorOffset(Sel, Start); 2056 unsigned N = Sel.getNumArgs(); 2057 clang::io::Emit16(Out, N); 2058 if (N == 0) 2059 N = 1; 2060 for (unsigned I = 0; I != N; ++I) 2061 clang::io::Emit32(Out, 2062 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I))); 2063 } 2064 2065 void EmitData(raw_ostream& Out, key_type_ref, 2066 data_type_ref Methods, unsigned DataLen) { 2067 uint64_t Start = Out.tell(); (void)Start; 2068 clang::io::Emit32(Out, Methods.ID); 2069 unsigned NumInstanceMethods = 0; 2070 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2071 Method = Method->Next) 2072 if (Method->Method) 2073 ++NumInstanceMethods; 2074 2075 unsigned NumFactoryMethods = 0; 2076 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2077 Method = Method->Next) 2078 if (Method->Method) 2079 ++NumFactoryMethods; 2080 2081 clang::io::Emit16(Out, NumInstanceMethods); 2082 clang::io::Emit16(Out, NumFactoryMethods); 2083 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2084 Method = Method->Next) 2085 if (Method->Method) 2086 clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); 2087 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2088 Method = Method->Next) 2089 if (Method->Method) 2090 clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); 2091 2092 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 2093 } 2094}; 2095} // end anonymous namespace 2096 2097/// \brief Write ObjC data: selectors and the method pool. 2098/// 2099/// The method pool contains both instance and factory methods, stored 2100/// in an on-disk hash table indexed by the selector. The hash table also 2101/// contains an empty entry for every other selector known to Sema. 2102void ASTWriter::WriteSelectors(Sema &SemaRef) { 2103 using namespace llvm; 2104 2105 // Do we have to do anything at all? 2106 if (SemaRef.MethodPool.empty() && SelectorIDs.empty()) 2107 return; 2108 unsigned NumTableEntries = 0; 2109 // Create and write out the blob that contains selectors and the method pool. 2110 { 2111 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator; 2112 ASTMethodPoolTrait Trait(*this); 2113 2114 // Create the on-disk hash table representation. We walk through every 2115 // selector we've seen and look it up in the method pool. 2116 SelectorOffsets.resize(NextSelectorID - FirstSelectorID); 2117 for (llvm::DenseMap<Selector, SelectorID>::iterator 2118 I = SelectorIDs.begin(), E = SelectorIDs.end(); 2119 I != E; ++I) { 2120 Selector S = I->first; 2121 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S); 2122 ASTMethodPoolTrait::data_type Data = { 2123 I->second, 2124 ObjCMethodList(), 2125 ObjCMethodList() 2126 }; 2127 if (F != SemaRef.MethodPool.end()) { 2128 Data.Instance = F->second.first; 2129 Data.Factory = F->second.second; 2130 } 2131 // Only write this selector if it's not in an existing AST or something 2132 // changed. 2133 if (Chain && I->second < FirstSelectorID) { 2134 // Selector already exists. Did it change? 2135 bool changed = false; 2136 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method; 2137 M = M->Next) { 2138 if (!M->Method->isFromASTFile()) 2139 changed = true; 2140 } 2141 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method; 2142 M = M->Next) { 2143 if (!M->Method->isFromASTFile()) 2144 changed = true; 2145 } 2146 if (!changed) 2147 continue; 2148 } else if (Data.Instance.Method || Data.Factory.Method) { 2149 // A new method pool entry. 2150 ++NumTableEntries; 2151 } 2152 Generator.insert(S, Data, Trait); 2153 } 2154 2155 // Create the on-disk hash table in a buffer. 2156 llvm::SmallString<4096> MethodPool; 2157 uint32_t BucketOffset; 2158 { 2159 ASTMethodPoolTrait Trait(*this); 2160 llvm::raw_svector_ostream Out(MethodPool); 2161 // Make sure that no bucket is at offset 0 2162 clang::io::Emit32(Out, 0); 2163 BucketOffset = Generator.Emit(Out, Trait); 2164 } 2165 2166 // Create a blob abbreviation 2167 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2168 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL)); 2169 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2170 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2171 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2172 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev); 2173 2174 // Write the method pool 2175 RecordData Record; 2176 Record.push_back(METHOD_POOL); 2177 Record.push_back(BucketOffset); 2178 Record.push_back(NumTableEntries); 2179 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str()); 2180 2181 // Create a blob abbreviation for the selector table offsets. 2182 Abbrev = new BitCodeAbbrev(); 2183 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS)); 2184 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 2185 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 2186 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2187 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2188 2189 // Write the selector offsets table. 2190 Record.clear(); 2191 Record.push_back(SELECTOR_OFFSETS); 2192 Record.push_back(SelectorOffsets.size()); 2193 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS); 2194 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record, 2195 data(SelectorOffsets)); 2196 } 2197} 2198 2199/// \brief Write the selectors referenced in @selector expression into AST file. 2200void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) { 2201 using namespace llvm; 2202 if (SemaRef.ReferencedSelectors.empty()) 2203 return; 2204 2205 RecordData Record; 2206 2207 // Note: this writes out all references even for a dependent AST. But it is 2208 // very tricky to fix, and given that @selector shouldn't really appear in 2209 // headers, probably not worth it. It's not a correctness issue. 2210 for (DenseMap<Selector, SourceLocation>::iterator S = 2211 SemaRef.ReferencedSelectors.begin(), 2212 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) { 2213 Selector Sel = (*S).first; 2214 SourceLocation Loc = (*S).second; 2215 AddSelectorRef(Sel, Record); 2216 AddSourceLocation(Loc, Record); 2217 } 2218 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record); 2219} 2220 2221//===----------------------------------------------------------------------===// 2222// Identifier Table Serialization 2223//===----------------------------------------------------------------------===// 2224 2225namespace { 2226class ASTIdentifierTableTrait { 2227 ASTWriter &Writer; 2228 Preprocessor &PP; 2229 IdentifierResolver &IdResolver; 2230 bool IsModule; 2231 2232 /// \brief Determines whether this is an "interesting" identifier 2233 /// that needs a full IdentifierInfo structure written into the hash 2234 /// table. 2235 bool isInterestingIdentifier(IdentifierInfo *II, MacroInfo *&Macro) { 2236 if (II->isPoisoned() || 2237 II->isExtensionToken() || 2238 II->getObjCOrBuiltinID() || 2239 II->hasRevertedTokenIDToIdentifier() || 2240 II->getFETokenInfo<void>()) 2241 return true; 2242 2243 return hasMacroDefinition(II, Macro); 2244 } 2245 2246 bool hasMacroDefinition(IdentifierInfo *II, MacroInfo *&Macro) { 2247 if (!II->hasMacroDefinition()) 2248 return false; 2249 2250 if (Macro || (Macro = PP.getMacroInfo(II))) 2251 return !Macro->isBuiltinMacro() && (!IsModule || Macro->isPublic()); 2252 2253 return false; 2254 } 2255 2256public: 2257 typedef IdentifierInfo* key_type; 2258 typedef key_type key_type_ref; 2259 2260 typedef IdentID data_type; 2261 typedef data_type data_type_ref; 2262 2263 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP, 2264 IdentifierResolver &IdResolver, bool IsModule) 2265 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { } 2266 2267 static unsigned ComputeHash(const IdentifierInfo* II) { 2268 return llvm::HashString(II->getName()); 2269 } 2270 2271 std::pair<unsigned,unsigned> 2272 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) { 2273 unsigned KeyLen = II->getLength() + 1; 2274 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1 2275 MacroInfo *Macro = 0; 2276 if (isInterestingIdentifier(II, Macro)) { 2277 DataLen += 2; // 2 bytes for builtin ID, flags 2278 if (hasMacroDefinition(II, Macro)) 2279 DataLen += 4; 2280 2281 for (IdentifierResolver::iterator D = IdResolver.begin(II), 2282 DEnd = IdResolver.end(); 2283 D != DEnd; ++D) 2284 DataLen += sizeof(DeclID); 2285 } 2286 clang::io::Emit16(Out, DataLen); 2287 // We emit the key length after the data length so that every 2288 // string is preceded by a 16-bit length. This matches the PTH 2289 // format for storing identifiers. 2290 clang::io::Emit16(Out, KeyLen); 2291 return std::make_pair(KeyLen, DataLen); 2292 } 2293 2294 void EmitKey(raw_ostream& Out, const IdentifierInfo* II, 2295 unsigned KeyLen) { 2296 // Record the location of the key data. This is used when generating 2297 // the mapping from persistent IDs to strings. 2298 Writer.SetIdentifierOffset(II, Out.tell()); 2299 Out.write(II->getNameStart(), KeyLen); 2300 } 2301 2302 void EmitData(raw_ostream& Out, IdentifierInfo* II, 2303 IdentID ID, unsigned) { 2304 MacroInfo *Macro = 0; 2305 if (!isInterestingIdentifier(II, Macro)) { 2306 clang::io::Emit32(Out, ID << 1); 2307 return; 2308 } 2309 2310 clang::io::Emit32(Out, (ID << 1) | 0x01); 2311 uint32_t Bits = 0; 2312 bool HasMacroDefinition = hasMacroDefinition(II, Macro); 2313 Bits = (uint32_t)II->getObjCOrBuiltinID(); 2314 Bits = (Bits << 1) | unsigned(HasMacroDefinition); 2315 Bits = (Bits << 1) | unsigned(II->isExtensionToken()); 2316 Bits = (Bits << 1) | unsigned(II->isPoisoned()); 2317 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier()); 2318 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword()); 2319 clang::io::Emit16(Out, Bits); 2320 2321 if (HasMacroDefinition) 2322 clang::io::Emit32(Out, Writer.getMacroOffset(II)); 2323 2324 // Emit the declaration IDs in reverse order, because the 2325 // IdentifierResolver provides the declarations as they would be 2326 // visible (e.g., the function "stat" would come before the struct 2327 // "stat"), but the ASTReader adds declarations to the end of the list 2328 // (so we need to see the struct "status" before the function "status"). 2329 // Only emit declarations that aren't from a chained PCH, though. 2330 SmallVector<Decl *, 16> Decls(IdResolver.begin(II), 2331 IdResolver.end()); 2332 for (SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(), 2333 DEnd = Decls.rend(); 2334 D != DEnd; ++D) 2335 clang::io::Emit32(Out, Writer.getDeclID(*D)); 2336 } 2337}; 2338} // end anonymous namespace 2339 2340/// \brief Write the identifier table into the AST file. 2341/// 2342/// The identifier table consists of a blob containing string data 2343/// (the actual identifiers themselves) and a separate "offsets" index 2344/// that maps identifier IDs to locations within the blob. 2345void ASTWriter::WriteIdentifierTable(Preprocessor &PP, 2346 IdentifierResolver &IdResolver, 2347 bool IsModule) { 2348 using namespace llvm; 2349 2350 // Create and write out the blob that contains the identifier 2351 // strings. 2352 { 2353 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator; 2354 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule); 2355 2356 // Look for any identifiers that were named while processing the 2357 // headers, but are otherwise not needed. We add these to the hash 2358 // table to enable checking of the predefines buffer in the case 2359 // where the user adds new macro definitions when building the AST 2360 // file. 2361 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 2362 IDEnd = PP.getIdentifierTable().end(); 2363 ID != IDEnd; ++ID) 2364 getIdentifierRef(ID->second); 2365 2366 // Create the on-disk hash table representation. We only store offsets 2367 // for identifiers that appear here for the first time. 2368 IdentifierOffsets.resize(NextIdentID - FirstIdentID); 2369 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator 2370 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end(); 2371 ID != IDEnd; ++ID) { 2372 assert(ID->first && "NULL identifier in identifier table"); 2373 if (!Chain || !ID->first->isFromAST() || 2374 ID->first->hasChangedSinceDeserialization()) 2375 Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second, 2376 Trait); 2377 } 2378 2379 // Create the on-disk hash table in a buffer. 2380 llvm::SmallString<4096> IdentifierTable; 2381 uint32_t BucketOffset; 2382 { 2383 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule); 2384 llvm::raw_svector_ostream Out(IdentifierTable); 2385 // Make sure that no bucket is at offset 0 2386 clang::io::Emit32(Out, 0); 2387 BucketOffset = Generator.Emit(Out, Trait); 2388 } 2389 2390 // Create a blob abbreviation 2391 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2392 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE)); 2393 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2394 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2395 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev); 2396 2397 // Write the identifier table 2398 RecordData Record; 2399 Record.push_back(IDENTIFIER_TABLE); 2400 Record.push_back(BucketOffset); 2401 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str()); 2402 } 2403 2404 // Write the offsets table for identifier IDs. 2405 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2406 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET)); 2407 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers 2408 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 2409 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2410 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2411 2412 RecordData Record; 2413 Record.push_back(IDENTIFIER_OFFSET); 2414 Record.push_back(IdentifierOffsets.size()); 2415 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS); 2416 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record, 2417 data(IdentifierOffsets)); 2418} 2419 2420//===----------------------------------------------------------------------===// 2421// DeclContext's Name Lookup Table Serialization 2422//===----------------------------------------------------------------------===// 2423 2424namespace { 2425// Trait used for the on-disk hash table used in the method pool. 2426class ASTDeclContextNameLookupTrait { 2427 ASTWriter &Writer; 2428 2429public: 2430 typedef DeclarationName key_type; 2431 typedef key_type key_type_ref; 2432 2433 typedef DeclContext::lookup_result data_type; 2434 typedef const data_type& data_type_ref; 2435 2436 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { } 2437 2438 unsigned ComputeHash(DeclarationName Name) { 2439 llvm::FoldingSetNodeID ID; 2440 ID.AddInteger(Name.getNameKind()); 2441 2442 switch (Name.getNameKind()) { 2443 case DeclarationName::Identifier: 2444 ID.AddString(Name.getAsIdentifierInfo()->getName()); 2445 break; 2446 case DeclarationName::ObjCZeroArgSelector: 2447 case DeclarationName::ObjCOneArgSelector: 2448 case DeclarationName::ObjCMultiArgSelector: 2449 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector())); 2450 break; 2451 case DeclarationName::CXXConstructorName: 2452 case DeclarationName::CXXDestructorName: 2453 case DeclarationName::CXXConversionFunctionName: 2454 break; 2455 case DeclarationName::CXXOperatorName: 2456 ID.AddInteger(Name.getCXXOverloadedOperator()); 2457 break; 2458 case DeclarationName::CXXLiteralOperatorName: 2459 ID.AddString(Name.getCXXLiteralIdentifier()->getName()); 2460 case DeclarationName::CXXUsingDirective: 2461 break; 2462 } 2463 2464 return ID.ComputeHash(); 2465 } 2466 2467 std::pair<unsigned,unsigned> 2468 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name, 2469 data_type_ref Lookup) { 2470 unsigned KeyLen = 1; 2471 switch (Name.getNameKind()) { 2472 case DeclarationName::Identifier: 2473 case DeclarationName::ObjCZeroArgSelector: 2474 case DeclarationName::ObjCOneArgSelector: 2475 case DeclarationName::ObjCMultiArgSelector: 2476 case DeclarationName::CXXLiteralOperatorName: 2477 KeyLen += 4; 2478 break; 2479 case DeclarationName::CXXOperatorName: 2480 KeyLen += 1; 2481 break; 2482 case DeclarationName::CXXConstructorName: 2483 case DeclarationName::CXXDestructorName: 2484 case DeclarationName::CXXConversionFunctionName: 2485 case DeclarationName::CXXUsingDirective: 2486 break; 2487 } 2488 clang::io::Emit16(Out, KeyLen); 2489 2490 // 2 bytes for num of decls and 4 for each DeclID. 2491 unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first); 2492 clang::io::Emit16(Out, DataLen); 2493 2494 return std::make_pair(KeyLen, DataLen); 2495 } 2496 2497 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) { 2498 using namespace clang::io; 2499 2500 assert(Name.getNameKind() < 0x100 && "Invalid name kind ?"); 2501 Emit8(Out, Name.getNameKind()); 2502 switch (Name.getNameKind()) { 2503 case DeclarationName::Identifier: 2504 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo())); 2505 break; 2506 case DeclarationName::ObjCZeroArgSelector: 2507 case DeclarationName::ObjCOneArgSelector: 2508 case DeclarationName::ObjCMultiArgSelector: 2509 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector())); 2510 break; 2511 case DeclarationName::CXXOperatorName: 2512 assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?"); 2513 Emit8(Out, Name.getCXXOverloadedOperator()); 2514 break; 2515 case DeclarationName::CXXLiteralOperatorName: 2516 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier())); 2517 break; 2518 case DeclarationName::CXXConstructorName: 2519 case DeclarationName::CXXDestructorName: 2520 case DeclarationName::CXXConversionFunctionName: 2521 case DeclarationName::CXXUsingDirective: 2522 break; 2523 } 2524 } 2525 2526 void EmitData(raw_ostream& Out, key_type_ref, 2527 data_type Lookup, unsigned DataLen) { 2528 uint64_t Start = Out.tell(); (void)Start; 2529 clang::io::Emit16(Out, Lookup.second - Lookup.first); 2530 for (; Lookup.first != Lookup.second; ++Lookup.first) 2531 clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first)); 2532 2533 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 2534 } 2535}; 2536} // end anonymous namespace 2537 2538/// \brief Write the block containing all of the declaration IDs 2539/// visible from the given DeclContext. 2540/// 2541/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the 2542/// bitstream, or 0 if no block was written. 2543uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context, 2544 DeclContext *DC) { 2545 if (DC->getPrimaryContext() != DC) 2546 return 0; 2547 2548 // Since there is no name lookup into functions or methods, don't bother to 2549 // build a visible-declarations table for these entities. 2550 if (DC->isFunctionOrMethod()) 2551 return 0; 2552 2553 // If not in C++, we perform name lookup for the translation unit via the 2554 // IdentifierInfo chains, don't bother to build a visible-declarations table. 2555 // FIXME: In C++ we need the visible declarations in order to "see" the 2556 // friend declarations, is there a way to do this without writing the table ? 2557 if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus) 2558 return 0; 2559 2560 // Force the DeclContext to build a its name-lookup table. 2561 if (!DC->hasExternalVisibleStorage()) 2562 DC->lookup(DeclarationName()); 2563 2564 // Serialize the contents of the mapping used for lookup. Note that, 2565 // although we have two very different code paths, the serialized 2566 // representation is the same for both cases: a declaration name, 2567 // followed by a size, followed by references to the visible 2568 // declarations that have that name. 2569 uint64_t Offset = Stream.GetCurrentBitNo(); 2570 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr()); 2571 if (!Map || Map->empty()) 2572 return 0; 2573 2574 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator; 2575 ASTDeclContextNameLookupTrait Trait(*this); 2576 2577 // Create the on-disk hash table representation. 2578 DeclarationName ConversionName; 2579 llvm::SmallVector<NamedDecl *, 4> ConversionDecls; 2580 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); 2581 D != DEnd; ++D) { 2582 DeclarationName Name = D->first; 2583 DeclContext::lookup_result Result = D->second.getLookupResult(); 2584 if (Result.first != Result.second) { 2585 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2586 // Hash all conversion function names to the same name. The actual 2587 // type information in conversion function name is not used in the 2588 // key (since such type information is not stable across different 2589 // modules), so the intended effect is to coalesce all of the conversion 2590 // functions under a single key. 2591 if (!ConversionName) 2592 ConversionName = Name; 2593 ConversionDecls.append(Result.first, Result.second); 2594 continue; 2595 } 2596 2597 Generator.insert(Name, Result, Trait); 2598 } 2599 } 2600 2601 // Add the conversion functions 2602 if (!ConversionDecls.empty()) { 2603 Generator.insert(ConversionName, 2604 DeclContext::lookup_result(ConversionDecls.begin(), 2605 ConversionDecls.end()), 2606 Trait); 2607 } 2608 2609 // Create the on-disk hash table in a buffer. 2610 llvm::SmallString<4096> LookupTable; 2611 uint32_t BucketOffset; 2612 { 2613 llvm::raw_svector_ostream Out(LookupTable); 2614 // Make sure that no bucket is at offset 0 2615 clang::io::Emit32(Out, 0); 2616 BucketOffset = Generator.Emit(Out, Trait); 2617 } 2618 2619 // Write the lookup table 2620 RecordData Record; 2621 Record.push_back(DECL_CONTEXT_VISIBLE); 2622 Record.push_back(BucketOffset); 2623 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record, 2624 LookupTable.str()); 2625 2626 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record); 2627 ++NumVisibleDeclContexts; 2628 return Offset; 2629} 2630 2631/// \brief Write an UPDATE_VISIBLE block for the given context. 2632/// 2633/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing 2634/// DeclContext in a dependent AST file. As such, they only exist for the TU 2635/// (in C++) and for namespaces. 2636void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) { 2637 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr()); 2638 if (!Map || Map->empty()) 2639 return; 2640 2641 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator; 2642 ASTDeclContextNameLookupTrait Trait(*this); 2643 2644 // Create the hash table. 2645 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); 2646 D != DEnd; ++D) { 2647 DeclarationName Name = D->first; 2648 DeclContext::lookup_result Result = D->second.getLookupResult(); 2649 // For any name that appears in this table, the results are complete, i.e. 2650 // they overwrite results from previous PCHs. Merging is always a mess. 2651 if (Result.first != Result.second) 2652 Generator.insert(Name, Result, Trait); 2653 } 2654 2655 // Create the on-disk hash table in a buffer. 2656 llvm::SmallString<4096> LookupTable; 2657 uint32_t BucketOffset; 2658 { 2659 llvm::raw_svector_ostream Out(LookupTable); 2660 // Make sure that no bucket is at offset 0 2661 clang::io::Emit32(Out, 0); 2662 BucketOffset = Generator.Emit(Out, Trait); 2663 } 2664 2665 // Write the lookup table 2666 RecordData Record; 2667 Record.push_back(UPDATE_VISIBLE); 2668 Record.push_back(getDeclID(cast<Decl>(DC))); 2669 Record.push_back(BucketOffset); 2670 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str()); 2671} 2672 2673/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions. 2674void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) { 2675 RecordData Record; 2676 Record.push_back(Opts.fp_contract); 2677 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record); 2678} 2679 2680/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions. 2681void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) { 2682 if (!SemaRef.Context.getLangOptions().OpenCL) 2683 return; 2684 2685 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions(); 2686 RecordData Record; 2687#define OPENCLEXT(nm) Record.push_back(Opts.nm); 2688#include "clang/Basic/OpenCLExtensions.def" 2689 Stream.EmitRecord(OPENCL_EXTENSIONS, Record); 2690} 2691 2692//===----------------------------------------------------------------------===// 2693// General Serialization Routines 2694//===----------------------------------------------------------------------===// 2695 2696/// \brief Write a record containing the given attributes. 2697void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) { 2698 Record.push_back(Attrs.size()); 2699 for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){ 2700 const Attr * A = *i; 2701 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs 2702 AddSourceRange(A->getRange(), Record); 2703 2704#include "clang/Serialization/AttrPCHWrite.inc" 2705 2706 } 2707} 2708 2709void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) { 2710 Record.push_back(Str.size()); 2711 Record.insert(Record.end(), Str.begin(), Str.end()); 2712} 2713 2714void ASTWriter::AddVersionTuple(const VersionTuple &Version, 2715 RecordDataImpl &Record) { 2716 Record.push_back(Version.getMajor()); 2717 if (llvm::Optional<unsigned> Minor = Version.getMinor()) 2718 Record.push_back(*Minor + 1); 2719 else 2720 Record.push_back(0); 2721 if (llvm::Optional<unsigned> Subminor = Version.getSubminor()) 2722 Record.push_back(*Subminor + 1); 2723 else 2724 Record.push_back(0); 2725} 2726 2727/// \brief Note that the identifier II occurs at the given offset 2728/// within the identifier table. 2729void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) { 2730 IdentID ID = IdentifierIDs[II]; 2731 // Only store offsets new to this AST file. Other identifier names are looked 2732 // up earlier in the chain and thus don't need an offset. 2733 if (ID >= FirstIdentID) 2734 IdentifierOffsets[ID - FirstIdentID] = Offset; 2735} 2736 2737/// \brief Note that the selector Sel occurs at the given offset 2738/// within the method pool/selector table. 2739void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { 2740 unsigned ID = SelectorIDs[Sel]; 2741 assert(ID && "Unknown selector"); 2742 // Don't record offsets for selectors that are also available in a different 2743 // file. 2744 if (ID < FirstSelectorID) 2745 return; 2746 SelectorOffsets[ID - FirstSelectorID] = Offset; 2747} 2748 2749ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream) 2750 : Stream(Stream), Context(0), Chain(0), WritingAST(false), 2751 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID), 2752 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID), 2753 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID), 2754 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID), 2755 CollectedStmts(&StmtsToEmit), 2756 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0), 2757 NumVisibleDeclContexts(0), 2758 NextCXXBaseSpecifiersID(1), 2759 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0), 2760 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0), 2761 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0), 2762 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0), 2763 DeclTypedefAbbrev(0), 2764 DeclVarAbbrev(0), DeclFieldAbbrev(0), 2765 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0) 2766{ 2767} 2768 2769ASTWriter::~ASTWriter() { 2770 for (FileDeclIDsTy::iterator 2771 I = FileDeclIDs.begin(), E = FileDeclIDs.end(); I != E; ++I) 2772 delete I->second; 2773} 2774 2775void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls, 2776 const std::string &OutputFile, 2777 bool IsModule, StringRef isysroot) { 2778 WritingAST = true; 2779 2780 // Emit the file header. 2781 Stream.Emit((unsigned)'C', 8); 2782 Stream.Emit((unsigned)'P', 8); 2783 Stream.Emit((unsigned)'C', 8); 2784 Stream.Emit((unsigned)'H', 8); 2785 2786 WriteBlockInfoBlock(); 2787 2788 Context = &SemaRef.Context; 2789 WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile, IsModule); 2790 Context = 0; 2791 2792 WritingAST = false; 2793} 2794 2795template<typename Vector> 2796static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, 2797 ASTWriter::RecordData &Record) { 2798 for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end(); 2799 I != E; ++I) { 2800 Writer.AddDeclRef(*I, Record); 2801 } 2802} 2803 2804void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls, 2805 StringRef isysroot, 2806 const std::string &OutputFile, bool IsModule) { 2807 using namespace llvm; 2808 2809 ASTContext &Context = SemaRef.Context; 2810 Preprocessor &PP = SemaRef.PP; 2811 2812 // Set up predefined declaration IDs. 2813 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID; 2814 if (Context.ObjCIdDecl) 2815 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID; 2816 if (Context.ObjCSelDecl) 2817 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID; 2818 if (Context.ObjCClassDecl) 2819 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID; 2820 if (Context.Int128Decl) 2821 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID; 2822 if (Context.UInt128Decl) 2823 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID; 2824 if (Context.ObjCInstanceTypeDecl) 2825 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID; 2826 2827 if (!Chain) { 2828 // Make sure that we emit IdentifierInfos (and any attached 2829 // declarations) for builtins. We don't need to do this when we're 2830 // emitting chained PCH files, because all of the builtins will be 2831 // in the original PCH file. 2832 // FIXME: Modules won't like this at all. 2833 IdentifierTable &Table = PP.getIdentifierTable(); 2834 SmallVector<const char *, 32> BuiltinNames; 2835 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames, 2836 Context.getLangOptions().NoBuiltin); 2837 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I) 2838 getIdentifierRef(&Table.get(BuiltinNames[I])); 2839 } 2840 2841 // If there are any out-of-date identifiers, bring them up to date. 2842 if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) { 2843 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 2844 IDEnd = PP.getIdentifierTable().end(); 2845 ID != IDEnd; ++ID) 2846 if (ID->second->isOutOfDate()) 2847 ExtSource->updateOutOfDateIdentifier(*ID->second); 2848 } 2849 2850 // Build a record containing all of the tentative definitions in this file, in 2851 // TentativeDefinitions order. Generally, this record will be empty for 2852 // headers. 2853 RecordData TentativeDefinitions; 2854 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions); 2855 2856 // Build a record containing all of the file scoped decls in this file. 2857 RecordData UnusedFileScopedDecls; 2858 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls, 2859 UnusedFileScopedDecls); 2860 2861 // Build a record containing all of the delegating constructors we still need 2862 // to resolve. 2863 RecordData DelegatingCtorDecls; 2864 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls); 2865 2866 // Write the set of weak, undeclared identifiers. We always write the 2867 // entire table, since later PCH files in a PCH chain are only interested in 2868 // the results at the end of the chain. 2869 RecordData WeakUndeclaredIdentifiers; 2870 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) { 2871 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 2872 I = SemaRef.WeakUndeclaredIdentifiers.begin(), 2873 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) { 2874 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers); 2875 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers); 2876 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers); 2877 WeakUndeclaredIdentifiers.push_back(I->second.getUsed()); 2878 } 2879 } 2880 2881 // Build a record containing all of the locally-scoped external 2882 // declarations in this header file. Generally, this record will be 2883 // empty. 2884 RecordData LocallyScopedExternalDecls; 2885 // FIXME: This is filling in the AST file in densemap order which is 2886 // nondeterminstic! 2887 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 2888 TD = SemaRef.LocallyScopedExternalDecls.begin(), 2889 TDEnd = SemaRef.LocallyScopedExternalDecls.end(); 2890 TD != TDEnd; ++TD) { 2891 if (!TD->second->isFromASTFile()) 2892 AddDeclRef(TD->second, LocallyScopedExternalDecls); 2893 } 2894 2895 // Build a record containing all of the ext_vector declarations. 2896 RecordData ExtVectorDecls; 2897 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls); 2898 2899 // Build a record containing all of the VTable uses information. 2900 RecordData VTableUses; 2901 if (!SemaRef.VTableUses.empty()) { 2902 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 2903 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 2904 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 2905 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 2906 } 2907 } 2908 2909 // Build a record containing all of dynamic classes declarations. 2910 RecordData DynamicClasses; 2911 AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses); 2912 2913 // Build a record containing all of pending implicit instantiations. 2914 RecordData PendingInstantiations; 2915 for (std::deque<Sema::PendingImplicitInstantiation>::iterator 2916 I = SemaRef.PendingInstantiations.begin(), 2917 N = SemaRef.PendingInstantiations.end(); I != N; ++I) { 2918 AddDeclRef(I->first, PendingInstantiations); 2919 AddSourceLocation(I->second, PendingInstantiations); 2920 } 2921 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 2922 "There are local ones at end of translation unit!"); 2923 2924 // Build a record containing some declaration references. 2925 RecordData SemaDeclRefs; 2926 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) { 2927 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 2928 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 2929 } 2930 2931 RecordData CUDASpecialDeclRefs; 2932 if (Context.getcudaConfigureCallDecl()) { 2933 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs); 2934 } 2935 2936 // Build a record containing all of the known namespaces. 2937 RecordData KnownNamespaces; 2938 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator 2939 I = SemaRef.KnownNamespaces.begin(), 2940 IEnd = SemaRef.KnownNamespaces.end(); 2941 I != IEnd; ++I) { 2942 if (!I->second) 2943 AddDeclRef(I->first, KnownNamespaces); 2944 } 2945 2946 // Write the remaining AST contents. 2947 RecordData Record; 2948 Stream.EnterSubblock(AST_BLOCK_ID, 5); 2949 WriteMetadata(Context, isysroot, OutputFile); 2950 WriteLanguageOptions(Context.getLangOptions()); 2951 if (StatCalls && isysroot.empty()) 2952 WriteStatCache(*StatCalls); 2953 2954 // Create a lexical update block containing all of the declarations in the 2955 // translation unit that do not come from other AST files. 2956 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 2957 SmallVector<KindDeclIDPair, 64> NewGlobalDecls; 2958 for (DeclContext::decl_iterator I = TU->noload_decls_begin(), 2959 E = TU->noload_decls_end(); 2960 I != E; ++I) { 2961 if (!(*I)->isFromASTFile()) 2962 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I))); 2963 else if ((*I)->isChangedSinceDeserialization()) 2964 (void)GetDeclRef(*I); // Make sure it's written, but don't record it. 2965 } 2966 2967 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev(); 2968 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL)); 2969 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 2970 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv); 2971 Record.clear(); 2972 Record.push_back(TU_UPDATE_LEXICAL); 2973 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, 2974 data(NewGlobalDecls)); 2975 2976 // And a visible updates block for the translation unit. 2977 Abv = new llvm::BitCodeAbbrev(); 2978 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE)); 2979 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 2980 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32)); 2981 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 2982 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv); 2983 WriteDeclContextVisibleUpdate(TU); 2984 2985 // If the translation unit has an anonymous namespace, and we don't already 2986 // have an update block for it, write it as an update block. 2987 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) { 2988 ASTWriter::UpdateRecord &Record = DeclUpdates[TU]; 2989 if (Record.empty()) { 2990 Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE); 2991 Record.push_back(reinterpret_cast<uint64_t>(NS)); 2992 } 2993 } 2994 2995 // Resolve any declaration pointers within the declaration updates block and 2996 // chained Objective-C categories block to declaration IDs. 2997 ResolveDeclUpdatesBlocks(); 2998 ResolveChainedObjCCategories(); 2999 3000 // Form the record of special types. 3001 RecordData SpecialTypes; 3002 AddTypeRef(Context.getBuiltinVaListType(), SpecialTypes); 3003 AddTypeRef(Context.ObjCProtoType, SpecialTypes); 3004 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes); 3005 AddTypeRef(Context.getFILEType(), SpecialTypes); 3006 AddTypeRef(Context.getjmp_bufType(), SpecialTypes); 3007 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes); 3008 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes); 3009 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes); 3010 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes); 3011 3012 // Keep writing types and declarations until all types and 3013 // declarations have been written. 3014 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 3015 WriteDeclsBlockAbbrevs(); 3016 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(), 3017 E = DeclsToRewrite.end(); 3018 I != E; ++I) 3019 DeclTypesToEmit.push(const_cast<Decl*>(*I)); 3020 while (!DeclTypesToEmit.empty()) { 3021 DeclOrType DOT = DeclTypesToEmit.front(); 3022 DeclTypesToEmit.pop(); 3023 if (DOT.isType()) 3024 WriteType(DOT.getType()); 3025 else 3026 WriteDecl(Context, DOT.getDecl()); 3027 } 3028 Stream.ExitBlock(); 3029 3030 WriteFileDeclIDsMap(); 3031 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot); 3032 3033 if (Chain) { 3034 // Write the mapping information describing our module dependencies and how 3035 // each of those modules were mapped into our own offset/ID space, so that 3036 // the reader can build the appropriate mapping to its own offset/ID space. 3037 // The map consists solely of a blob with the following format: 3038 // *(module-name-len:i16 module-name:len*i8 3039 // source-location-offset:i32 3040 // identifier-id:i32 3041 // preprocessed-entity-id:i32 3042 // macro-definition-id:i32 3043 // selector-id:i32 3044 // declaration-id:i32 3045 // c++-base-specifiers-id:i32 3046 // type-id:i32) 3047 // 3048 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 3049 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP)); 3050 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3051 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev); 3052 llvm::SmallString<2048> Buffer; 3053 { 3054 llvm::raw_svector_ostream Out(Buffer); 3055 for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(), 3056 MEnd = Chain->ModuleMgr.end(); 3057 M != MEnd; ++M) { 3058 StringRef FileName = (*M)->FileName; 3059 io::Emit16(Out, FileName.size()); 3060 Out.write(FileName.data(), FileName.size()); 3061 io::Emit32(Out, (*M)->SLocEntryBaseOffset); 3062 io::Emit32(Out, (*M)->BaseIdentifierID); 3063 io::Emit32(Out, (*M)->BasePreprocessedEntityID); 3064 io::Emit32(Out, (*M)->BaseSelectorID); 3065 io::Emit32(Out, (*M)->BaseDeclID); 3066 io::Emit32(Out, (*M)->BaseTypeIndex); 3067 } 3068 } 3069 Record.clear(); 3070 Record.push_back(MODULE_OFFSET_MAP); 3071 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record, 3072 Buffer.data(), Buffer.size()); 3073 } 3074 3075 WritePreprocessor(PP, IsModule); 3076 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot); 3077 WriteSelectors(SemaRef); 3078 WriteReferencedSelectorsPool(SemaRef); 3079 WriteIdentifierTable(PP, SemaRef.IdResolver, IsModule); 3080 WriteFPPragmaOptions(SemaRef.getFPOptions()); 3081 WriteOpenCLExtensions(SemaRef); 3082 3083 WriteTypeDeclOffsets(); 3084 WritePragmaDiagnosticMappings(Context.getDiagnostics()); 3085 3086 WriteCXXBaseSpecifiersOffsets(); 3087 3088 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes); 3089 3090 /// Build a record containing first declarations from a chained PCH and the 3091 /// most recent declarations in this AST that they point to. 3092 RecordData FirstLatestDeclIDs; 3093 for (FirstLatestDeclMap::iterator I = FirstLatestDecls.begin(), 3094 E = FirstLatestDecls.end(); 3095 I != E; ++I) { 3096 AddDeclRef(I->first, FirstLatestDeclIDs); 3097 AddDeclRef(I->second, FirstLatestDeclIDs); 3098 } 3099 3100 if (!FirstLatestDeclIDs.empty()) 3101 Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs); 3102 3103 // Write the record containing external, unnamed definitions. 3104 if (!ExternalDefinitions.empty()) 3105 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions); 3106 3107 // Write the record containing tentative definitions. 3108 if (!TentativeDefinitions.empty()) 3109 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 3110 3111 // Write the record containing unused file scoped decls. 3112 if (!UnusedFileScopedDecls.empty()) 3113 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 3114 3115 // Write the record containing weak undeclared identifiers. 3116 if (!WeakUndeclaredIdentifiers.empty()) 3117 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 3118 WeakUndeclaredIdentifiers); 3119 3120 // Write the record containing locally-scoped external definitions. 3121 if (!LocallyScopedExternalDecls.empty()) 3122 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS, 3123 LocallyScopedExternalDecls); 3124 3125 // Write the record containing ext_vector type names. 3126 if (!ExtVectorDecls.empty()) 3127 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 3128 3129 // Write the record containing VTable uses information. 3130 if (!VTableUses.empty()) 3131 Stream.EmitRecord(VTABLE_USES, VTableUses); 3132 3133 // Write the record containing dynamic classes declarations. 3134 if (!DynamicClasses.empty()) 3135 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses); 3136 3137 // Write the record containing pending implicit instantiations. 3138 if (!PendingInstantiations.empty()) 3139 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 3140 3141 // Write the record containing declaration references of Sema. 3142 if (!SemaDeclRefs.empty()) 3143 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 3144 3145 // Write the record containing CUDA-specific declaration references. 3146 if (!CUDASpecialDeclRefs.empty()) 3147 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs); 3148 3149 // Write the delegating constructors. 3150 if (!DelegatingCtorDecls.empty()) 3151 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls); 3152 3153 // Write the known namespaces. 3154 if (!KnownNamespaces.empty()) 3155 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces); 3156 3157 // Write the visible updates to DeclContexts. 3158 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator 3159 I = UpdatedDeclContexts.begin(), 3160 E = UpdatedDeclContexts.end(); 3161 I != E; ++I) 3162 WriteDeclContextVisibleUpdate(*I); 3163 3164 WriteDeclUpdatesBlocks(); 3165 WriteDeclReplacementsBlock(); 3166 WriteChainedObjCCategories(); 3167 3168 // Some simple statistics 3169 Record.clear(); 3170 Record.push_back(NumStatements); 3171 Record.push_back(NumMacros); 3172 Record.push_back(NumLexicalDeclContexts); 3173 Record.push_back(NumVisibleDeclContexts); 3174 Stream.EmitRecord(STATISTICS, Record); 3175 Stream.ExitBlock(); 3176} 3177 3178/// \brief Go through the declaration update blocks and resolve declaration 3179/// pointers into declaration IDs. 3180void ASTWriter::ResolveDeclUpdatesBlocks() { 3181 for (DeclUpdateMap::iterator 3182 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) { 3183 const Decl *D = I->first; 3184 UpdateRecord &URec = I->second; 3185 3186 if (DeclsToRewrite.count(D)) 3187 continue; // The decl will be written completely 3188 3189 unsigned Idx = 0, N = URec.size(); 3190 while (Idx < N) { 3191 switch ((DeclUpdateKind)URec[Idx++]) { 3192 case UPD_CXX_SET_DEFINITIONDATA: 3193 case UPD_CXX_ADDED_IMPLICIT_MEMBER: 3194 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: 3195 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: 3196 URec[Idx] = GetDeclRef(reinterpret_cast<Decl *>(URec[Idx])); 3197 ++Idx; 3198 break; 3199 3200 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER: 3201 ++Idx; 3202 break; 3203 } 3204 } 3205 } 3206} 3207 3208void ASTWriter::WriteDeclUpdatesBlocks() { 3209 if (DeclUpdates.empty()) 3210 return; 3211 3212 RecordData OffsetsRecord; 3213 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 3214 for (DeclUpdateMap::iterator 3215 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) { 3216 const Decl *D = I->first; 3217 UpdateRecord &URec = I->second; 3218 3219 if (DeclsToRewrite.count(D)) 3220 continue; // The decl will be written completely,no need to store updates. 3221 3222 uint64_t Offset = Stream.GetCurrentBitNo(); 3223 Stream.EmitRecord(DECL_UPDATES, URec); 3224 3225 OffsetsRecord.push_back(GetDeclRef(D)); 3226 OffsetsRecord.push_back(Offset); 3227 } 3228 Stream.ExitBlock(); 3229 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord); 3230} 3231 3232void ASTWriter::WriteDeclReplacementsBlock() { 3233 if (ReplacedDecls.empty()) 3234 return; 3235 3236 RecordData Record; 3237 for (SmallVector<std::pair<DeclID, uint64_t>, 16>::iterator 3238 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) { 3239 Record.push_back(I->first); 3240 Record.push_back(I->second); 3241 } 3242 Stream.EmitRecord(DECL_REPLACEMENTS, Record); 3243} 3244 3245void ASTWriter::ResolveChainedObjCCategories() { 3246 for (SmallVector<ChainedObjCCategoriesData, 16>::iterator 3247 I = LocalChainedObjCCategories.begin(), 3248 E = LocalChainedObjCCategories.end(); I != E; ++I) { 3249 ChainedObjCCategoriesData &Data = *I; 3250 Data.InterfaceID = GetDeclRef(Data.Interface); 3251 Data.TailCategoryID = GetDeclRef(Data.TailCategory); 3252 } 3253 3254} 3255 3256void ASTWriter::WriteChainedObjCCategories() { 3257 if (LocalChainedObjCCategories.empty()) 3258 return; 3259 3260 RecordData Record; 3261 for (SmallVector<ChainedObjCCategoriesData, 16>::iterator 3262 I = LocalChainedObjCCategories.begin(), 3263 E = LocalChainedObjCCategories.end(); I != E; ++I) { 3264 ChainedObjCCategoriesData &Data = *I; 3265 serialization::DeclID 3266 HeadCatID = getDeclID(Data.Interface->getCategoryList()); 3267 assert(HeadCatID != 0 && "Category not written ?"); 3268 3269 Record.push_back(Data.InterfaceID); 3270 Record.push_back(HeadCatID); 3271 Record.push_back(Data.TailCategoryID); 3272 } 3273 Stream.EmitRecord(OBJC_CHAINED_CATEGORIES, Record); 3274} 3275 3276void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) { 3277 Record.push_back(Loc.getRawEncoding()); 3278} 3279 3280void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) { 3281 AddSourceLocation(Range.getBegin(), Record); 3282 AddSourceLocation(Range.getEnd(), Record); 3283} 3284 3285void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) { 3286 Record.push_back(Value.getBitWidth()); 3287 const uint64_t *Words = Value.getRawData(); 3288 Record.append(Words, Words + Value.getNumWords()); 3289} 3290 3291void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) { 3292 Record.push_back(Value.isUnsigned()); 3293 AddAPInt(Value, Record); 3294} 3295 3296void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) { 3297 AddAPInt(Value.bitcastToAPInt(), Record); 3298} 3299 3300void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) { 3301 Record.push_back(getIdentifierRef(II)); 3302} 3303 3304IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) { 3305 if (II == 0) 3306 return 0; 3307 3308 IdentID &ID = IdentifierIDs[II]; 3309 if (ID == 0) 3310 ID = NextIdentID++; 3311 return ID; 3312} 3313 3314void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) { 3315 Record.push_back(getSelectorRef(SelRef)); 3316} 3317 3318SelectorID ASTWriter::getSelectorRef(Selector Sel) { 3319 if (Sel.getAsOpaquePtr() == 0) { 3320 return 0; 3321 } 3322 3323 SelectorID &SID = SelectorIDs[Sel]; 3324 if (SID == 0 && Chain) { 3325 // This might trigger a ReadSelector callback, which will set the ID for 3326 // this selector. 3327 Chain->LoadSelector(Sel); 3328 } 3329 if (SID == 0) { 3330 SID = NextSelectorID++; 3331 } 3332 return SID; 3333} 3334 3335void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) { 3336 AddDeclRef(Temp->getDestructor(), Record); 3337} 3338 3339void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases, 3340 CXXBaseSpecifier const *BasesEnd, 3341 RecordDataImpl &Record) { 3342 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded"); 3343 CXXBaseSpecifiersToWrite.push_back( 3344 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID, 3345 Bases, BasesEnd)); 3346 Record.push_back(NextCXXBaseSpecifiersID++); 3347} 3348 3349void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind, 3350 const TemplateArgumentLocInfo &Arg, 3351 RecordDataImpl &Record) { 3352 switch (Kind) { 3353 case TemplateArgument::Expression: 3354 AddStmt(Arg.getAsExpr()); 3355 break; 3356 case TemplateArgument::Type: 3357 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record); 3358 break; 3359 case TemplateArgument::Template: 3360 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record); 3361 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 3362 break; 3363 case TemplateArgument::TemplateExpansion: 3364 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record); 3365 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 3366 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record); 3367 break; 3368 case TemplateArgument::Null: 3369 case TemplateArgument::Integral: 3370 case TemplateArgument::Declaration: 3371 case TemplateArgument::Pack: 3372 break; 3373 } 3374} 3375 3376void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg, 3377 RecordDataImpl &Record) { 3378 AddTemplateArgument(Arg.getArgument(), Record); 3379 3380 if (Arg.getArgument().getKind() == TemplateArgument::Expression) { 3381 bool InfoHasSameExpr 3382 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr(); 3383 Record.push_back(InfoHasSameExpr); 3384 if (InfoHasSameExpr) 3385 return; // Avoid storing the same expr twice. 3386 } 3387 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(), 3388 Record); 3389} 3390 3391void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo, 3392 RecordDataImpl &Record) { 3393 if (TInfo == 0) { 3394 AddTypeRef(QualType(), Record); 3395 return; 3396 } 3397 3398 AddTypeLoc(TInfo->getTypeLoc(), Record); 3399} 3400 3401void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) { 3402 AddTypeRef(TL.getType(), Record); 3403 3404 TypeLocWriter TLW(*this, Record); 3405 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 3406 TLW.Visit(TL); 3407} 3408 3409void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) { 3410 Record.push_back(GetOrCreateTypeID(T)); 3411} 3412 3413TypeID ASTWriter::GetOrCreateTypeID( QualType T) { 3414 return MakeTypeID(*Context, T, 3415 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this)); 3416} 3417 3418TypeID ASTWriter::getTypeID(QualType T) const { 3419 return MakeTypeID(*Context, T, 3420 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this)); 3421} 3422 3423TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) { 3424 if (T.isNull()) 3425 return TypeIdx(); 3426 assert(!T.getLocalFastQualifiers()); 3427 3428 TypeIdx &Idx = TypeIdxs[T]; 3429 if (Idx.getIndex() == 0) { 3430 // We haven't seen this type before. Assign it a new ID and put it 3431 // into the queue of types to emit. 3432 Idx = TypeIdx(NextTypeID++); 3433 DeclTypesToEmit.push(T); 3434 } 3435 return Idx; 3436} 3437 3438TypeIdx ASTWriter::getTypeIdx(QualType T) const { 3439 if (T.isNull()) 3440 return TypeIdx(); 3441 assert(!T.getLocalFastQualifiers()); 3442 3443 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 3444 assert(I != TypeIdxs.end() && "Type not emitted!"); 3445 return I->second; 3446} 3447 3448void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) { 3449 Record.push_back(GetDeclRef(D)); 3450} 3451 3452DeclID ASTWriter::GetDeclRef(const Decl *D) { 3453 assert(WritingAST && "Cannot request a declaration ID before AST writing"); 3454 3455 if (D == 0) { 3456 return 0; 3457 } 3458 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer"); 3459 DeclID &ID = DeclIDs[D]; 3460 if (ID == 0) { 3461 // We haven't seen this declaration before. Give it a new ID and 3462 // enqueue it in the list of declarations to emit. 3463 ID = NextDeclID++; 3464 DeclTypesToEmit.push(const_cast<Decl *>(D)); 3465 } else if (ID < FirstDeclID && D->isChangedSinceDeserialization()) { 3466 // We don't add it to the replacement collection here, because we don't 3467 // have the offset yet. 3468 DeclTypesToEmit.push(const_cast<Decl *>(D)); 3469 // Reset the flag, so that we don't add this decl multiple times. 3470 const_cast<Decl *>(D)->setChangedSinceDeserialization(false); 3471 } 3472 3473 return ID; 3474} 3475 3476DeclID ASTWriter::getDeclID(const Decl *D) { 3477 if (D == 0) 3478 return 0; 3479 3480 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!"); 3481 return DeclIDs[D]; 3482} 3483 3484static inline bool compLocDecl(std::pair<unsigned, serialization::DeclID> L, 3485 std::pair<unsigned, serialization::DeclID> R) { 3486 return L.first < R.first; 3487} 3488 3489void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID, 3490 SourceLocation FileLoc) { 3491 assert(ID); 3492 assert(FileLoc.isValid()); 3493 assert(FileLoc.isFileID()); 3494 3495 // We only keep track of the file-level declarations of each file. 3496 if (!D->getLexicalDeclContext()->isFileContext()) 3497 return; 3498 3499 SourceManager &SM = Context->getSourceManager(); 3500 assert(SM.isLocalSourceLocation(FileLoc)); 3501 FileID FID = SM.getFileID(FileLoc); 3502 if (FID.isInvalid()) 3503 return; 3504 const SrcMgr::SLocEntry *Entry = &SM.getSLocEntry(FID); 3505 assert(Entry->isFile()); 3506 3507 DeclIDInFileInfo *&Info = FileDeclIDs[Entry]; 3508 if (!Info) 3509 Info = new DeclIDInFileInfo(); 3510 3511 unsigned RawLoc = FileLoc.getRawEncoding(); 3512 std::pair<unsigned, serialization::DeclID> LocDecl(RawLoc, ID); 3513 LocDeclIDsTy &Decls = Info->DeclIDs; 3514 3515 if (Decls.empty() || Decls.back().first <= RawLoc) { 3516 Decls.push_back(LocDecl); 3517 return; 3518 } 3519 3520 LocDeclIDsTy::iterator 3521 I = std::upper_bound(Decls.begin(), Decls.end(), LocDecl, compLocDecl); 3522 3523 Decls.insert(I, LocDecl); 3524} 3525 3526void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) { 3527 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc. 3528 Record.push_back(Name.getNameKind()); 3529 switch (Name.getNameKind()) { 3530 case DeclarationName::Identifier: 3531 AddIdentifierRef(Name.getAsIdentifierInfo(), Record); 3532 break; 3533 3534 case DeclarationName::ObjCZeroArgSelector: 3535 case DeclarationName::ObjCOneArgSelector: 3536 case DeclarationName::ObjCMultiArgSelector: 3537 AddSelectorRef(Name.getObjCSelector(), Record); 3538 break; 3539 3540 case DeclarationName::CXXConstructorName: 3541 case DeclarationName::CXXDestructorName: 3542 case DeclarationName::CXXConversionFunctionName: 3543 AddTypeRef(Name.getCXXNameType(), Record); 3544 break; 3545 3546 case DeclarationName::CXXOperatorName: 3547 Record.push_back(Name.getCXXOverloadedOperator()); 3548 break; 3549 3550 case DeclarationName::CXXLiteralOperatorName: 3551 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record); 3552 break; 3553 3554 case DeclarationName::CXXUsingDirective: 3555 // No extra data to emit 3556 break; 3557 } 3558} 3559 3560void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 3561 DeclarationName Name, RecordDataImpl &Record) { 3562 switch (Name.getNameKind()) { 3563 case DeclarationName::CXXConstructorName: 3564 case DeclarationName::CXXDestructorName: 3565 case DeclarationName::CXXConversionFunctionName: 3566 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record); 3567 break; 3568 3569 case DeclarationName::CXXOperatorName: 3570 AddSourceLocation( 3571 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc), 3572 Record); 3573 AddSourceLocation( 3574 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc), 3575 Record); 3576 break; 3577 3578 case DeclarationName::CXXLiteralOperatorName: 3579 AddSourceLocation( 3580 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc), 3581 Record); 3582 break; 3583 3584 case DeclarationName::Identifier: 3585 case DeclarationName::ObjCZeroArgSelector: 3586 case DeclarationName::ObjCOneArgSelector: 3587 case DeclarationName::ObjCMultiArgSelector: 3588 case DeclarationName::CXXUsingDirective: 3589 break; 3590 } 3591} 3592 3593void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 3594 RecordDataImpl &Record) { 3595 AddDeclarationName(NameInfo.getName(), Record); 3596 AddSourceLocation(NameInfo.getLoc(), Record); 3597 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record); 3598} 3599 3600void ASTWriter::AddQualifierInfo(const QualifierInfo &Info, 3601 RecordDataImpl &Record) { 3602 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record); 3603 Record.push_back(Info.NumTemplParamLists); 3604 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i) 3605 AddTemplateParameterList(Info.TemplParamLists[i], Record); 3606} 3607 3608void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS, 3609 RecordDataImpl &Record) { 3610 // Nested name specifiers usually aren't too long. I think that 8 would 3611 // typically accommodate the vast majority. 3612 SmallVector<NestedNameSpecifier *, 8> NestedNames; 3613 3614 // Push each of the NNS's onto a stack for serialization in reverse order. 3615 while (NNS) { 3616 NestedNames.push_back(NNS); 3617 NNS = NNS->getPrefix(); 3618 } 3619 3620 Record.push_back(NestedNames.size()); 3621 while(!NestedNames.empty()) { 3622 NNS = NestedNames.pop_back_val(); 3623 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind(); 3624 Record.push_back(Kind); 3625 switch (Kind) { 3626 case NestedNameSpecifier::Identifier: 3627 AddIdentifierRef(NNS->getAsIdentifier(), Record); 3628 break; 3629 3630 case NestedNameSpecifier::Namespace: 3631 AddDeclRef(NNS->getAsNamespace(), Record); 3632 break; 3633 3634 case NestedNameSpecifier::NamespaceAlias: 3635 AddDeclRef(NNS->getAsNamespaceAlias(), Record); 3636 break; 3637 3638 case NestedNameSpecifier::TypeSpec: 3639 case NestedNameSpecifier::TypeSpecWithTemplate: 3640 AddTypeRef(QualType(NNS->getAsType(), 0), Record); 3641 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 3642 break; 3643 3644 case NestedNameSpecifier::Global: 3645 // Don't need to write an associated value. 3646 break; 3647 } 3648 } 3649} 3650 3651void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 3652 RecordDataImpl &Record) { 3653 // Nested name specifiers usually aren't too long. I think that 8 would 3654 // typically accommodate the vast majority. 3655 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 3656 3657 // Push each of the nested-name-specifiers's onto a stack for 3658 // serialization in reverse order. 3659 while (NNS) { 3660 NestedNames.push_back(NNS); 3661 NNS = NNS.getPrefix(); 3662 } 3663 3664 Record.push_back(NestedNames.size()); 3665 while(!NestedNames.empty()) { 3666 NNS = NestedNames.pop_back_val(); 3667 NestedNameSpecifier::SpecifierKind Kind 3668 = NNS.getNestedNameSpecifier()->getKind(); 3669 Record.push_back(Kind); 3670 switch (Kind) { 3671 case NestedNameSpecifier::Identifier: 3672 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record); 3673 AddSourceRange(NNS.getLocalSourceRange(), Record); 3674 break; 3675 3676 case NestedNameSpecifier::Namespace: 3677 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record); 3678 AddSourceRange(NNS.getLocalSourceRange(), Record); 3679 break; 3680 3681 case NestedNameSpecifier::NamespaceAlias: 3682 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record); 3683 AddSourceRange(NNS.getLocalSourceRange(), Record); 3684 break; 3685 3686 case NestedNameSpecifier::TypeSpec: 3687 case NestedNameSpecifier::TypeSpecWithTemplate: 3688 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 3689 AddTypeLoc(NNS.getTypeLoc(), Record); 3690 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record); 3691 break; 3692 3693 case NestedNameSpecifier::Global: 3694 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record); 3695 break; 3696 } 3697 } 3698} 3699 3700void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) { 3701 TemplateName::NameKind Kind = Name.getKind(); 3702 Record.push_back(Kind); 3703 switch (Kind) { 3704 case TemplateName::Template: 3705 AddDeclRef(Name.getAsTemplateDecl(), Record); 3706 break; 3707 3708 case TemplateName::OverloadedTemplate: { 3709 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate(); 3710 Record.push_back(OvT->size()); 3711 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end(); 3712 I != E; ++I) 3713 AddDeclRef(*I, Record); 3714 break; 3715 } 3716 3717 case TemplateName::QualifiedTemplate: { 3718 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName(); 3719 AddNestedNameSpecifier(QualT->getQualifier(), Record); 3720 Record.push_back(QualT->hasTemplateKeyword()); 3721 AddDeclRef(QualT->getTemplateDecl(), Record); 3722 break; 3723 } 3724 3725 case TemplateName::DependentTemplate: { 3726 DependentTemplateName *DepT = Name.getAsDependentTemplateName(); 3727 AddNestedNameSpecifier(DepT->getQualifier(), Record); 3728 Record.push_back(DepT->isIdentifier()); 3729 if (DepT->isIdentifier()) 3730 AddIdentifierRef(DepT->getIdentifier(), Record); 3731 else 3732 Record.push_back(DepT->getOperator()); 3733 break; 3734 } 3735 3736 case TemplateName::SubstTemplateTemplateParm: { 3737 SubstTemplateTemplateParmStorage *subst 3738 = Name.getAsSubstTemplateTemplateParm(); 3739 AddDeclRef(subst->getParameter(), Record); 3740 AddTemplateName(subst->getReplacement(), Record); 3741 break; 3742 } 3743 3744 case TemplateName::SubstTemplateTemplateParmPack: { 3745 SubstTemplateTemplateParmPackStorage *SubstPack 3746 = Name.getAsSubstTemplateTemplateParmPack(); 3747 AddDeclRef(SubstPack->getParameterPack(), Record); 3748 AddTemplateArgument(SubstPack->getArgumentPack(), Record); 3749 break; 3750 } 3751 } 3752} 3753 3754void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg, 3755 RecordDataImpl &Record) { 3756 Record.push_back(Arg.getKind()); 3757 switch (Arg.getKind()) { 3758 case TemplateArgument::Null: 3759 break; 3760 case TemplateArgument::Type: 3761 AddTypeRef(Arg.getAsType(), Record); 3762 break; 3763 case TemplateArgument::Declaration: 3764 AddDeclRef(Arg.getAsDecl(), Record); 3765 break; 3766 case TemplateArgument::Integral: 3767 AddAPSInt(*Arg.getAsIntegral(), Record); 3768 AddTypeRef(Arg.getIntegralType(), Record); 3769 break; 3770 case TemplateArgument::Template: 3771 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 3772 break; 3773 case TemplateArgument::TemplateExpansion: 3774 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 3775 if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions()) 3776 Record.push_back(*NumExpansions + 1); 3777 else 3778 Record.push_back(0); 3779 break; 3780 case TemplateArgument::Expression: 3781 AddStmt(Arg.getAsExpr()); 3782 break; 3783 case TemplateArgument::Pack: 3784 Record.push_back(Arg.pack_size()); 3785 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end(); 3786 I != E; ++I) 3787 AddTemplateArgument(*I, Record); 3788 break; 3789 } 3790} 3791 3792void 3793ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams, 3794 RecordDataImpl &Record) { 3795 assert(TemplateParams && "No TemplateParams!"); 3796 AddSourceLocation(TemplateParams->getTemplateLoc(), Record); 3797 AddSourceLocation(TemplateParams->getLAngleLoc(), Record); 3798 AddSourceLocation(TemplateParams->getRAngleLoc(), Record); 3799 Record.push_back(TemplateParams->size()); 3800 for (TemplateParameterList::const_iterator 3801 P = TemplateParams->begin(), PEnd = TemplateParams->end(); 3802 P != PEnd; ++P) 3803 AddDeclRef(*P, Record); 3804} 3805 3806/// \brief Emit a template argument list. 3807void 3808ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs, 3809 RecordDataImpl &Record) { 3810 assert(TemplateArgs && "No TemplateArgs!"); 3811 Record.push_back(TemplateArgs->size()); 3812 for (int i=0, e = TemplateArgs->size(); i != e; ++i) 3813 AddTemplateArgument(TemplateArgs->get(i), Record); 3814} 3815 3816 3817void 3818ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) { 3819 Record.push_back(Set.size()); 3820 for (UnresolvedSetImpl::const_iterator 3821 I = Set.begin(), E = Set.end(); I != E; ++I) { 3822 AddDeclRef(I.getDecl(), Record); 3823 Record.push_back(I.getAccess()); 3824 } 3825} 3826 3827void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base, 3828 RecordDataImpl &Record) { 3829 Record.push_back(Base.isVirtual()); 3830 Record.push_back(Base.isBaseOfClass()); 3831 Record.push_back(Base.getAccessSpecifierAsWritten()); 3832 Record.push_back(Base.getInheritConstructors()); 3833 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record); 3834 AddSourceRange(Base.getSourceRange(), Record); 3835 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 3836 : SourceLocation(), 3837 Record); 3838} 3839 3840void ASTWriter::FlushCXXBaseSpecifiers() { 3841 RecordData Record; 3842 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) { 3843 Record.clear(); 3844 3845 // Record the offset of this base-specifier set. 3846 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1; 3847 if (Index == CXXBaseSpecifiersOffsets.size()) 3848 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo()); 3849 else { 3850 if (Index > CXXBaseSpecifiersOffsets.size()) 3851 CXXBaseSpecifiersOffsets.resize(Index + 1); 3852 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo(); 3853 } 3854 3855 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases, 3856 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd; 3857 Record.push_back(BEnd - B); 3858 for (; B != BEnd; ++B) 3859 AddCXXBaseSpecifier(*B, Record); 3860 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record); 3861 3862 // Flush any expressions that were written as part of the base specifiers. 3863 FlushStmts(); 3864 } 3865 3866 CXXBaseSpecifiersToWrite.clear(); 3867} 3868 3869void ASTWriter::AddCXXCtorInitializers( 3870 const CXXCtorInitializer * const *CtorInitializers, 3871 unsigned NumCtorInitializers, 3872 RecordDataImpl &Record) { 3873 Record.push_back(NumCtorInitializers); 3874 for (unsigned i=0; i != NumCtorInitializers; ++i) { 3875 const CXXCtorInitializer *Init = CtorInitializers[i]; 3876 3877 if (Init->isBaseInitializer()) { 3878 Record.push_back(CTOR_INITIALIZER_BASE); 3879 AddTypeSourceInfo(Init->getBaseClassInfo(), Record); 3880 Record.push_back(Init->isBaseVirtual()); 3881 } else if (Init->isDelegatingInitializer()) { 3882 Record.push_back(CTOR_INITIALIZER_DELEGATING); 3883 AddDeclRef(Init->getTargetConstructor(), Record); 3884 } else if (Init->isMemberInitializer()){ 3885 Record.push_back(CTOR_INITIALIZER_MEMBER); 3886 AddDeclRef(Init->getMember(), Record); 3887 } else { 3888 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER); 3889 AddDeclRef(Init->getIndirectMember(), Record); 3890 } 3891 3892 AddSourceLocation(Init->getMemberLocation(), Record); 3893 AddStmt(Init->getInit()); 3894 AddSourceLocation(Init->getLParenLoc(), Record); 3895 AddSourceLocation(Init->getRParenLoc(), Record); 3896 Record.push_back(Init->isWritten()); 3897 if (Init->isWritten()) { 3898 Record.push_back(Init->getSourceOrder()); 3899 } else { 3900 Record.push_back(Init->getNumArrayIndices()); 3901 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i) 3902 AddDeclRef(Init->getArrayIndex(i), Record); 3903 } 3904 } 3905} 3906 3907void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) { 3908 assert(D->DefinitionData); 3909 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData; 3910 Record.push_back(Data.UserDeclaredConstructor); 3911 Record.push_back(Data.UserDeclaredCopyConstructor); 3912 Record.push_back(Data.UserDeclaredMoveConstructor); 3913 Record.push_back(Data.UserDeclaredCopyAssignment); 3914 Record.push_back(Data.UserDeclaredMoveAssignment); 3915 Record.push_back(Data.UserDeclaredDestructor); 3916 Record.push_back(Data.Aggregate); 3917 Record.push_back(Data.PlainOldData); 3918 Record.push_back(Data.Empty); 3919 Record.push_back(Data.Polymorphic); 3920 Record.push_back(Data.Abstract); 3921 Record.push_back(Data.IsStandardLayout); 3922 Record.push_back(Data.HasNoNonEmptyBases); 3923 Record.push_back(Data.HasPrivateFields); 3924 Record.push_back(Data.HasProtectedFields); 3925 Record.push_back(Data.HasPublicFields); 3926 Record.push_back(Data.HasMutableFields); 3927 Record.push_back(Data.HasTrivialDefaultConstructor); 3928 Record.push_back(Data.HasConstexprNonCopyMoveConstructor); 3929 Record.push_back(Data.HasTrivialCopyConstructor); 3930 Record.push_back(Data.HasTrivialMoveConstructor); 3931 Record.push_back(Data.HasTrivialCopyAssignment); 3932 Record.push_back(Data.HasTrivialMoveAssignment); 3933 Record.push_back(Data.HasTrivialDestructor); 3934 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases); 3935 Record.push_back(Data.ComputedVisibleConversions); 3936 Record.push_back(Data.UserProvidedDefaultConstructor); 3937 Record.push_back(Data.DeclaredDefaultConstructor); 3938 Record.push_back(Data.DeclaredCopyConstructor); 3939 Record.push_back(Data.DeclaredMoveConstructor); 3940 Record.push_back(Data.DeclaredCopyAssignment); 3941 Record.push_back(Data.DeclaredMoveAssignment); 3942 Record.push_back(Data.DeclaredDestructor); 3943 Record.push_back(Data.FailedImplicitMoveConstructor); 3944 Record.push_back(Data.FailedImplicitMoveAssignment); 3945 3946 Record.push_back(Data.NumBases); 3947 if (Data.NumBases > 0) 3948 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases, 3949 Record); 3950 3951 // FIXME: Make VBases lazily computed when needed to avoid storing them. 3952 Record.push_back(Data.NumVBases); 3953 if (Data.NumVBases > 0) 3954 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases, 3955 Record); 3956 3957 AddUnresolvedSet(Data.Conversions, Record); 3958 AddUnresolvedSet(Data.VisibleConversions, Record); 3959 // Data.Definition is the owning decl, no need to write it. 3960 AddDeclRef(Data.FirstFriend, Record); 3961} 3962 3963void ASTWriter::ReaderInitialized(ASTReader *Reader) { 3964 assert(Reader && "Cannot remove chain"); 3965 assert((!Chain || Chain == Reader) && "Cannot replace chain"); 3966 assert(FirstDeclID == NextDeclID && 3967 FirstTypeID == NextTypeID && 3968 FirstIdentID == NextIdentID && 3969 FirstSelectorID == NextSelectorID && 3970 "Setting chain after writing has started."); 3971 3972 Chain = Reader; 3973 3974 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls(); 3975 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes(); 3976 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers(); 3977 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors(); 3978 NextDeclID = FirstDeclID; 3979 NextTypeID = FirstTypeID; 3980 NextIdentID = FirstIdentID; 3981 NextSelectorID = FirstSelectorID; 3982} 3983 3984void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) { 3985 IdentifierIDs[II] = ID; 3986 if (II->hasMacroDefinition()) 3987 DeserializedMacroNames.push_back(II); 3988} 3989 3990void ASTWriter::TypeRead(TypeIdx Idx, QualType T) { 3991 // Always take the highest-numbered type index. This copes with an interesting 3992 // case for chained AST writing where we schedule writing the type and then, 3993 // later, deserialize the type from another AST. In this case, we want to 3994 // keep the higher-numbered entry so that we can properly write it out to 3995 // the AST file. 3996 TypeIdx &StoredIdx = TypeIdxs[T]; 3997 if (Idx.getIndex() >= StoredIdx.getIndex()) 3998 StoredIdx = Idx; 3999} 4000 4001void ASTWriter::DeclRead(DeclID ID, const Decl *D) { 4002 DeclIDs[D] = ID; 4003} 4004 4005void ASTWriter::SelectorRead(SelectorID ID, Selector S) { 4006 SelectorIDs[S] = ID; 4007} 4008 4009void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID, 4010 MacroDefinition *MD) { 4011 assert(MacroDefinitions.find(MD) == MacroDefinitions.end()); 4012 MacroDefinitions[MD] = ID; 4013} 4014 4015void ASTWriter::CompletedTagDefinition(const TagDecl *D) { 4016 assert(D->isCompleteDefinition()); 4017 assert(!WritingAST && "Already writing the AST!"); 4018 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 4019 // We are interested when a PCH decl is modified. 4020 if (RD->isFromASTFile()) { 4021 // A forward reference was mutated into a definition. Rewrite it. 4022 // FIXME: This happens during template instantiation, should we 4023 // have created a new definition decl instead ? 4024 RewriteDecl(RD); 4025 } 4026 4027 for (CXXRecordDecl::redecl_iterator 4028 I = RD->redecls_begin(), E = RD->redecls_end(); I != E; ++I) { 4029 CXXRecordDecl *Redecl = cast<CXXRecordDecl>(*I); 4030 if (Redecl == RD) 4031 continue; 4032 4033 // We are interested when a PCH decl is modified. 4034 if (Redecl->isFromASTFile()) { 4035 UpdateRecord &Record = DeclUpdates[Redecl]; 4036 Record.push_back(UPD_CXX_SET_DEFINITIONDATA); 4037 assert(Redecl->DefinitionData); 4038 assert(Redecl->DefinitionData->Definition == D); 4039 Record.push_back(reinterpret_cast<uint64_t>(D)); // the DefinitionDecl 4040 } 4041 } 4042 } 4043} 4044void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) { 4045 assert(!WritingAST && "Already writing the AST!"); 4046 4047 // TU and namespaces are handled elsewhere. 4048 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC)) 4049 return; 4050 4051 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile())) 4052 return; // Not a source decl added to a DeclContext from PCH. 4053 4054 AddUpdatedDeclContext(DC); 4055} 4056 4057void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { 4058 assert(!WritingAST && "Already writing the AST!"); 4059 assert(D->isImplicit()); 4060 if (!(!D->isFromASTFile() && RD->isFromASTFile())) 4061 return; // Not a source member added to a class from PCH. 4062 if (!isa<CXXMethodDecl>(D)) 4063 return; // We are interested in lazily declared implicit methods. 4064 4065 // A decl coming from PCH was modified. 4066 assert(RD->isCompleteDefinition()); 4067 UpdateRecord &Record = DeclUpdates[RD]; 4068 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER); 4069 Record.push_back(reinterpret_cast<uint64_t>(D)); 4070} 4071 4072void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD, 4073 const ClassTemplateSpecializationDecl *D) { 4074 // The specializations set is kept in the canonical template. 4075 assert(!WritingAST && "Already writing the AST!"); 4076 TD = TD->getCanonicalDecl(); 4077 if (!(!D->isFromASTFile() && TD->isFromASTFile())) 4078 return; // Not a source specialization added to a template from PCH. 4079 4080 UpdateRecord &Record = DeclUpdates[TD]; 4081 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION); 4082 Record.push_back(reinterpret_cast<uint64_t>(D)); 4083} 4084 4085void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, 4086 const FunctionDecl *D) { 4087 // The specializations set is kept in the canonical template. 4088 assert(!WritingAST && "Already writing the AST!"); 4089 TD = TD->getCanonicalDecl(); 4090 if (!(!D->isFromASTFile() && TD->isFromASTFile())) 4091 return; // Not a source specialization added to a template from PCH. 4092 4093 UpdateRecord &Record = DeclUpdates[TD]; 4094 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION); 4095 Record.push_back(reinterpret_cast<uint64_t>(D)); 4096} 4097 4098void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) { 4099 assert(!WritingAST && "Already writing the AST!"); 4100 if (!D->isFromASTFile()) 4101 return; // Declaration not imported from PCH. 4102 4103 // Implicit decl from a PCH was defined. 4104 // FIXME: Should implicit definition be a separate FunctionDecl? 4105 RewriteDecl(D); 4106} 4107 4108void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) { 4109 assert(!WritingAST && "Already writing the AST!"); 4110 if (!D->isFromASTFile()) 4111 return; 4112 4113 // Since the actual instantiation is delayed, this really means that we need 4114 // to update the instantiation location. 4115 UpdateRecord &Record = DeclUpdates[D]; 4116 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER); 4117 AddSourceLocation( 4118 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record); 4119} 4120 4121void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, 4122 const ObjCInterfaceDecl *IFD) { 4123 assert(!WritingAST && "Already writing the AST!"); 4124 if (!IFD->isFromASTFile()) 4125 return; // Declaration not imported from PCH. 4126 if (CatD->getNextClassCategory() && 4127 !CatD->getNextClassCategory()->isFromASTFile()) 4128 return; // We already recorded that the tail of a category chain should be 4129 // attached to an interface. 4130 4131 ChainedObjCCategoriesData Data = { IFD, CatD, 0, 0 }; 4132 LocalChainedObjCCategories.push_back(Data); 4133} 4134