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