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