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