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