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