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(CHAINED_METADATA); 769 RECORD(REFERENCED_SELECTOR_POOL); 770 RECORD(TU_UPDATE_LEXICAL); 771 RECORD(REDECLS_UPDATE_LATEST); 772 RECORD(SEMA_DECL_REFS); 773 RECORD(WEAK_UNDECLARED_IDENTIFIERS); 774 RECORD(PENDING_IMPLICIT_INSTANTIATIONS); 775 RECORD(DECL_REPLACEMENTS); 776 RECORD(UPDATE_VISIBLE); 777 RECORD(DECL_UPDATE_OFFSETS); 778 RECORD(DECL_UPDATES); 779 RECORD(CXX_BASE_SPECIFIER_OFFSETS); 780 RECORD(DIAG_PRAGMA_MAPPINGS); 781 RECORD(CUDA_SPECIAL_DECL_REFS); 782 RECORD(HEADER_SEARCH_TABLE); 783 RECORD(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.Target; 954 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev(); 955 MetaAbbrev->Add(BitCodeAbbrevOp( 956 Chain ? CHAINED_METADATA : METADATA)); 957 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major 958 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor 959 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major 960 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor 961 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable 962 // Target triple or chained PCH name 963 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 964 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev); 965 966 RecordData Record; 967 Record.push_back(Chain ? CHAINED_METADATA : METADATA); 968 Record.push_back(VERSION_MAJOR); 969 Record.push_back(VERSION_MINOR); 970 Record.push_back(CLANG_VERSION_MAJOR); 971 Record.push_back(CLANG_VERSION_MINOR); 972 Record.push_back(!isysroot.empty()); 973 // FIXME: This writes the absolute path for chained headers. 974 const std::string &BlobStr = 975 Chain ? Chain->getFileName() : Target.getTriple().getTriple(); 976 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, BlobStr); 977 978 // Original file name and file ID 979 SourceManager &SM = Context.getSourceManager(); 980 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 981 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev(); 982 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME)); 983 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 984 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev); 985 986 llvm::SmallString<128> MainFilePath(MainFile->getName()); 987 988 llvm::sys::fs::make_absolute(MainFilePath); 989 990 const char *MainFileNameStr = MainFilePath.c_str(); 991 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr, 992 isysroot); 993 RecordData Record; 994 Record.push_back(ORIGINAL_FILE_NAME); 995 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr); 996 997 Record.clear(); 998 Record.push_back(SM.getMainFileID().getOpaqueValue()); 999 Stream.EmitRecord(ORIGINAL_FILE_ID, Record); 1000 } 1001 1002 // Original PCH directory 1003 if (!OutputFile.empty() && OutputFile != "-") { 1004 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1005 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR)); 1006 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1007 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev); 1008 1009 llvm::SmallString<128> OutputPath(OutputFile); 1010 1011 llvm::sys::fs::make_absolute(OutputPath); 1012 StringRef origDir = llvm::sys::path::parent_path(OutputPath); 1013 1014 RecordData Record; 1015 Record.push_back(ORIGINAL_PCH_DIR); 1016 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir); 1017 } 1018 1019 // Repository branch/version information. 1020 BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev(); 1021 RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION)); 1022 RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag 1023 unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev); 1024 Record.clear(); 1025 Record.push_back(VERSION_CONTROL_BRANCH_REVISION); 1026 Stream.EmitRecordWithBlob(RepoAbbrevCode, Record, 1027 getClangFullRepositoryVersion()); 1028 } 1029 1030 /// \brief Write the LangOptions structure. 1031 void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) { 1032 RecordData Record; 1033 Record.push_back(LangOpts.Trigraphs); 1034 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments. 1035 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers. 1036 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode. 1037 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc) 1038 Record.push_back(LangOpts.GNUKeywords); // Allow GNU-extension keywords 1039 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'. 1040 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++ 1041 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants. 1042 Record.push_back(LangOpts.C99); // C99 Support 1043 Record.push_back(LangOpts.C1X); // C1X Support 1044 Record.push_back(LangOpts.Microsoft); // Microsoft extensions. 1045 // LangOpts.MSCVersion is ignored because all it does it set a macro, which is 1046 // already saved elsewhere. 1047 Record.push_back(LangOpts.CPlusPlus); // C++ Support 1048 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support 1049 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords. 1050 1051 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled. 1052 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled. 1053 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C 1054 // modern abi enabled. 1055 Record.push_back(LangOpts.ObjCNonFragileABI2); // Objective-C enhanced 1056 // modern abi enabled. 1057 Record.push_back(LangOpts.AppleKext); // Apple's kernel extensions ABI 1058 Record.push_back(LangOpts.ObjCDefaultSynthProperties); // Objective-C auto-synthesized 1059 // properties enabled. 1060 Record.push_back(LangOpts.ObjCInferRelatedResultType); 1061 Record.push_back(LangOpts.NoConstantCFStrings); // non cfstring generation enabled.. 1062 1063 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings 1064 Record.push_back(LangOpts.WritableStrings); // Allow writable strings 1065 Record.push_back(LangOpts.LaxVectorConversions); 1066 Record.push_back(LangOpts.AltiVec); 1067 Record.push_back(LangOpts.Exceptions); // Support exception handling. 1068 Record.push_back(LangOpts.ObjCExceptions); 1069 Record.push_back(LangOpts.CXXExceptions); 1070 Record.push_back(LangOpts.SjLjExceptions); 1071 1072 Record.push_back(LangOpts.MSBitfields); // MS-compatible structure layout 1073 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime. 1074 Record.push_back(LangOpts.Freestanding); // Freestanding implementation 1075 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin) 1076 1077 // Whether static initializers are protected by locks. 1078 Record.push_back(LangOpts.ThreadsafeStatics); 1079 Record.push_back(LangOpts.POSIXThreads); 1080 Record.push_back(LangOpts.Blocks); // block extension to C 1081 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if 1082 // they are unused. 1083 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno 1084 // (modulo the platform support). 1085 1086 Record.push_back(LangOpts.getSignedOverflowBehavior()); 1087 Record.push_back(LangOpts.HeinousExtensions); 1088 1089 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined. 1090 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be 1091 // defined. 1092 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as 1093 // opposed to __DYNAMIC__). 1094 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero. 1095 1096 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be 1097 // used (instead of C99 semantics). 1098 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined. 1099 Record.push_back(LangOpts.Deprecated); // Should __DEPRECATED be defined. 1100 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should 1101 // be enabled. 1102 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or 1103 // unsigned type 1104 Record.push_back(LangOpts.ShortWChar); // force wchar_t to be unsigned short 1105 Record.push_back(LangOpts.ShortEnums); // Should the enum type be equivalent 1106 // to the smallest integer type with 1107 // enough room. 1108 Record.push_back(LangOpts.getGCMode()); 1109 Record.push_back(LangOpts.getVisibilityMode()); 1110 Record.push_back(LangOpts.getStackProtectorMode()); 1111 Record.push_back(LangOpts.InstantiationDepth); 1112 Record.push_back(LangOpts.OpenCL); 1113 Record.push_back(LangOpts.CUDA); 1114 Record.push_back(LangOpts.CatchUndefined); 1115 Record.push_back(LangOpts.DefaultFPContract); 1116 Record.push_back(LangOpts.ElideConstructors); 1117 Record.push_back(LangOpts.SpellChecking); 1118 Record.push_back(LangOpts.MRTD); 1119 Record.push_back(LangOpts.ObjCAutoRefCount); 1120 Record.push_back(LangOpts.ObjCInferRelatedReturnType); 1121 Stream.EmitRecord(LANGUAGE_OPTIONS, Record); 1122 } 1123 1124 //===----------------------------------------------------------------------===// 1125 // stat cache Serialization 1126 //===----------------------------------------------------------------------===// 1127 1128 namespace { 1129 // Trait used for the on-disk hash table of stat cache results. 1130 class ASTStatCacheTrait { 1131 public: 1132 typedef const char * key_type; 1133 typedef key_type key_type_ref; 1134 1135 typedef struct stat data_type; 1136 typedef const data_type &data_type_ref; 1137 1138 static unsigned ComputeHash(const char *path) { 1139 return llvm::HashString(path); 1140 } 1141 1142 std::pair<unsigned,unsigned> 1143 EmitKeyDataLength(raw_ostream& Out, const char *path, 1144 data_type_ref Data) { 1145 unsigned StrLen = strlen(path); 1146 clang::io::Emit16(Out, StrLen); 1147 unsigned DataLen = 4 + 4 + 2 + 8 + 8; 1148 clang::io::Emit8(Out, DataLen); 1149 return std::make_pair(StrLen + 1, DataLen); 1150 } 1151 1152 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) { 1153 Out.write(path, KeyLen); 1154 } 1155 1156 void EmitData(raw_ostream &Out, key_type_ref, 1157 data_type_ref Data, unsigned DataLen) { 1158 using namespace clang::io; 1159 uint64_t Start = Out.tell(); (void)Start; 1160 1161 Emit32(Out, (uint32_t) Data.st_ino); 1162 Emit32(Out, (uint32_t) Data.st_dev); 1163 Emit16(Out, (uint16_t) Data.st_mode); 1164 Emit64(Out, (uint64_t) Data.st_mtime); 1165 Emit64(Out, (uint64_t) Data.st_size); 1166 1167 assert(Out.tell() - Start == DataLen && "Wrong data length"); 1168 } 1169 }; 1170 } // end anonymous namespace 1171 1172 /// \brief Write the stat() system call cache to the AST file. 1173 void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) { 1174 // Build the on-disk hash table containing information about every 1175 // stat() call. 1176 OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator; 1177 unsigned NumStatEntries = 0; 1178 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(), 1179 StatEnd = StatCalls.end(); 1180 Stat != StatEnd; ++Stat, ++NumStatEntries) { 1181 StringRef Filename = Stat->first(); 1182 Generator.insert(Filename.data(), Stat->second); 1183 } 1184 1185 // Create the on-disk hash table in a buffer. 1186 llvm::SmallString<4096> StatCacheData; 1187 uint32_t BucketOffset; 1188 { 1189 llvm::raw_svector_ostream Out(StatCacheData); 1190 // Make sure that no bucket is at offset 0 1191 clang::io::Emit32(Out, 0); 1192 BucketOffset = Generator.Emit(Out); 1193 } 1194 1195 // Create a blob abbreviation 1196 using namespace llvm; 1197 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1198 Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE)); 1199 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1200 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1201 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1202 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev); 1203 1204 // Write the stat cache 1205 RecordData Record; 1206 Record.push_back(STAT_CACHE); 1207 Record.push_back(BucketOffset); 1208 Record.push_back(NumStatEntries); 1209 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str()); 1210 } 1211 1212 //===----------------------------------------------------------------------===// 1213 // Source Manager Serialization 1214 //===----------------------------------------------------------------------===// 1215 1216 /// \brief Create an abbreviation for the SLocEntry that refers to a 1217 /// file. 1218 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) { 1219 using namespace llvm; 1220 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1221 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY)); 1222 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1223 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1224 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 1225 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1226 // FileEntry fields. 1227 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size 1228 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time 1229 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1230 return Stream.EmitAbbrev(Abbrev); 1231 } 1232 1233 /// \brief Create an abbreviation for the SLocEntry that refers to a 1234 /// buffer. 1235 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) { 1236 using namespace llvm; 1237 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1238 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY)); 1239 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1240 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1241 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 1242 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1243 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob 1244 return Stream.EmitAbbrev(Abbrev); 1245 } 1246 1247 /// \brief Create an abbreviation for the SLocEntry that refers to a 1248 /// buffer's blob. 1249 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) { 1250 using namespace llvm; 1251 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1252 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB)); 1253 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob 1254 return Stream.EmitAbbrev(Abbrev); 1255 } 1256 1257 /// \brief Create an abbreviation for the SLocEntry that refers to a macro 1258 /// expansion. 1259 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) { 1260 using namespace llvm; 1261 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1262 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY)); 1263 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1264 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location 1265 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location 1266 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location 1267 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length 1268 return Stream.EmitAbbrev(Abbrev); 1269 } 1270 1271 namespace { 1272 // Trait used for the on-disk hash table of header search information. 1273 class HeaderFileInfoTrait { 1274 ASTWriter &Writer; 1275 HeaderSearch &HS; 1276 1277 // Keep track of the framework names we've used during serialization. 1278 SmallVector<char, 128> FrameworkStringData; 1279 llvm::StringMap<unsigned> FrameworkNameOffset; 1280 1281 public: 1282 HeaderFileInfoTrait(ASTWriter &Writer, HeaderSearch &HS) 1283 : Writer(Writer), HS(HS) { } 1284 1285 typedef const char *key_type; 1286 typedef key_type key_type_ref; 1287 1288 typedef HeaderFileInfo data_type; 1289 typedef const data_type &data_type_ref; 1290 1291 static unsigned ComputeHash(const char *path) { 1292 // The hash is based only on the filename portion of the key, so that the 1293 // reader can match based on filenames when symlinking or excess path 1294 // elements ("foo/../", "../") change the form of the name. However, 1295 // complete path is still the key. 1296 return llvm::HashString(llvm::sys::path::filename(path)); 1297 } 1298 1299 std::pair<unsigned,unsigned> 1300 EmitKeyDataLength(raw_ostream& Out, const char *path, 1301 data_type_ref Data) { 1302 unsigned StrLen = strlen(path); 1303 clang::io::Emit16(Out, StrLen); 1304 unsigned DataLen = 1 + 2 + 4 + 4; 1305 clang::io::Emit8(Out, DataLen); 1306 return std::make_pair(StrLen + 1, DataLen); 1307 } 1308 1309 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) { 1310 Out.write(path, KeyLen); 1311 } 1312 1313 void EmitData(raw_ostream &Out, key_type_ref, 1314 data_type_ref Data, unsigned DataLen) { 1315 using namespace clang::io; 1316 uint64_t Start = Out.tell(); (void)Start; 1317 1318 unsigned char Flags = (Data.isImport << 5) 1319 | (Data.isPragmaOnce << 4) 1320 | (Data.DirInfo << 2) 1321 | (Data.Resolved << 1) 1322 | Data.IndexHeaderMapHeader; 1323 Emit8(Out, (uint8_t)Flags); 1324 Emit16(Out, (uint16_t) Data.NumIncludes); 1325 1326 if (!Data.ControllingMacro) 1327 Emit32(Out, (uint32_t)Data.ControllingMacroID); 1328 else 1329 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro)); 1330 1331 unsigned Offset = 0; 1332 if (!Data.Framework.empty()) { 1333 // If this header refers into a framework, save the framework name. 1334 llvm::StringMap<unsigned>::iterator Pos 1335 = FrameworkNameOffset.find(Data.Framework); 1336 if (Pos == FrameworkNameOffset.end()) { 1337 Offset = FrameworkStringData.size() + 1; 1338 FrameworkStringData.append(Data.Framework.begin(), 1339 Data.Framework.end()); 1340 FrameworkStringData.push_back(0); 1341 1342 FrameworkNameOffset[Data.Framework] = Offset; 1343 } else 1344 Offset = Pos->second; 1345 } 1346 Emit32(Out, Offset); 1347 1348 assert(Out.tell() - Start == DataLen && "Wrong data length"); 1349 } 1350 1351 const char *strings_begin() const { return FrameworkStringData.begin(); } 1352 const char *strings_end() const { return FrameworkStringData.end(); } 1353 }; 1354 } // end anonymous namespace 1355 1356 /// \brief Write the header search block for the list of files that 1357 /// 1358 /// \param HS The header search structure to save. 1359 /// 1360 /// \param Chain Whether we're creating a chained AST file. 1361 void ASTWriter::WriteHeaderSearch(HeaderSearch &HS, StringRef isysroot) { 1362 SmallVector<const FileEntry *, 16> FilesByUID; 1363 HS.getFileMgr().GetUniqueIDMapping(FilesByUID); 1364 1365 if (FilesByUID.size() > HS.header_file_size()) 1366 FilesByUID.resize(HS.header_file_size()); 1367 1368 HeaderFileInfoTrait GeneratorTrait(*this, HS); 1369 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator; 1370 SmallVector<const char *, 4> SavedStrings; 1371 unsigned NumHeaderSearchEntries = 0; 1372 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) { 1373 const FileEntry *File = FilesByUID[UID]; 1374 if (!File) 1375 continue; 1376 1377 const HeaderFileInfo &HFI = HS.header_file_begin()[UID]; 1378 if (HFI.External && Chain) 1379 continue; 1380 1381 // Turn the file name into an absolute path, if it isn't already. 1382 const char *Filename = File->getName(); 1383 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1384 1385 // If we performed any translation on the file name at all, we need to 1386 // save this string, since the generator will refer to it later. 1387 if (Filename != File->getName()) { 1388 Filename = strdup(Filename); 1389 SavedStrings.push_back(Filename); 1390 } 1391 1392 Generator.insert(Filename, HFI, GeneratorTrait); 1393 ++NumHeaderSearchEntries; 1394 } 1395 1396 // Create the on-disk hash table in a buffer. 1397 llvm::SmallString<4096> TableData; 1398 uint32_t BucketOffset; 1399 { 1400 llvm::raw_svector_ostream Out(TableData); 1401 // Make sure that no bucket is at offset 0 1402 clang::io::Emit32(Out, 0); 1403 BucketOffset = Generator.Emit(Out, GeneratorTrait); 1404 } 1405 1406 // Create a blob abbreviation 1407 using namespace llvm; 1408 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1409 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE)); 1410 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1411 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1412 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1413 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1414 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev); 1415 1416 // Write the header search table 1417 RecordData Record; 1418 Record.push_back(HEADER_SEARCH_TABLE); 1419 Record.push_back(BucketOffset); 1420 Record.push_back(NumHeaderSearchEntries); 1421 Record.push_back(TableData.size()); 1422 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end()); 1423 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str()); 1424 1425 // Free all of the strings we had to duplicate. 1426 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I) 1427 free((void*)SavedStrings[I]); 1428 } 1429 1430 /// \brief Writes the block containing the serialized form of the 1431 /// source manager. 1432 /// 1433 /// TODO: We should probably use an on-disk hash table (stored in a 1434 /// blob), indexed based on the file name, so that we only create 1435 /// entries for files that we actually need. In the common case (no 1436 /// errors), we probably won't have to create file entries for any of 1437 /// the files in the AST. 1438 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, 1439 const Preprocessor &PP, 1440 StringRef isysroot) { 1441 RecordData Record; 1442 1443 // Enter the source manager block. 1444 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3); 1445 1446 // Abbreviations for the various kinds of source-location entries. 1447 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream); 1448 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream); 1449 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream); 1450 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream); 1451 1452 // Write out the source location entry table. We skip the first 1453 // entry, which is always the same dummy entry. 1454 std::vector<uint32_t> SLocEntryOffsets; 1455 // Write out the offsets of only source location file entries. 1456 // We will go through them in ASTReader::validateFileEntries(). 1457 std::vector<uint32_t> SLocFileEntryOffsets; 1458 RecordData PreloadSLocs; 1459 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1); 1460 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); 1461 I != N; ++I) { 1462 // Get this source location entry. 1463 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I); 1464 1465 // Record the offset of this source-location entry. 1466 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo()); 1467 1468 // Figure out which record code to use. 1469 unsigned Code; 1470 if (SLoc->isFile()) { 1471 if (SLoc->getFile().getContentCache()->OrigEntry) { 1472 Code = SM_SLOC_FILE_ENTRY; 1473 SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo()); 1474 } else 1475 Code = SM_SLOC_BUFFER_ENTRY; 1476 } else 1477 Code = SM_SLOC_EXPANSION_ENTRY; 1478 Record.clear(); 1479 Record.push_back(Code); 1480 1481 // Starting offset of this entry within this module, so skip the dummy. 1482 Record.push_back(SLoc->getOffset() - 2); 1483 if (SLoc->isFile()) { 1484 const SrcMgr::FileInfo &File = SLoc->getFile(); 1485 Record.push_back(File.getIncludeLoc().getRawEncoding()); 1486 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding 1487 Record.push_back(File.hasLineDirectives()); 1488 1489 const SrcMgr::ContentCache *Content = File.getContentCache(); 1490 if (Content->OrigEntry) { 1491 assert(Content->OrigEntry == Content->ContentsEntry && 1492 "Writing to AST an overriden file is not supported"); 1493 1494 // The source location entry is a file. The blob associated 1495 // with this entry is the file name. 1496 1497 // Emit size/modification time for this file. 1498 Record.push_back(Content->OrigEntry->getSize()); 1499 Record.push_back(Content->OrigEntry->getModificationTime()); 1500 1501 // Turn the file name into an absolute path, if it isn't already. 1502 const char *Filename = Content->OrigEntry->getName(); 1503 llvm::SmallString<128> FilePath(Filename); 1504 1505 // Ask the file manager to fixup the relative path for us. This will 1506 // honor the working directory. 1507 SourceMgr.getFileManager().FixupRelativePath(FilePath); 1508 1509 // FIXME: This call to make_absolute shouldn't be necessary, the 1510 // call to FixupRelativePath should always return an absolute path. 1511 llvm::sys::fs::make_absolute(FilePath); 1512 Filename = FilePath.c_str(); 1513 1514 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1515 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename); 1516 } else { 1517 // The source location entry is a buffer. The blob associated 1518 // with this entry contains the contents of the buffer. 1519 1520 // We add one to the size so that we capture the trailing NULL 1521 // that is required by llvm::MemoryBuffer::getMemBuffer (on 1522 // the reader side). 1523 const llvm::MemoryBuffer *Buffer 1524 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager()); 1525 const char *Name = Buffer->getBufferIdentifier(); 1526 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, 1527 StringRef(Name, strlen(Name) + 1)); 1528 Record.clear(); 1529 Record.push_back(SM_SLOC_BUFFER_BLOB); 1530 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, 1531 StringRef(Buffer->getBufferStart(), 1532 Buffer->getBufferSize() + 1)); 1533 1534 if (strcmp(Name, "<built-in>") == 0) { 1535 PreloadSLocs.push_back(SLocEntryOffsets.size()); 1536 } 1537 } 1538 } else { 1539 // The source location entry is a macro expansion. 1540 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion(); 1541 Record.push_back(Expansion.getSpellingLoc().getRawEncoding()); 1542 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding()); 1543 Record.push_back(Expansion.getExpansionLocEnd().getRawEncoding()); 1544 1545 // Compute the token length for this macro expansion. 1546 unsigned NextOffset = SourceMgr.getNextLocalOffset(); 1547 if (I + 1 != N) 1548 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset(); 1549 Record.push_back(NextOffset - SLoc->getOffset() - 1); 1550 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record); 1551 } 1552 } 1553 1554 Stream.ExitBlock(); 1555 1556 if (SLocEntryOffsets.empty()) 1557 return; 1558 1559 // Write the source-location offsets table into the AST block. This 1560 // table is used for lazily loading source-location information. 1561 using namespace llvm; 1562 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1563 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS)); 1564 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 1565 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size 1566 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 1567 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); 1568 1569 Record.clear(); 1570 Record.push_back(SOURCE_LOCATION_OFFSETS); 1571 Record.push_back(SLocEntryOffsets.size()); 1572 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy 1573 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets)); 1574 1575 Abbrev = new BitCodeAbbrev(); 1576 Abbrev->Add(BitCodeAbbrevOp(FILE_SOURCE_LOCATION_OFFSETS)); 1577 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 1578 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 1579 unsigned SLocFileOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); 1580 1581 Record.clear(); 1582 Record.push_back(FILE_SOURCE_LOCATION_OFFSETS); 1583 Record.push_back(SLocFileEntryOffsets.size()); 1584 Stream.EmitRecordWithBlob(SLocFileOffsetsAbbrev, Record, 1585 data(SLocFileEntryOffsets)); 1586 1587 // Write the source location entry preloads array, telling the AST 1588 // reader which source locations entries it should load eagerly. 1589 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs); 1590 1591 // Write the line table. It depends on remapping working, so it must come 1592 // after the source location offsets. 1593 if (SourceMgr.hasLineTable()) { 1594 LineTableInfo &LineTable = SourceMgr.getLineTable(); 1595 1596 Record.clear(); 1597 // Emit the file names 1598 Record.push_back(LineTable.getNumFilenames()); 1599 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) { 1600 // Emit the file name 1601 const char *Filename = LineTable.getFilename(I); 1602 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1603 unsigned FilenameLen = Filename? strlen(Filename) : 0; 1604 Record.push_back(FilenameLen); 1605 if (FilenameLen) 1606 Record.insert(Record.end(), Filename, Filename + FilenameLen); 1607 } 1608 1609 // Emit the line entries 1610 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end(); 1611 L != LEnd; ++L) { 1612 // Only emit entries for local files. 1613 if (L->first < 0) 1614 continue; 1615 1616 // Emit the file ID 1617 Record.push_back(L->first); 1618 1619 // Emit the line entries 1620 Record.push_back(L->second.size()); 1621 for (std::vector<LineEntry>::iterator LE = L->second.begin(), 1622 LEEnd = L->second.end(); 1623 LE != LEEnd; ++LE) { 1624 Record.push_back(LE->FileOffset); 1625 Record.push_back(LE->LineNo); 1626 Record.push_back(LE->FilenameID); 1627 Record.push_back((unsigned)LE->FileKind); 1628 Record.push_back(LE->IncludeOffset); 1629 } 1630 } 1631 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record); 1632 } 1633 } 1634 1635 //===----------------------------------------------------------------------===// 1636 // Preprocessor Serialization 1637 //===----------------------------------------------------------------------===// 1638 1639 static int compareMacroDefinitions(const void *XPtr, const void *YPtr) { 1640 const std::pair<const IdentifierInfo *, MacroInfo *> &X = 1641 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr; 1642 const std::pair<const IdentifierInfo *, MacroInfo *> &Y = 1643 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr; 1644 return X.first->getName().compare(Y.first->getName()); 1645 } 1646 1647 /// \brief Writes the block containing the serialized form of the 1648 /// preprocessor. 1649 /// 1650 void ASTWriter::WritePreprocessor(const Preprocessor &PP) { 1651 RecordData Record; 1652 1653 // If the preprocessor __COUNTER__ value has been bumped, remember it. 1654 if (PP.getCounterValue() != 0) { 1655 Record.push_back(PP.getCounterValue()); 1656 Stream.EmitRecord(PP_COUNTER_VALUE, Record); 1657 Record.clear(); 1658 } 1659 1660 // Enter the preprocessor block. 1661 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3); 1662 1663 // If the AST file contains __DATE__ or __TIME__ emit a warning about this. 1664 // FIXME: use diagnostics subsystem for localization etc. 1665 if (PP.SawDateOrTime()) 1666 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n"); 1667 1668 1669 // Loop over all the macro definitions that are live at the end of the file, 1670 // emitting each to the PP section. 1671 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 1672 1673 // Construct the list of macro definitions that need to be serialized. 1674 SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2> 1675 MacrosToEmit; 1676 llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen; 1677 for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0), 1678 E = PP.macro_end(Chain == 0); 1679 I != E; ++I) { 1680 MacroDefinitionsSeen.insert(I->first); 1681 MacrosToEmit.push_back(std::make_pair(I->first, I->second)); 1682 } 1683 1684 // Sort the set of macro definitions that need to be serialized by the 1685 // name of the macro, to provide a stable ordering. 1686 llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(), 1687 &compareMacroDefinitions); 1688 1689 // Resolve any identifiers that defined macros at the time they were 1690 // deserialized, adding them to the list of macros to emit (if appropriate). 1691 for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) { 1692 IdentifierInfo *Name 1693 = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]); 1694 if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name)) 1695 MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name))); 1696 } 1697 1698 for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) { 1699 const IdentifierInfo *Name = MacrosToEmit[I].first; 1700 MacroInfo *MI = MacrosToEmit[I].second; 1701 if (!MI) 1702 continue; 1703 1704 // Don't emit builtin macros like __LINE__ to the AST file unless they have 1705 // been redefined by the header (in which case they are not isBuiltinMacro). 1706 // Also skip macros from a AST file if we're chaining. 1707 1708 // FIXME: There is a (probably minor) optimization we could do here, if 1709 // the macro comes from the original PCH but the identifier comes from a 1710 // chained PCH, by storing the offset into the original PCH rather than 1711 // writing the macro definition a second time. 1712 if (MI->isBuiltinMacro() || 1713 (Chain && Name->isFromAST() && MI->isFromAST())) 1714 continue; 1715 1716 AddIdentifierRef(Name, Record); 1717 MacroOffsets[Name] = Stream.GetCurrentBitNo(); 1718 Record.push_back(MI->getDefinitionLoc().getRawEncoding()); 1719 Record.push_back(MI->isUsed()); 1720 1721 unsigned Code; 1722 if (MI->isObjectLike()) { 1723 Code = PP_MACRO_OBJECT_LIKE; 1724 } else { 1725 Code = PP_MACRO_FUNCTION_LIKE; 1726 1727 Record.push_back(MI->isC99Varargs()); 1728 Record.push_back(MI->isGNUVarargs()); 1729 Record.push_back(MI->getNumArgs()); 1730 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); 1731 I != E; ++I) 1732 AddIdentifierRef(*I, Record); 1733 } 1734 1735 // If we have a detailed preprocessing record, record the macro definition 1736 // ID that corresponds to this macro. 1737 if (PPRec) 1738 Record.push_back(getMacroDefinitionID(PPRec->findMacroDefinition(MI))); 1739 1740 Stream.EmitRecord(Code, Record); 1741 Record.clear(); 1742 1743 // Emit the tokens array. 1744 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) { 1745 // Note that we know that the preprocessor does not have any annotation 1746 // tokens in it because they are created by the parser, and thus can't be 1747 // in a macro definition. 1748 const Token &Tok = MI->getReplacementToken(TokNo); 1749 1750 Record.push_back(Tok.getLocation().getRawEncoding()); 1751 Record.push_back(Tok.getLength()); 1752 1753 // FIXME: When reading literal tokens, reconstruct the literal pointer if 1754 // it is needed. 1755 AddIdentifierRef(Tok.getIdentifierInfo(), Record); 1756 // FIXME: Should translate token kind to a stable encoding. 1757 Record.push_back(Tok.getKind()); 1758 // FIXME: Should translate token flags to a stable encoding. 1759 Record.push_back(Tok.getFlags()); 1760 1761 Stream.EmitRecord(PP_TOKEN, Record); 1762 Record.clear(); 1763 } 1764 ++NumMacros; 1765 } 1766 Stream.ExitBlock(); 1767 1768 if (PPRec) 1769 WritePreprocessorDetail(*PPRec); 1770 } 1771 1772 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) { 1773 if (PPRec.begin(Chain) == PPRec.end(Chain)) 1774 return; 1775 1776 // Enter the preprocessor block. 1777 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3); 1778 1779 // If the preprocessor has a preprocessing record, emit it. 1780 unsigned NumPreprocessingRecords = 0; 1781 using namespace llvm; 1782 1783 // Set up the abbreviation for 1784 unsigned InclusionAbbrev = 0; 1785 { 1786 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1787 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE)); 1788 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index 1789 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // start location 1790 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // end location 1791 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length 1792 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes 1793 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind 1794 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1795 InclusionAbbrev = Stream.EmitAbbrev(Abbrev); 1796 } 1797 1798 unsigned FirstPreprocessorEntityID 1799 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0) 1800 + NUM_PREDEF_PP_ENTITY_IDS; 1801 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID; 1802 RecordData Record; 1803 uint64_t BitsInChain = Chain? Chain->TotalModulesSizeInBits : 0; 1804 for (PreprocessingRecord::iterator E = PPRec.begin(Chain), 1805 EEnd = PPRec.end(Chain); 1806 E != EEnd; 1807 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) { 1808 Record.clear(); 1809 1810 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) { 1811 // Record this macro definition's location. 1812 MacroID ID = getMacroDefinitionID(MD); 1813 1814 // Don't write the macro definition if it is from another AST file. 1815 if (ID < FirstMacroID) 1816 continue; 1817 1818 // Notify the serialization listener that we're serializing this entity. 1819 if (SerializationListener) 1820 SerializationListener->SerializedPreprocessedEntity(*E, 1821 BitsInChain + Stream.GetCurrentBitNo()); 1822 1823 unsigned Position = ID - FirstMacroID; 1824 if (Position != MacroDefinitionOffsets.size()) { 1825 if (Position > MacroDefinitionOffsets.size()) 1826 MacroDefinitionOffsets.resize(Position + 1); 1827 1828 MacroDefinitionOffsets[Position] = Stream.GetCurrentBitNo(); 1829 } else 1830 MacroDefinitionOffsets.push_back(Stream.GetCurrentBitNo()); 1831 1832 Record.push_back(NextPreprocessorEntityID); 1833 Record.push_back(ID); 1834 AddSourceLocation(MD->getSourceRange().getBegin(), Record); 1835 AddSourceLocation(MD->getSourceRange().getEnd(), Record); 1836 AddIdentifierRef(MD->getName(), Record); 1837 AddSourceLocation(MD->getLocation(), Record); 1838 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record); 1839 continue; 1840 } 1841 1842 // Notify the serialization listener that we're serializing this entity. 1843 if (SerializationListener) 1844 SerializationListener->SerializedPreprocessedEntity(*E, 1845 BitsInChain + Stream.GetCurrentBitNo()); 1846 1847 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) { 1848 Record.push_back(NextPreprocessorEntityID); 1849 AddSourceLocation(ME->getSourceRange().getBegin(), Record); 1850 AddSourceLocation(ME->getSourceRange().getEnd(), Record); 1851 AddIdentifierRef(ME->getName(), Record); 1852 Record.push_back(getMacroDefinitionID(ME->getDefinition())); 1853 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record); 1854 continue; 1855 } 1856 1857 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) { 1858 Record.push_back(PPD_INCLUSION_DIRECTIVE); 1859 Record.push_back(NextPreprocessorEntityID); 1860 AddSourceLocation(ID->getSourceRange().getBegin(), Record); 1861 AddSourceLocation(ID->getSourceRange().getEnd(), Record); 1862 Record.push_back(ID->getFileName().size()); 1863 Record.push_back(ID->wasInQuotes()); 1864 Record.push_back(static_cast<unsigned>(ID->getKind())); 1865 llvm::SmallString<64> Buffer; 1866 Buffer += ID->getFileName(); 1867 Buffer += ID->getFile()->getName(); 1868 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer); 1869 continue; 1870 } 1871 1872 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter"); 1873 } 1874 Stream.ExitBlock(); 1875 1876 // Write the offsets table for the preprocessing record. 1877 if (NumPreprocessingRecords > 0) { 1878 // Write the offsets table for identifier IDs. 1879 using namespace llvm; 1880 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1881 Abbrev->Add(BitCodeAbbrevOp(MACRO_DEFINITION_OFFSETS)); 1882 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of records 1883 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity 1884 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macro defs 1885 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first macro def 1886 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1887 unsigned MacroDefOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1888 1889 Record.clear(); 1890 Record.push_back(MACRO_DEFINITION_OFFSETS); 1891 Record.push_back(NumPreprocessingRecords); 1892 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS); 1893 Record.push_back(MacroDefinitionOffsets.size()); 1894 Record.push_back(FirstMacroID - NUM_PREDEF_MACRO_IDS); 1895 Stream.EmitRecordWithBlob(MacroDefOffsetAbbrev, Record, 1896 data(MacroDefinitionOffsets)); 1897 } 1898 } 1899 1900 void ASTWriter::WritePragmaDiagnosticMappings(const Diagnostic &Diag) { 1901 RecordData Record; 1902 for (Diagnostic::DiagStatePointsTy::const_iterator 1903 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end(); 1904 I != E; ++I) { 1905 const Diagnostic::DiagStatePoint &point = *I; 1906 if (point.Loc.isInvalid()) 1907 continue; 1908 1909 Record.push_back(point.Loc.getRawEncoding()); 1910 for (Diagnostic::DiagState::iterator 1911 I = point.State->begin(), E = point.State->end(); I != E; ++I) { 1912 unsigned diag = I->first, map = I->second; 1913 if (map & 0x10) { // mapping from a diagnostic pragma. 1914 Record.push_back(diag); 1915 Record.push_back(map & 0x7); 1916 } 1917 } 1918 Record.push_back(-1); // mark the end of the diag/map pairs for this 1919 // location. 1920 } 1921 1922 if (!Record.empty()) 1923 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record); 1924 } 1925 1926 void ASTWriter::WriteCXXBaseSpecifiersOffsets() { 1927 if (CXXBaseSpecifiersOffsets.empty()) 1928 return; 1929 1930 RecordData Record; 1931 1932 // Create a blob abbreviation for the C++ base specifiers offsets. 1933 using namespace llvm; 1934 1935 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1936 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS)); 1937 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 1938 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1939 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1940 1941 // Write the base specifier offsets table. 1942 Record.clear(); 1943 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS); 1944 Record.push_back(CXXBaseSpecifiersOffsets.size()); 1945 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record, 1946 data(CXXBaseSpecifiersOffsets)); 1947 } 1948 1949 //===----------------------------------------------------------------------===// 1950 // Type Serialization 1951 //===----------------------------------------------------------------------===// 1952 1953 /// \brief Write the representation of a type to the AST stream. 1954 void ASTWriter::WriteType(QualType T) { 1955 TypeIdx &Idx = TypeIdxs[T]; 1956 if (Idx.getIndex() == 0) // we haven't seen this type before. 1957 Idx = TypeIdx(NextTypeID++); 1958 1959 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST"); 1960 1961 // Record the offset for this type. 1962 unsigned Index = Idx.getIndex() - FirstTypeID; 1963 if (TypeOffsets.size() == Index) 1964 TypeOffsets.push_back(Stream.GetCurrentBitNo()); 1965 else if (TypeOffsets.size() < Index) { 1966 TypeOffsets.resize(Index + 1); 1967 TypeOffsets[Index] = Stream.GetCurrentBitNo(); 1968 } 1969 1970 RecordData Record; 1971 1972 // Emit the type's representation. 1973 ASTTypeWriter W(*this, Record); 1974 1975 if (T.hasLocalNonFastQualifiers()) { 1976 Qualifiers Qs = T.getLocalQualifiers(); 1977 AddTypeRef(T.getLocalUnqualifiedType(), Record); 1978 Record.push_back(Qs.getAsOpaqueValue()); 1979 W.Code = TYPE_EXT_QUAL; 1980 } else { 1981 switch (T->getTypeClass()) { 1982 // For all of the concrete, non-dependent types, call the 1983 // appropriate visitor function. 1984 #define TYPE(Class, Base) \ 1985 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break; 1986 #define ABSTRACT_TYPE(Class, Base) 1987 #include "clang/AST/TypeNodes.def" 1988 } 1989 } 1990 1991 // Emit the serialized record. 1992 Stream.EmitRecord(W.Code, Record); 1993 1994 // Flush any expressions that were written as part of this type. 1995 FlushStmts(); 1996 } 1997 1998 //===----------------------------------------------------------------------===// 1999 // Declaration Serialization 2000 //===----------------------------------------------------------------------===// 2001 2002 /// \brief Write the block containing all of the declaration IDs 2003 /// lexically declared within the given DeclContext. 2004 /// 2005 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the 2006 /// bistream, or 0 if no block was written. 2007 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context, 2008 DeclContext *DC) { 2009 if (DC->decls_empty()) 2010 return 0; 2011 2012 uint64_t Offset = Stream.GetCurrentBitNo(); 2013 RecordData Record; 2014 Record.push_back(DECL_CONTEXT_LEXICAL); 2015 SmallVector<KindDeclIDPair, 64> Decls; 2016 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end(); 2017 D != DEnd; ++D) 2018 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D))); 2019 2020 ++NumLexicalDeclContexts; 2021 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls)); 2022 return Offset; 2023 } 2024 2025 void ASTWriter::WriteTypeDeclOffsets() { 2026 using namespace llvm; 2027 RecordData Record; 2028 2029 // Write the type offsets array 2030 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2031 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET)); 2032 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types 2033 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index 2034 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block 2035 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2036 Record.clear(); 2037 Record.push_back(TYPE_OFFSET); 2038 Record.push_back(TypeOffsets.size()); 2039 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS); 2040 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets)); 2041 2042 // Write the declaration offsets array 2043 Abbrev = new BitCodeAbbrev(); 2044 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET)); 2045 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations 2046 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID 2047 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block 2048 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2049 Record.clear(); 2050 Record.push_back(DECL_OFFSET); 2051 Record.push_back(DeclOffsets.size()); 2052 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS); 2053 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets)); 2054 } 2055 2056 //===----------------------------------------------------------------------===// 2057 // Global Method Pool and Selector Serialization 2058 //===----------------------------------------------------------------------===// 2059 2060 namespace { 2061 // Trait used for the on-disk hash table used in the method pool. 2062 class ASTMethodPoolTrait { 2063 ASTWriter &Writer; 2064 2065 public: 2066 typedef Selector key_type; 2067 typedef key_type key_type_ref; 2068 2069 struct data_type { 2070 SelectorID ID; 2071 ObjCMethodList Instance, Factory; 2072 }; 2073 typedef const data_type& data_type_ref; 2074 2075 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { } 2076 2077 static unsigned ComputeHash(Selector Sel) { 2078 return serialization::ComputeHash(Sel); 2079 } 2080 2081 std::pair<unsigned,unsigned> 2082 EmitKeyDataLength(raw_ostream& Out, Selector Sel, 2083 data_type_ref Methods) { 2084 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4); 2085 clang::io::Emit16(Out, KeyLen); 2086 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts 2087 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2088 Method = Method->Next) 2089 if (Method->Method) 2090 DataLen += 4; 2091 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2092 Method = Method->Next) 2093 if (Method->Method) 2094 DataLen += 4; 2095 clang::io::Emit16(Out, DataLen); 2096 return std::make_pair(KeyLen, DataLen); 2097 } 2098 2099 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) { 2100 uint64_t Start = Out.tell(); 2101 assert((Start >> 32) == 0 && "Selector key offset too large"); 2102 Writer.SetSelectorOffset(Sel, Start); 2103 unsigned N = Sel.getNumArgs(); 2104 clang::io::Emit16(Out, N); 2105 if (N == 0) 2106 N = 1; 2107 for (unsigned I = 0; I != N; ++I) 2108 clang::io::Emit32(Out, 2109 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I))); 2110 } 2111 2112 void EmitData(raw_ostream& Out, key_type_ref, 2113 data_type_ref Methods, unsigned DataLen) { 2114 uint64_t Start = Out.tell(); (void)Start; 2115 clang::io::Emit32(Out, Methods.ID); 2116 unsigned NumInstanceMethods = 0; 2117 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2118 Method = Method->Next) 2119 if (Method->Method) 2120 ++NumInstanceMethods; 2121 2122 unsigned NumFactoryMethods = 0; 2123 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2124 Method = Method->Next) 2125 if (Method->Method) 2126 ++NumFactoryMethods; 2127 2128 clang::io::Emit16(Out, NumInstanceMethods); 2129 clang::io::Emit16(Out, NumFactoryMethods); 2130 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2131 Method = Method->Next) 2132 if (Method->Method) 2133 clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); 2134 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2135 Method = Method->Next) 2136 if (Method->Method) 2137 clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); 2138 2139 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 2140 } 2141 }; 2142 } // end anonymous namespace 2143 2144 /// \brief Write ObjC data: selectors and the method pool. 2145 /// 2146 /// The method pool contains both instance and factory methods, stored 2147 /// in an on-disk hash table indexed by the selector. The hash table also 2148 /// contains an empty entry for every other selector known to Sema. 2149 void ASTWriter::WriteSelectors(Sema &SemaRef) { 2150 using namespace llvm; 2151 2152 // Do we have to do anything at all? 2153 if (SemaRef.MethodPool.empty() && SelectorIDs.empty()) 2154 return; 2155 unsigned NumTableEntries = 0; 2156 // Create and write out the blob that contains selectors and the method pool. 2157 { 2158 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator; 2159 ASTMethodPoolTrait Trait(*this); 2160 2161 // Create the on-disk hash table representation. We walk through every 2162 // selector we've seen and look it up in the method pool. 2163 SelectorOffsets.resize(NextSelectorID - FirstSelectorID); 2164 for (llvm::DenseMap<Selector, SelectorID>::iterator 2165 I = SelectorIDs.begin(), E = SelectorIDs.end(); 2166 I != E; ++I) { 2167 Selector S = I->first; 2168 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S); 2169 ASTMethodPoolTrait::data_type Data = { 2170 I->second, 2171 ObjCMethodList(), 2172 ObjCMethodList() 2173 }; 2174 if (F != SemaRef.MethodPool.end()) { 2175 Data.Instance = F->second.first; 2176 Data.Factory = F->second.second; 2177 } 2178 // Only write this selector if it's not in an existing AST or something 2179 // changed. 2180 if (Chain && I->second < FirstSelectorID) { 2181 // Selector already exists. Did it change? 2182 bool changed = false; 2183 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method; 2184 M = M->Next) { 2185 if (M->Method->getPCHLevel() == 0) 2186 changed = true; 2187 } 2188 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method; 2189 M = M->Next) { 2190 if (M->Method->getPCHLevel() == 0) 2191 changed = true; 2192 } 2193 if (!changed) 2194 continue; 2195 } else if (Data.Instance.Method || Data.Factory.Method) { 2196 // A new method pool entry. 2197 ++NumTableEntries; 2198 } 2199 Generator.insert(S, Data, Trait); 2200 } 2201 2202 // Create the on-disk hash table in a buffer. 2203 llvm::SmallString<4096> MethodPool; 2204 uint32_t BucketOffset; 2205 { 2206 ASTMethodPoolTrait Trait(*this); 2207 llvm::raw_svector_ostream Out(MethodPool); 2208 // Make sure that no bucket is at offset 0 2209 clang::io::Emit32(Out, 0); 2210 BucketOffset = Generator.Emit(Out, Trait); 2211 } 2212 2213 // Create a blob abbreviation 2214 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2215 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL)); 2216 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2217 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2218 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2219 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev); 2220 2221 // Write the method pool 2222 RecordData Record; 2223 Record.push_back(METHOD_POOL); 2224 Record.push_back(BucketOffset); 2225 Record.push_back(NumTableEntries); 2226 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str()); 2227 2228 // Create a blob abbreviation for the selector table offsets. 2229 Abbrev = new BitCodeAbbrev(); 2230 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS)); 2231 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 2232 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 2233 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2234 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2235 2236 // Write the selector offsets table. 2237 Record.clear(); 2238 Record.push_back(SELECTOR_OFFSETS); 2239 Record.push_back(SelectorOffsets.size()); 2240 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS); 2241 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record, 2242 data(SelectorOffsets)); 2243 } 2244 } 2245 2246 /// \brief Write the selectors referenced in @selector expression into AST file. 2247 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) { 2248 using namespace llvm; 2249 if (SemaRef.ReferencedSelectors.empty()) 2250 return; 2251 2252 RecordData Record; 2253 2254 // Note: this writes out all references even for a dependent AST. But it is 2255 // very tricky to fix, and given that @selector shouldn't really appear in 2256 // headers, probably not worth it. It's not a correctness issue. 2257 for (DenseMap<Selector, SourceLocation>::iterator S = 2258 SemaRef.ReferencedSelectors.begin(), 2259 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) { 2260 Selector Sel = (*S).first; 2261 SourceLocation Loc = (*S).second; 2262 AddSelectorRef(Sel, Record); 2263 AddSourceLocation(Loc, Record); 2264 } 2265 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record); 2266 } 2267 2268 //===----------------------------------------------------------------------===// 2269 // Identifier Table Serialization 2270 //===----------------------------------------------------------------------===// 2271 2272 namespace { 2273 class ASTIdentifierTableTrait { 2274 ASTWriter &Writer; 2275 Preprocessor &PP; 2276 2277 /// \brief Determines whether this is an "interesting" identifier 2278 /// that needs a full IdentifierInfo structure written into the hash 2279 /// table. 2280 static bool isInterestingIdentifier(const IdentifierInfo *II) { 2281 return II->isPoisoned() || 2282 II->isExtensionToken() || 2283 II->hasMacroDefinition() || 2284 II->getObjCOrBuiltinID() || 2285 II->getFETokenInfo<void>(); 2286 } 2287 2288 public: 2289 typedef const IdentifierInfo* key_type; 2290 typedef key_type key_type_ref; 2291 2292 typedef IdentID data_type; 2293 typedef data_type data_type_ref; 2294 2295 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP) 2296 : Writer(Writer), PP(PP) { } 2297 2298 static unsigned ComputeHash(const IdentifierInfo* II) { 2299 return llvm::HashString(II->getName()); 2300 } 2301 2302 std::pair<unsigned,unsigned> 2303 EmitKeyDataLength(raw_ostream& Out, const IdentifierInfo* II, 2304 IdentID ID) { 2305 unsigned KeyLen = II->getLength() + 1; 2306 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1 2307 if (isInterestingIdentifier(II)) { 2308 DataLen += 2; // 2 bytes for builtin ID, flags 2309 if (II->hasMacroDefinition() && 2310 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro()) 2311 DataLen += 4; 2312 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II), 2313 DEnd = IdentifierResolver::end(); 2314 D != DEnd; ++D) 2315 DataLen += sizeof(DeclID); 2316 } 2317 clang::io::Emit16(Out, DataLen); 2318 // We emit the key length after the data length so that every 2319 // string is preceded by a 16-bit length. This matches the PTH 2320 // format for storing identifiers. 2321 clang::io::Emit16(Out, KeyLen); 2322 return std::make_pair(KeyLen, DataLen); 2323 } 2324 2325 void EmitKey(raw_ostream& Out, const IdentifierInfo* II, 2326 unsigned KeyLen) { 2327 // Record the location of the key data. This is used when generating 2328 // the mapping from persistent IDs to strings. 2329 Writer.SetIdentifierOffset(II, Out.tell()); 2330 Out.write(II->getNameStart(), KeyLen); 2331 } 2332 2333 void EmitData(raw_ostream& Out, const IdentifierInfo* II, 2334 IdentID ID, unsigned) { 2335 if (!isInterestingIdentifier(II)) { 2336 clang::io::Emit32(Out, ID << 1); 2337 return; 2338 } 2339 2340 clang::io::Emit32(Out, (ID << 1) | 0x01); 2341 uint32_t Bits = 0; 2342 bool hasMacroDefinition = 2343 II->hasMacroDefinition() && 2344 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro(); 2345 Bits = (uint32_t)II->getObjCOrBuiltinID(); 2346 Bits = (Bits << 1) | unsigned(hasMacroDefinition); 2347 Bits = (Bits << 1) | unsigned(II->isExtensionToken()); 2348 Bits = (Bits << 1) | unsigned(II->isPoisoned()); 2349 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier()); 2350 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword()); 2351 clang::io::Emit16(Out, Bits); 2352 2353 if (hasMacroDefinition) 2354 clang::io::Emit32(Out, Writer.getMacroOffset(II)); 2355 2356 // Emit the declaration IDs in reverse order, because the 2357 // IdentifierResolver provides the declarations as they would be 2358 // visible (e.g., the function "stat" would come before the struct 2359 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain() 2360 // adds declarations to the end of the list (so we need to see the 2361 // struct "status" before the function "status"). 2362 // Only emit declarations that aren't from a chained PCH, though. 2363 SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II), 2364 IdentifierResolver::end()); 2365 for (SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(), 2366 DEnd = Decls.rend(); 2367 D != DEnd; ++D) 2368 clang::io::Emit32(Out, Writer.getDeclID(*D)); 2369 } 2370 }; 2371 } // end anonymous namespace 2372 2373 /// \brief Write the identifier table into the AST file. 2374 /// 2375 /// The identifier table consists of a blob containing string data 2376 /// (the actual identifiers themselves) and a separate "offsets" index 2377 /// that maps identifier IDs to locations within the blob. 2378 void ASTWriter::WriteIdentifierTable(Preprocessor &PP) { 2379 using namespace llvm; 2380 2381 // Create and write out the blob that contains the identifier 2382 // strings. 2383 { 2384 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator; 2385 ASTIdentifierTableTrait Trait(*this, PP); 2386 2387 // Look for any identifiers that were named while processing the 2388 // headers, but are otherwise not needed. We add these to the hash 2389 // table to enable checking of the predefines buffer in the case 2390 // where the user adds new macro definitions when building the AST 2391 // file. 2392 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 2393 IDEnd = PP.getIdentifierTable().end(); 2394 ID != IDEnd; ++ID) 2395 getIdentifierRef(ID->second); 2396 2397 // Create the on-disk hash table representation. We only store offsets 2398 // for identifiers that appear here for the first time. 2399 IdentifierOffsets.resize(NextIdentID - FirstIdentID); 2400 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator 2401 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end(); 2402 ID != IDEnd; ++ID) { 2403 assert(ID->first && "NULL identifier in identifier table"); 2404 if (!Chain || !ID->first->isFromAST()) 2405 Generator.insert(ID->first, ID->second, Trait); 2406 } 2407 2408 // Create the on-disk hash table in a buffer. 2409 llvm::SmallString<4096> IdentifierTable; 2410 uint32_t BucketOffset; 2411 { 2412 ASTIdentifierTableTrait Trait(*this, PP); 2413 llvm::raw_svector_ostream Out(IdentifierTable); 2414 // Make sure that no bucket is at offset 0 2415 clang::io::Emit32(Out, 0); 2416 BucketOffset = Generator.Emit(Out, Trait); 2417 } 2418 2419 // Create a blob abbreviation 2420 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2421 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE)); 2422 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2423 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2424 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev); 2425 2426 // Write the identifier table 2427 RecordData Record; 2428 Record.push_back(IDENTIFIER_TABLE); 2429 Record.push_back(BucketOffset); 2430 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str()); 2431 } 2432 2433 // Write the offsets table for identifier IDs. 2434 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2435 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET)); 2436 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers 2437 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 2438 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2439 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2440 2441 RecordData Record; 2442 Record.push_back(IDENTIFIER_OFFSET); 2443 Record.push_back(IdentifierOffsets.size()); 2444 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS); 2445 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record, 2446 data(IdentifierOffsets)); 2447 } 2448 2449 //===----------------------------------------------------------------------===// 2450 // DeclContext's Name Lookup Table Serialization 2451 //===----------------------------------------------------------------------===// 2452 2453 namespace { 2454 // Trait used for the on-disk hash table used in the method pool. 2455 class ASTDeclContextNameLookupTrait { 2456 ASTWriter &Writer; 2457 2458 public: 2459 typedef DeclarationName key_type; 2460 typedef key_type key_type_ref; 2461 2462 typedef DeclContext::lookup_result data_type; 2463 typedef const data_type& data_type_ref; 2464 2465 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { } 2466 2467 unsigned ComputeHash(DeclarationName Name) { 2468 llvm::FoldingSetNodeID ID; 2469 ID.AddInteger(Name.getNameKind()); 2470 2471 switch (Name.getNameKind()) { 2472 case DeclarationName::Identifier: 2473 ID.AddString(Name.getAsIdentifierInfo()->getName()); 2474 break; 2475 case DeclarationName::ObjCZeroArgSelector: 2476 case DeclarationName::ObjCOneArgSelector: 2477 case DeclarationName::ObjCMultiArgSelector: 2478 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector())); 2479 break; 2480 case DeclarationName::CXXConstructorName: 2481 case DeclarationName::CXXDestructorName: 2482 case DeclarationName::CXXConversionFunctionName: 2483 break; 2484 case DeclarationName::CXXOperatorName: 2485 ID.AddInteger(Name.getCXXOverloadedOperator()); 2486 break; 2487 case DeclarationName::CXXLiteralOperatorName: 2488 ID.AddString(Name.getCXXLiteralIdentifier()->getName()); 2489 case DeclarationName::CXXUsingDirective: 2490 break; 2491 } 2492 2493 return ID.ComputeHash(); 2494 } 2495 2496 std::pair<unsigned,unsigned> 2497 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name, 2498 data_type_ref Lookup) { 2499 unsigned KeyLen = 1; 2500 switch (Name.getNameKind()) { 2501 case DeclarationName::Identifier: 2502 case DeclarationName::ObjCZeroArgSelector: 2503 case DeclarationName::ObjCOneArgSelector: 2504 case DeclarationName::ObjCMultiArgSelector: 2505 case DeclarationName::CXXLiteralOperatorName: 2506 KeyLen += 4; 2507 break; 2508 case DeclarationName::CXXOperatorName: 2509 KeyLen += 1; 2510 break; 2511 case DeclarationName::CXXConstructorName: 2512 case DeclarationName::CXXDestructorName: 2513 case DeclarationName::CXXConversionFunctionName: 2514 case DeclarationName::CXXUsingDirective: 2515 break; 2516 } 2517 clang::io::Emit16(Out, KeyLen); 2518 2519 // 2 bytes for num of decls and 4 for each DeclID. 2520 unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first); 2521 clang::io::Emit16(Out, DataLen); 2522 2523 return std::make_pair(KeyLen, DataLen); 2524 } 2525 2526 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) { 2527 using namespace clang::io; 2528 2529 assert(Name.getNameKind() < 0x100 && "Invalid name kind ?"); 2530 Emit8(Out, Name.getNameKind()); 2531 switch (Name.getNameKind()) { 2532 case DeclarationName::Identifier: 2533 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo())); 2534 break; 2535 case DeclarationName::ObjCZeroArgSelector: 2536 case DeclarationName::ObjCOneArgSelector: 2537 case DeclarationName::ObjCMultiArgSelector: 2538 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector())); 2539 break; 2540 case DeclarationName::CXXOperatorName: 2541 assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?"); 2542 Emit8(Out, Name.getCXXOverloadedOperator()); 2543 break; 2544 case DeclarationName::CXXLiteralOperatorName: 2545 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier())); 2546 break; 2547 case DeclarationName::CXXConstructorName: 2548 case DeclarationName::CXXDestructorName: 2549 case DeclarationName::CXXConversionFunctionName: 2550 case DeclarationName::CXXUsingDirective: 2551 break; 2552 } 2553 } 2554 2555 void EmitData(raw_ostream& Out, key_type_ref, 2556 data_type Lookup, unsigned DataLen) { 2557 uint64_t Start = Out.tell(); (void)Start; 2558 clang::io::Emit16(Out, Lookup.second - Lookup.first); 2559 for (; Lookup.first != Lookup.second; ++Lookup.first) 2560 clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first)); 2561 2562 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 2563 } 2564 }; 2565 } // end anonymous namespace 2566 2567 /// \brief Write the block containing all of the declaration IDs 2568 /// visible from the given DeclContext. 2569 /// 2570 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the 2571 /// bitstream, or 0 if no block was written. 2572 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context, 2573 DeclContext *DC) { 2574 if (DC->getPrimaryContext() != DC) 2575 return 0; 2576 2577 // Since there is no name lookup into functions or methods, don't bother to 2578 // build a visible-declarations table for these entities. 2579 if (DC->isFunctionOrMethod()) 2580 return 0; 2581 2582 // If not in C++, we perform name lookup for the translation unit via the 2583 // IdentifierInfo chains, don't bother to build a visible-declarations table. 2584 // FIXME: In C++ we need the visible declarations in order to "see" the 2585 // friend declarations, is there a way to do this without writing the table ? 2586 if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus) 2587 return 0; 2588 2589 // Force the DeclContext to build a its name-lookup table. 2590 if (DC->hasExternalVisibleStorage()) 2591 DC->MaterializeVisibleDeclsFromExternalStorage(); 2592 else 2593 DC->lookup(DeclarationName()); 2594 2595 // Serialize the contents of the mapping used for lookup. Note that, 2596 // although we have two very different code paths, the serialized 2597 // representation is the same for both cases: a declaration name, 2598 // followed by a size, followed by references to the visible 2599 // declarations that have that name. 2600 uint64_t Offset = Stream.GetCurrentBitNo(); 2601 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr()); 2602 if (!Map || Map->empty()) 2603 return 0; 2604 2605 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator; 2606 ASTDeclContextNameLookupTrait Trait(*this); 2607 2608 // Create the on-disk hash table representation. 2609 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); 2610 D != DEnd; ++D) { 2611 DeclarationName Name = D->first; 2612 DeclContext::lookup_result Result = D->second.getLookupResult(); 2613 Generator.insert(Name, Result, Trait); 2614 } 2615 2616 // Create the on-disk hash table in a buffer. 2617 llvm::SmallString<4096> LookupTable; 2618 uint32_t BucketOffset; 2619 { 2620 llvm::raw_svector_ostream Out(LookupTable); 2621 // Make sure that no bucket is at offset 0 2622 clang::io::Emit32(Out, 0); 2623 BucketOffset = Generator.Emit(Out, Trait); 2624 } 2625 2626 // Write the lookup table 2627 RecordData Record; 2628 Record.push_back(DECL_CONTEXT_VISIBLE); 2629 Record.push_back(BucketOffset); 2630 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record, 2631 LookupTable.str()); 2632 2633 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record); 2634 ++NumVisibleDeclContexts; 2635 return Offset; 2636 } 2637 2638 /// \brief Write an UPDATE_VISIBLE block for the given context. 2639 /// 2640 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing 2641 /// DeclContext in a dependent AST file. As such, they only exist for the TU 2642 /// (in C++) and for namespaces. 2643 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) { 2644 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr()); 2645 if (!Map || Map->empty()) 2646 return; 2647 2648 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator; 2649 ASTDeclContextNameLookupTrait Trait(*this); 2650 2651 // Create the hash table. 2652 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); 2653 D != DEnd; ++D) { 2654 DeclarationName Name = D->first; 2655 DeclContext::lookup_result Result = D->second.getLookupResult(); 2656 // For any name that appears in this table, the results are complete, i.e. 2657 // they overwrite results from previous PCHs. Merging is always a mess. 2658 Generator.insert(Name, Result, Trait); 2659 } 2660 2661 // Create the on-disk hash table in a buffer. 2662 llvm::SmallString<4096> LookupTable; 2663 uint32_t BucketOffset; 2664 { 2665 llvm::raw_svector_ostream Out(LookupTable); 2666 // Make sure that no bucket is at offset 0 2667 clang::io::Emit32(Out, 0); 2668 BucketOffset = Generator.Emit(Out, Trait); 2669 } 2670 2671 // Write the lookup table 2672 RecordData Record; 2673 Record.push_back(UPDATE_VISIBLE); 2674 Record.push_back(getDeclID(cast<Decl>(DC))); 2675 Record.push_back(BucketOffset); 2676 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str()); 2677 } 2678 2679 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions. 2680 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) { 2681 RecordData Record; 2682 Record.push_back(Opts.fp_contract); 2683 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record); 2684 } 2685 2686 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions. 2687 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) { 2688 if (!SemaRef.Context.getLangOptions().OpenCL) 2689 return; 2690 2691 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions(); 2692 RecordData Record; 2693 #define OPENCLEXT(nm) Record.push_back(Opts.nm); 2694 #include "clang/Basic/OpenCLExtensions.def" 2695 Stream.EmitRecord(OPENCL_EXTENSIONS, Record); 2696 } 2697 2698 //===----------------------------------------------------------------------===// 2699 // General Serialization Routines 2700 //===----------------------------------------------------------------------===// 2701 2702 /// \brief Write a record containing the given attributes. 2703 void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) { 2704 Record.push_back(Attrs.size()); 2705 for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){ 2706 const Attr * A = *i; 2707 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs 2708 AddSourceLocation(A->getLocation(), Record); 2709 2710 #include "clang/Serialization/AttrPCHWrite.inc" 2711 2712 } 2713 } 2714 2715 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) { 2716 Record.push_back(Str.size()); 2717 Record.insert(Record.end(), Str.begin(), Str.end()); 2718 } 2719 2720 void ASTWriter::AddVersionTuple(const VersionTuple &Version, 2721 RecordDataImpl &Record) { 2722 Record.push_back(Version.getMajor()); 2723 if (llvm::Optional<unsigned> Minor = Version.getMinor()) 2724 Record.push_back(*Minor + 1); 2725 else 2726 Record.push_back(0); 2727 if (llvm::Optional<unsigned> Subminor = Version.getSubminor()) 2728 Record.push_back(*Subminor + 1); 2729 else 2730 Record.push_back(0); 2731 } 2732 2733 /// \brief Note that the identifier II occurs at the given offset 2734 /// within the identifier table. 2735 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) { 2736 IdentID ID = IdentifierIDs[II]; 2737 // Only store offsets new to this AST file. Other identifier names are looked 2738 // up earlier in the chain and thus don't need an offset. 2739 if (ID >= FirstIdentID) 2740 IdentifierOffsets[ID - FirstIdentID] = Offset; 2741 } 2742 2743 /// \brief Note that the selector Sel occurs at the given offset 2744 /// within the method pool/selector table. 2745 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { 2746 unsigned ID = SelectorIDs[Sel]; 2747 assert(ID && "Unknown selector"); 2748 // Don't record offsets for selectors that are also available in a different 2749 // file. 2750 if (ID < FirstSelectorID) 2751 return; 2752 SelectorOffsets[ID - FirstSelectorID] = Offset; 2753 } 2754 2755 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream) 2756 : Stream(Stream), Context(0), Chain(0), SerializationListener(0), 2757 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID), 2758 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID), 2759 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID), 2760 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID), 2761 FirstMacroID(NUM_PREDEF_MACRO_IDS), NextMacroID(FirstMacroID), 2762 CollectedStmts(&StmtsToEmit), 2763 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0), 2764 NumVisibleDeclContexts(0), 2765 NextCXXBaseSpecifiersID(1), 2766 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0), 2767 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0), 2768 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0), 2769 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0), 2770 DeclTypedefAbbrev(0), 2771 DeclVarAbbrev(0), DeclFieldAbbrev(0), 2772 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0) 2773 { 2774 } 2775 2776 void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls, 2777 const std::string &OutputFile, 2778 StringRef isysroot) { 2779 // Emit the file header. 2780 Stream.Emit((unsigned)'C', 8); 2781 Stream.Emit((unsigned)'P', 8); 2782 Stream.Emit((unsigned)'C', 8); 2783 Stream.Emit((unsigned)'H', 8); 2784 2785 WriteBlockInfoBlock(); 2786 2787 Context = &SemaRef.Context; 2788 WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile); 2789 Context = 0; 2790 } 2791 2792 template<typename Vector> 2793 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, 2794 ASTWriter::RecordData &Record) { 2795 for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end(); 2796 I != E; ++I) { 2797 Writer.AddDeclRef(*I, Record); 2798 } 2799 } 2800 2801 void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls, 2802 StringRef isysroot, 2803 const std::string &OutputFile) { 2804 using namespace llvm; 2805 2806 ASTContext &Context = SemaRef.Context; 2807 Preprocessor &PP = SemaRef.PP; 2808 2809 // Set up predefined declaration IDs. 2810 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID; 2811 if (Context.ObjCIdDecl) 2812 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID; 2813 2814 if (!Chain) { 2815 // Make sure that we emit IdentifierInfos (and any attached 2816 // declarations) for builtins. We don't need to do this when we're 2817 // emitting chained PCH files, because all of the builtins will be 2818 // in the original PCH file. 2819 // FIXME: Modules won't like this at all. 2820 IdentifierTable &Table = PP.getIdentifierTable(); 2821 SmallVector<const char *, 32> BuiltinNames; 2822 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames, 2823 Context.getLangOptions().NoBuiltin); 2824 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I) 2825 getIdentifierRef(&Table.get(BuiltinNames[I])); 2826 } 2827 2828 // Build a record containing all of the tentative definitions in this file, in 2829 // TentativeDefinitions order. Generally, this record will be empty for 2830 // headers. 2831 RecordData TentativeDefinitions; 2832 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions); 2833 2834 // Build a record containing all of the file scoped decls in this file. 2835 RecordData UnusedFileScopedDecls; 2836 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls, 2837 UnusedFileScopedDecls); 2838 2839 // Build a record containing all of the delegating constructors we still need 2840 // to resolve. 2841 RecordData DelegatingCtorDecls; 2842 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls); 2843 2844 // Write the set of weak, undeclared identifiers. We always write the 2845 // entire table, since later PCH files in a PCH chain are only interested in 2846 // the results at the end of the chain. 2847 RecordData WeakUndeclaredIdentifiers; 2848 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) { 2849 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 2850 I = SemaRef.WeakUndeclaredIdentifiers.begin(), 2851 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) { 2852 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers); 2853 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers); 2854 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers); 2855 WeakUndeclaredIdentifiers.push_back(I->second.getUsed()); 2856 } 2857 } 2858 2859 // Build a record containing all of the locally-scoped external 2860 // declarations in this header file. Generally, this record will be 2861 // empty. 2862 RecordData LocallyScopedExternalDecls; 2863 // FIXME: This is filling in the AST file in densemap order which is 2864 // nondeterminstic! 2865 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 2866 TD = SemaRef.LocallyScopedExternalDecls.begin(), 2867 TDEnd = SemaRef.LocallyScopedExternalDecls.end(); 2868 TD != TDEnd; ++TD) { 2869 if (TD->second->getPCHLevel() == 0) 2870 AddDeclRef(TD->second, LocallyScopedExternalDecls); 2871 } 2872 2873 // Build a record containing all of the ext_vector declarations. 2874 RecordData ExtVectorDecls; 2875 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls); 2876 2877 // Build a record containing all of the VTable uses information. 2878 RecordData VTableUses; 2879 if (!SemaRef.VTableUses.empty()) { 2880 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 2881 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 2882 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 2883 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 2884 } 2885 } 2886 2887 // Build a record containing all of dynamic classes declarations. 2888 RecordData DynamicClasses; 2889 AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses); 2890 2891 // Build a record containing all of pending implicit instantiations. 2892 RecordData PendingInstantiations; 2893 for (std::deque<Sema::PendingImplicitInstantiation>::iterator 2894 I = SemaRef.PendingInstantiations.begin(), 2895 N = SemaRef.PendingInstantiations.end(); I != N; ++I) { 2896 AddDeclRef(I->first, PendingInstantiations); 2897 AddSourceLocation(I->second, PendingInstantiations); 2898 } 2899 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 2900 "There are local ones at end of translation unit!"); 2901 2902 // Build a record containing some declaration references. 2903 RecordData SemaDeclRefs; 2904 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) { 2905 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 2906 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 2907 } 2908 2909 RecordData CUDASpecialDeclRefs; 2910 if (Context.getcudaConfigureCallDecl()) { 2911 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs); 2912 } 2913 2914 // Build a record containing all of the known namespaces. 2915 RecordData KnownNamespaces; 2916 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator 2917 I = SemaRef.KnownNamespaces.begin(), 2918 IEnd = SemaRef.KnownNamespaces.end(); 2919 I != IEnd; ++I) { 2920 if (!I->second) 2921 AddDeclRef(I->first, KnownNamespaces); 2922 } 2923 2924 // Write the remaining AST contents. 2925 RecordData Record; 2926 Stream.EnterSubblock(AST_BLOCK_ID, 5); 2927 WriteMetadata(Context, isysroot, OutputFile); 2928 WriteLanguageOptions(Context.getLangOptions()); 2929 if (StatCalls && isysroot.empty()) 2930 WriteStatCache(*StatCalls); 2931 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot); 2932 2933 if (Chain) { 2934 // Write the mapping information describing our module dependencies and how 2935 // each of those modules were mapped into our own offset/ID space, so that 2936 // the reader can build the appropriate mapping to its own offset/ID space. 2937 // The map consists solely of a blob with the following format: 2938 // *(module-name-len:i16 module-name:len*i8 2939 // source-location-offset:i32 2940 // identifier-id:i32 2941 // preprocessed-entity-id:i32 2942 // macro-definition-id:i32 2943 // selector-id:i32 2944 // declaration-id:i32 2945 // c++-base-specifiers-id:i32 2946 // type-id:i32) 2947 // 2948 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2949 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP)); 2950 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2951 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev); 2952 llvm::SmallString<2048> Buffer; 2953 { 2954 llvm::raw_svector_ostream Out(Buffer); 2955 for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(), 2956 MEnd = Chain->ModuleMgr.end(); 2957 M != MEnd; ++M) { 2958 StringRef FileName = (*M)->FileName; 2959 io::Emit16(Out, FileName.size()); 2960 Out.write(FileName.data(), FileName.size()); 2961 io::Emit32(Out, (*M)->SLocEntryBaseOffset); 2962 io::Emit32(Out, (*M)->BaseIdentifierID); 2963 io::Emit32(Out, (*M)->BasePreprocessedEntityID); 2964 io::Emit32(Out, (*M)->BaseMacroDefinitionID); 2965 io::Emit32(Out, (*M)->BaseSelectorID); 2966 io::Emit32(Out, (*M)->BaseDeclID); 2967 io::Emit32(Out, (*M)->BaseTypeIndex); 2968 } 2969 } 2970 Record.clear(); 2971 Record.push_back(MODULE_OFFSET_MAP); 2972 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record, 2973 Buffer.data(), Buffer.size()); 2974 } 2975 2976 // Create a lexical update block containing all of the declarations in the 2977 // translation unit that do not come from other AST files. 2978 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 2979 SmallVector<KindDeclIDPair, 64> NewGlobalDecls; 2980 for (DeclContext::decl_iterator I = TU->noload_decls_begin(), 2981 E = TU->noload_decls_end(); 2982 I != E; ++I) { 2983 if ((*I)->getPCHLevel() == 0) 2984 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I))); 2985 else if ((*I)->isChangedSinceDeserialization()) 2986 (void)GetDeclRef(*I); // Make sure it's written, but don't record it. 2987 } 2988 2989 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev(); 2990 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL)); 2991 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 2992 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv); 2993 Record.clear(); 2994 Record.push_back(TU_UPDATE_LEXICAL); 2995 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, 2996 data(NewGlobalDecls)); 2997 2998 // And a visible updates block for the translation unit. 2999 Abv = new llvm::BitCodeAbbrev(); 3000 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE)); 3001 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 3002 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32)); 3003 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 3004 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv); 3005 WriteDeclContextVisibleUpdate(TU); 3006 3007 // If the translation unit has an anonymous namespace, and we don't already 3008 // have an update block for it, write it as an update block. 3009 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) { 3010 ASTWriter::UpdateRecord &Record = DeclUpdates[TU]; 3011 if (Record.empty()) { 3012 Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE); 3013 AddDeclRef(NS, Record); 3014 } 3015 } 3016 3017 // Form the record of special types. 3018 RecordData SpecialTypes; 3019 AddTypeRef(Context.getBuiltinVaListType(), SpecialTypes); 3020 AddTypeRef(Context.ObjCSelTypedefType, SpecialTypes); 3021 AddTypeRef(Context.ObjCProtoType, SpecialTypes); 3022 AddTypeRef(Context.ObjCClassTypedefType, SpecialTypes); 3023 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes); 3024 AddTypeRef(Context.getFILEType(), SpecialTypes); 3025 AddTypeRef(Context.getjmp_bufType(), SpecialTypes); 3026 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes); 3027 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes); 3028 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes); 3029 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes); 3030 SpecialTypes.push_back(Context.isInt128Installed()); 3031 3032 // Keep writing types and declarations until all types and 3033 // declarations have been written. 3034 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 3035 WriteDeclsBlockAbbrevs(); 3036 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(), 3037 E = DeclsToRewrite.end(); 3038 I != E; ++I) 3039 DeclTypesToEmit.push(const_cast<Decl*>(*I)); 3040 while (!DeclTypesToEmit.empty()) { 3041 DeclOrType DOT = DeclTypesToEmit.front(); 3042 DeclTypesToEmit.pop(); 3043 if (DOT.isType()) 3044 WriteType(DOT.getType()); 3045 else 3046 WriteDecl(Context, DOT.getDecl()); 3047 } 3048 Stream.ExitBlock(); 3049 3050 WritePreprocessor(PP); 3051 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot); 3052 WriteSelectors(SemaRef); 3053 WriteReferencedSelectorsPool(SemaRef); 3054 WriteIdentifierTable(PP); 3055 WriteFPPragmaOptions(SemaRef.getFPOptions()); 3056 WriteOpenCLExtensions(SemaRef); 3057 3058 WriteTypeDeclOffsets(); 3059 WritePragmaDiagnosticMappings(Context.getDiagnostics()); 3060 3061 WriteCXXBaseSpecifiersOffsets(); 3062 3063 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes); 3064 3065 /// Build a record containing first declarations from a chained PCH and the 3066 /// most recent declarations in this AST that they point to. 3067 RecordData FirstLatestDeclIDs; 3068 for (FirstLatestDeclMap::iterator I = FirstLatestDecls.begin(), 3069 E = FirstLatestDecls.end(); 3070 I != E; ++I) { 3071 assert(I->first->getPCHLevel() > I->second->getPCHLevel() && 3072 "Expected first & second to be in different PCHs"); 3073 AddDeclRef(I->first, FirstLatestDeclIDs); 3074 AddDeclRef(I->second, FirstLatestDeclIDs); 3075 } 3076 3077 if (!FirstLatestDeclIDs.empty()) 3078 Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs); 3079 3080 // Write the record containing external, unnamed definitions. 3081 if (!ExternalDefinitions.empty()) 3082 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions); 3083 3084 // Write the record containing tentative definitions. 3085 if (!TentativeDefinitions.empty()) 3086 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 3087 3088 // Write the record containing unused file scoped decls. 3089 if (!UnusedFileScopedDecls.empty()) 3090 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 3091 3092 // Write the record containing weak undeclared identifiers. 3093 if (!WeakUndeclaredIdentifiers.empty()) 3094 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 3095 WeakUndeclaredIdentifiers); 3096 3097 // Write the record containing locally-scoped external definitions. 3098 if (!LocallyScopedExternalDecls.empty()) 3099 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS, 3100 LocallyScopedExternalDecls); 3101 3102 // Write the record containing ext_vector type names. 3103 if (!ExtVectorDecls.empty()) 3104 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 3105 3106 // Write the record containing VTable uses information. 3107 if (!VTableUses.empty()) 3108 Stream.EmitRecord(VTABLE_USES, VTableUses); 3109 3110 // Write the record containing dynamic classes declarations. 3111 if (!DynamicClasses.empty()) 3112 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses); 3113 3114 // Write the record containing pending implicit instantiations. 3115 if (!PendingInstantiations.empty()) 3116 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 3117 3118 // Write the record containing declaration references of Sema. 3119 if (!SemaDeclRefs.empty()) 3120 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 3121 3122 // Write the record containing CUDA-specific declaration references. 3123 if (!CUDASpecialDeclRefs.empty()) 3124 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs); 3125 3126 // Write the delegating constructors. 3127 if (!DelegatingCtorDecls.empty()) 3128 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls); 3129 3130 // Write the known namespaces. 3131 if (!KnownNamespaces.empty()) 3132 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces); 3133 3134 // Write the visible updates to DeclContexts. 3135 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator 3136 I = UpdatedDeclContexts.begin(), 3137 E = UpdatedDeclContexts.end(); 3138 I != E; ++I) 3139 WriteDeclContextVisibleUpdate(*I); 3140 3141 WriteDeclUpdatesBlocks(); 3142 WriteDeclReplacementsBlock(); 3143 3144 // Some simple statistics 3145 Record.clear(); 3146 Record.push_back(NumStatements); 3147 Record.push_back(NumMacros); 3148 Record.push_back(NumLexicalDeclContexts); 3149 Record.push_back(NumVisibleDeclContexts); 3150 Stream.EmitRecord(STATISTICS, Record); 3151 Stream.ExitBlock(); 3152 } 3153 3154 void ASTWriter::WriteDeclUpdatesBlocks() { 3155 if (DeclUpdates.empty()) 3156 return; 3157 3158 RecordData OffsetsRecord; 3159 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 3160 for (DeclUpdateMap::iterator 3161 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) { 3162 const Decl *D = I->first; 3163 UpdateRecord &URec = I->second; 3164 3165 if (DeclsToRewrite.count(D)) 3166 continue; // The decl will be written completely,no need to store updates. 3167 3168 uint64_t Offset = Stream.GetCurrentBitNo(); 3169 Stream.EmitRecord(DECL_UPDATES, URec); 3170 3171 OffsetsRecord.push_back(GetDeclRef(D)); 3172 OffsetsRecord.push_back(Offset); 3173 } 3174 Stream.ExitBlock(); 3175 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord); 3176 } 3177 3178 void ASTWriter::WriteDeclReplacementsBlock() { 3179 if (ReplacedDecls.empty()) 3180 return; 3181 3182 RecordData Record; 3183 for (SmallVector<std::pair<DeclID, uint64_t>, 16>::iterator 3184 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) { 3185 Record.push_back(I->first); 3186 Record.push_back(I->second); 3187 } 3188 Stream.EmitRecord(DECL_REPLACEMENTS, Record); 3189 } 3190 3191 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) { 3192 Record.push_back(Loc.getRawEncoding()); 3193 } 3194 3195 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) { 3196 AddSourceLocation(Range.getBegin(), Record); 3197 AddSourceLocation(Range.getEnd(), Record); 3198 } 3199 3200 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) { 3201 Record.push_back(Value.getBitWidth()); 3202 const uint64_t *Words = Value.getRawData(); 3203 Record.append(Words, Words + Value.getNumWords()); 3204 } 3205 3206 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) { 3207 Record.push_back(Value.isUnsigned()); 3208 AddAPInt(Value, Record); 3209 } 3210 3211 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) { 3212 AddAPInt(Value.bitcastToAPInt(), Record); 3213 } 3214 3215 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) { 3216 Record.push_back(getIdentifierRef(II)); 3217 } 3218 3219 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) { 3220 if (II == 0) 3221 return 0; 3222 3223 IdentID &ID = IdentifierIDs[II]; 3224 if (ID == 0) 3225 ID = NextIdentID++; 3226 return ID; 3227 } 3228 3229 MacroID ASTWriter::getMacroDefinitionID(MacroDefinition *MD) { 3230 if (MD == 0) 3231 return 0; 3232 3233 MacroID &ID = MacroDefinitions[MD]; 3234 if (ID == 0) 3235 ID = NextMacroID++; 3236 return ID; 3237 } 3238 3239 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) { 3240 Record.push_back(getSelectorRef(SelRef)); 3241 } 3242 3243 SelectorID ASTWriter::getSelectorRef(Selector Sel) { 3244 if (Sel.getAsOpaquePtr() == 0) { 3245 return 0; 3246 } 3247 3248 SelectorID &SID = SelectorIDs[Sel]; 3249 if (SID == 0 && Chain) { 3250 // This might trigger a ReadSelector callback, which will set the ID for 3251 // this selector. 3252 Chain->LoadSelector(Sel); 3253 } 3254 if (SID == 0) { 3255 SID = NextSelectorID++; 3256 } 3257 return SID; 3258 } 3259 3260 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) { 3261 AddDeclRef(Temp->getDestructor(), Record); 3262 } 3263 3264 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases, 3265 CXXBaseSpecifier const *BasesEnd, 3266 RecordDataImpl &Record) { 3267 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded"); 3268 CXXBaseSpecifiersToWrite.push_back( 3269 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID, 3270 Bases, BasesEnd)); 3271 Record.push_back(NextCXXBaseSpecifiersID++); 3272 } 3273 3274 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind, 3275 const TemplateArgumentLocInfo &Arg, 3276 RecordDataImpl &Record) { 3277 switch (Kind) { 3278 case TemplateArgument::Expression: 3279 AddStmt(Arg.getAsExpr()); 3280 break; 3281 case TemplateArgument::Type: 3282 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record); 3283 break; 3284 case TemplateArgument::Template: 3285 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record); 3286 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 3287 break; 3288 case TemplateArgument::TemplateExpansion: 3289 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record); 3290 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 3291 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record); 3292 break; 3293 case TemplateArgument::Null: 3294 case TemplateArgument::Integral: 3295 case TemplateArgument::Declaration: 3296 case TemplateArgument::Pack: 3297 break; 3298 } 3299 } 3300 3301 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg, 3302 RecordDataImpl &Record) { 3303 AddTemplateArgument(Arg.getArgument(), Record); 3304 3305 if (Arg.getArgument().getKind() == TemplateArgument::Expression) { 3306 bool InfoHasSameExpr 3307 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr(); 3308 Record.push_back(InfoHasSameExpr); 3309 if (InfoHasSameExpr) 3310 return; // Avoid storing the same expr twice. 3311 } 3312 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(), 3313 Record); 3314 } 3315 3316 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo, 3317 RecordDataImpl &Record) { 3318 if (TInfo == 0) { 3319 AddTypeRef(QualType(), Record); 3320 return; 3321 } 3322 3323 AddTypeLoc(TInfo->getTypeLoc(), Record); 3324 } 3325 3326 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) { 3327 AddTypeRef(TL.getType(), Record); 3328 3329 TypeLocWriter TLW(*this, Record); 3330 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 3331 TLW.Visit(TL); 3332 } 3333 3334 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) { 3335 Record.push_back(GetOrCreateTypeID(T)); 3336 } 3337 3338 TypeID ASTWriter::GetOrCreateTypeID( QualType T) { 3339 return MakeTypeID(*Context, T, 3340 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this)); 3341 } 3342 3343 TypeID ASTWriter::getTypeID(QualType T) const { 3344 return MakeTypeID(*Context, T, 3345 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this)); 3346 } 3347 3348 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) { 3349 if (T.isNull()) 3350 return TypeIdx(); 3351 assert(!T.getLocalFastQualifiers()); 3352 3353 TypeIdx &Idx = TypeIdxs[T]; 3354 if (Idx.getIndex() == 0) { 3355 // We haven't seen this type before. Assign it a new ID and put it 3356 // into the queue of types to emit. 3357 Idx = TypeIdx(NextTypeID++); 3358 DeclTypesToEmit.push(T); 3359 } 3360 return Idx; 3361 } 3362 3363 TypeIdx ASTWriter::getTypeIdx(QualType T) const { 3364 if (T.isNull()) 3365 return TypeIdx(); 3366 assert(!T.getLocalFastQualifiers()); 3367 3368 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 3369 assert(I != TypeIdxs.end() && "Type not emitted!"); 3370 return I->second; 3371 } 3372 3373 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) { 3374 Record.push_back(GetDeclRef(D)); 3375 } 3376 3377 DeclID ASTWriter::GetDeclRef(const Decl *D) { 3378 if (D == 0) { 3379 return 0; 3380 } 3381 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer"); 3382 DeclID &ID = DeclIDs[D]; 3383 if (ID == 0) { 3384 // We haven't seen this declaration before. Give it a new ID and 3385 // enqueue it in the list of declarations to emit. 3386 ID = NextDeclID++; 3387 DeclTypesToEmit.push(const_cast<Decl *>(D)); 3388 } else if (ID < FirstDeclID && D->isChangedSinceDeserialization()) { 3389 // We don't add it to the replacement collection here, because we don't 3390 // have the offset yet. 3391 DeclTypesToEmit.push(const_cast<Decl *>(D)); 3392 // Reset the flag, so that we don't add this decl multiple times. 3393 const_cast<Decl *>(D)->setChangedSinceDeserialization(false); 3394 } 3395 3396 return ID; 3397 } 3398 3399 DeclID ASTWriter::getDeclID(const Decl *D) { 3400 if (D == 0) 3401 return 0; 3402 3403 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!"); 3404 return DeclIDs[D]; 3405 } 3406 3407 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) { 3408 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc. 3409 Record.push_back(Name.getNameKind()); 3410 switch (Name.getNameKind()) { 3411 case DeclarationName::Identifier: 3412 AddIdentifierRef(Name.getAsIdentifierInfo(), Record); 3413 break; 3414 3415 case DeclarationName::ObjCZeroArgSelector: 3416 case DeclarationName::ObjCOneArgSelector: 3417 case DeclarationName::ObjCMultiArgSelector: 3418 AddSelectorRef(Name.getObjCSelector(), Record); 3419 break; 3420 3421 case DeclarationName::CXXConstructorName: 3422 case DeclarationName::CXXDestructorName: 3423 case DeclarationName::CXXConversionFunctionName: 3424 AddTypeRef(Name.getCXXNameType(), Record); 3425 break; 3426 3427 case DeclarationName::CXXOperatorName: 3428 Record.push_back(Name.getCXXOverloadedOperator()); 3429 break; 3430 3431 case DeclarationName::CXXLiteralOperatorName: 3432 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record); 3433 break; 3434 3435 case DeclarationName::CXXUsingDirective: 3436 // No extra data to emit 3437 break; 3438 } 3439 } 3440 3441 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 3442 DeclarationName Name, RecordDataImpl &Record) { 3443 switch (Name.getNameKind()) { 3444 case DeclarationName::CXXConstructorName: 3445 case DeclarationName::CXXDestructorName: 3446 case DeclarationName::CXXConversionFunctionName: 3447 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record); 3448 break; 3449 3450 case DeclarationName::CXXOperatorName: 3451 AddSourceLocation( 3452 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc), 3453 Record); 3454 AddSourceLocation( 3455 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc), 3456 Record); 3457 break; 3458 3459 case DeclarationName::CXXLiteralOperatorName: 3460 AddSourceLocation( 3461 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc), 3462 Record); 3463 break; 3464 3465 case DeclarationName::Identifier: 3466 case DeclarationName::ObjCZeroArgSelector: 3467 case DeclarationName::ObjCOneArgSelector: 3468 case DeclarationName::ObjCMultiArgSelector: 3469 case DeclarationName::CXXUsingDirective: 3470 break; 3471 } 3472 } 3473 3474 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 3475 RecordDataImpl &Record) { 3476 AddDeclarationName(NameInfo.getName(), Record); 3477 AddSourceLocation(NameInfo.getLoc(), Record); 3478 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record); 3479 } 3480 3481 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info, 3482 RecordDataImpl &Record) { 3483 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record); 3484 Record.push_back(Info.NumTemplParamLists); 3485 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i) 3486 AddTemplateParameterList(Info.TemplParamLists[i], Record); 3487 } 3488 3489 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS, 3490 RecordDataImpl &Record) { 3491 // Nested name specifiers usually aren't too long. I think that 8 would 3492 // typically accommodate the vast majority. 3493 SmallVector<NestedNameSpecifier *, 8> NestedNames; 3494 3495 // Push each of the NNS's onto a stack for serialization in reverse order. 3496 while (NNS) { 3497 NestedNames.push_back(NNS); 3498 NNS = NNS->getPrefix(); 3499 } 3500 3501 Record.push_back(NestedNames.size()); 3502 while(!NestedNames.empty()) { 3503 NNS = NestedNames.pop_back_val(); 3504 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind(); 3505 Record.push_back(Kind); 3506 switch (Kind) { 3507 case NestedNameSpecifier::Identifier: 3508 AddIdentifierRef(NNS->getAsIdentifier(), Record); 3509 break; 3510 3511 case NestedNameSpecifier::Namespace: 3512 AddDeclRef(NNS->getAsNamespace(), Record); 3513 break; 3514 3515 case NestedNameSpecifier::NamespaceAlias: 3516 AddDeclRef(NNS->getAsNamespaceAlias(), Record); 3517 break; 3518 3519 case NestedNameSpecifier::TypeSpec: 3520 case NestedNameSpecifier::TypeSpecWithTemplate: 3521 AddTypeRef(QualType(NNS->getAsType(), 0), Record); 3522 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 3523 break; 3524 3525 case NestedNameSpecifier::Global: 3526 // Don't need to write an associated value. 3527 break; 3528 } 3529 } 3530 } 3531 3532 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 3533 RecordDataImpl &Record) { 3534 // Nested name specifiers usually aren't too long. I think that 8 would 3535 // typically accommodate the vast majority. 3536 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 3537 3538 // Push each of the nested-name-specifiers's onto a stack for 3539 // serialization in reverse order. 3540 while (NNS) { 3541 NestedNames.push_back(NNS); 3542 NNS = NNS.getPrefix(); 3543 } 3544 3545 Record.push_back(NestedNames.size()); 3546 while(!NestedNames.empty()) { 3547 NNS = NestedNames.pop_back_val(); 3548 NestedNameSpecifier::SpecifierKind Kind 3549 = NNS.getNestedNameSpecifier()->getKind(); 3550 Record.push_back(Kind); 3551 switch (Kind) { 3552 case NestedNameSpecifier::Identifier: 3553 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record); 3554 AddSourceRange(NNS.getLocalSourceRange(), Record); 3555 break; 3556 3557 case NestedNameSpecifier::Namespace: 3558 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record); 3559 AddSourceRange(NNS.getLocalSourceRange(), Record); 3560 break; 3561 3562 case NestedNameSpecifier::NamespaceAlias: 3563 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record); 3564 AddSourceRange(NNS.getLocalSourceRange(), Record); 3565 break; 3566 3567 case NestedNameSpecifier::TypeSpec: 3568 case NestedNameSpecifier::TypeSpecWithTemplate: 3569 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 3570 AddTypeLoc(NNS.getTypeLoc(), Record); 3571 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record); 3572 break; 3573 3574 case NestedNameSpecifier::Global: 3575 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record); 3576 break; 3577 } 3578 } 3579 } 3580 3581 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) { 3582 TemplateName::NameKind Kind = Name.getKind(); 3583 Record.push_back(Kind); 3584 switch (Kind) { 3585 case TemplateName::Template: 3586 AddDeclRef(Name.getAsTemplateDecl(), Record); 3587 break; 3588 3589 case TemplateName::OverloadedTemplate: { 3590 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate(); 3591 Record.push_back(OvT->size()); 3592 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end(); 3593 I != E; ++I) 3594 AddDeclRef(*I, Record); 3595 break; 3596 } 3597 3598 case TemplateName::QualifiedTemplate: { 3599 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName(); 3600 AddNestedNameSpecifier(QualT->getQualifier(), Record); 3601 Record.push_back(QualT->hasTemplateKeyword()); 3602 AddDeclRef(QualT->getTemplateDecl(), Record); 3603 break; 3604 } 3605 3606 case TemplateName::DependentTemplate: { 3607 DependentTemplateName *DepT = Name.getAsDependentTemplateName(); 3608 AddNestedNameSpecifier(DepT->getQualifier(), Record); 3609 Record.push_back(DepT->isIdentifier()); 3610 if (DepT->isIdentifier()) 3611 AddIdentifierRef(DepT->getIdentifier(), Record); 3612 else 3613 Record.push_back(DepT->getOperator()); 3614 break; 3615 } 3616 3617 case TemplateName::SubstTemplateTemplateParm: { 3618 SubstTemplateTemplateParmStorage *subst 3619 = Name.getAsSubstTemplateTemplateParm(); 3620 AddDeclRef(subst->getParameter(), Record); 3621 AddTemplateName(subst->getReplacement(), Record); 3622 break; 3623 } 3624 3625 case TemplateName::SubstTemplateTemplateParmPack: { 3626 SubstTemplateTemplateParmPackStorage *SubstPack 3627 = Name.getAsSubstTemplateTemplateParmPack(); 3628 AddDeclRef(SubstPack->getParameterPack(), Record); 3629 AddTemplateArgument(SubstPack->getArgumentPack(), Record); 3630 break; 3631 } 3632 } 3633 } 3634 3635 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg, 3636 RecordDataImpl &Record) { 3637 Record.push_back(Arg.getKind()); 3638 switch (Arg.getKind()) { 3639 case TemplateArgument::Null: 3640 break; 3641 case TemplateArgument::Type: 3642 AddTypeRef(Arg.getAsType(), Record); 3643 break; 3644 case TemplateArgument::Declaration: 3645 AddDeclRef(Arg.getAsDecl(), Record); 3646 break; 3647 case TemplateArgument::Integral: 3648 AddAPSInt(*Arg.getAsIntegral(), Record); 3649 AddTypeRef(Arg.getIntegralType(), Record); 3650 break; 3651 case TemplateArgument::Template: 3652 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 3653 break; 3654 case TemplateArgument::TemplateExpansion: 3655 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 3656 if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions()) 3657 Record.push_back(*NumExpansions + 1); 3658 else 3659 Record.push_back(0); 3660 break; 3661 case TemplateArgument::Expression: 3662 AddStmt(Arg.getAsExpr()); 3663 break; 3664 case TemplateArgument::Pack: 3665 Record.push_back(Arg.pack_size()); 3666 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end(); 3667 I != E; ++I) 3668 AddTemplateArgument(*I, Record); 3669 break; 3670 } 3671 } 3672 3673 void 3674 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams, 3675 RecordDataImpl &Record) { 3676 assert(TemplateParams && "No TemplateParams!"); 3677 AddSourceLocation(TemplateParams->getTemplateLoc(), Record); 3678 AddSourceLocation(TemplateParams->getLAngleLoc(), Record); 3679 AddSourceLocation(TemplateParams->getRAngleLoc(), Record); 3680 Record.push_back(TemplateParams->size()); 3681 for (TemplateParameterList::const_iterator 3682 P = TemplateParams->begin(), PEnd = TemplateParams->end(); 3683 P != PEnd; ++P) 3684 AddDeclRef(*P, Record); 3685 } 3686 3687 /// \brief Emit a template argument list. 3688 void 3689 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs, 3690 RecordDataImpl &Record) { 3691 assert(TemplateArgs && "No TemplateArgs!"); 3692 Record.push_back(TemplateArgs->size()); 3693 for (int i=0, e = TemplateArgs->size(); i != e; ++i) 3694 AddTemplateArgument(TemplateArgs->get(i), Record); 3695 } 3696 3697 3698 void 3699 ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) { 3700 Record.push_back(Set.size()); 3701 for (UnresolvedSetImpl::const_iterator 3702 I = Set.begin(), E = Set.end(); I != E; ++I) { 3703 AddDeclRef(I.getDecl(), Record); 3704 Record.push_back(I.getAccess()); 3705 } 3706 } 3707 3708 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base, 3709 RecordDataImpl &Record) { 3710 Record.push_back(Base.isVirtual()); 3711 Record.push_back(Base.isBaseOfClass()); 3712 Record.push_back(Base.getAccessSpecifierAsWritten()); 3713 Record.push_back(Base.getInheritConstructors()); 3714 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record); 3715 AddSourceRange(Base.getSourceRange(), Record); 3716 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 3717 : SourceLocation(), 3718 Record); 3719 } 3720 3721 void ASTWriter::FlushCXXBaseSpecifiers() { 3722 RecordData Record; 3723 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) { 3724 Record.clear(); 3725 3726 // Record the offset of this base-specifier set. 3727 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1; 3728 if (Index == CXXBaseSpecifiersOffsets.size()) 3729 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo()); 3730 else { 3731 if (Index > CXXBaseSpecifiersOffsets.size()) 3732 CXXBaseSpecifiersOffsets.resize(Index + 1); 3733 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo(); 3734 } 3735 3736 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases, 3737 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd; 3738 Record.push_back(BEnd - B); 3739 for (; B != BEnd; ++B) 3740 AddCXXBaseSpecifier(*B, Record); 3741 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record); 3742 3743 // Flush any expressions that were written as part of the base specifiers. 3744 FlushStmts(); 3745 } 3746 3747 CXXBaseSpecifiersToWrite.clear(); 3748 } 3749 3750 void ASTWriter::AddCXXCtorInitializers( 3751 const CXXCtorInitializer * const *CtorInitializers, 3752 unsigned NumCtorInitializers, 3753 RecordDataImpl &Record) { 3754 Record.push_back(NumCtorInitializers); 3755 for (unsigned i=0; i != NumCtorInitializers; ++i) { 3756 const CXXCtorInitializer *Init = CtorInitializers[i]; 3757 3758 if (Init->isBaseInitializer()) { 3759 Record.push_back(CTOR_INITIALIZER_BASE); 3760 AddTypeSourceInfo(Init->getBaseClassInfo(), Record); 3761 Record.push_back(Init->isBaseVirtual()); 3762 } else if (Init->isDelegatingInitializer()) { 3763 Record.push_back(CTOR_INITIALIZER_DELEGATING); 3764 AddDeclRef(Init->getTargetConstructor(), Record); 3765 } else if (Init->isMemberInitializer()){ 3766 Record.push_back(CTOR_INITIALIZER_MEMBER); 3767 AddDeclRef(Init->getMember(), Record); 3768 } else { 3769 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER); 3770 AddDeclRef(Init->getIndirectMember(), Record); 3771 } 3772 3773 AddSourceLocation(Init->getMemberLocation(), Record); 3774 AddStmt(Init->getInit()); 3775 AddSourceLocation(Init->getLParenLoc(), Record); 3776 AddSourceLocation(Init->getRParenLoc(), Record); 3777 Record.push_back(Init->isWritten()); 3778 if (Init->isWritten()) { 3779 Record.push_back(Init->getSourceOrder()); 3780 } else { 3781 Record.push_back(Init->getNumArrayIndices()); 3782 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i) 3783 AddDeclRef(Init->getArrayIndex(i), Record); 3784 } 3785 } 3786 } 3787 3788 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) { 3789 assert(D->DefinitionData); 3790 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData; 3791 Record.push_back(Data.UserDeclaredConstructor); 3792 Record.push_back(Data.UserDeclaredCopyConstructor); 3793 Record.push_back(Data.UserDeclaredCopyAssignment); 3794 Record.push_back(Data.UserDeclaredDestructor); 3795 Record.push_back(Data.Aggregate); 3796 Record.push_back(Data.PlainOldData); 3797 Record.push_back(Data.Empty); 3798 Record.push_back(Data.Polymorphic); 3799 Record.push_back(Data.Abstract); 3800 Record.push_back(Data.IsStandardLayout); 3801 Record.push_back(Data.HasNoNonEmptyBases); 3802 Record.push_back(Data.HasPrivateFields); 3803 Record.push_back(Data.HasProtectedFields); 3804 Record.push_back(Data.HasPublicFields); 3805 Record.push_back(Data.HasMutableFields); 3806 Record.push_back(Data.HasTrivialDefaultConstructor); 3807 Record.push_back(Data.HasConstexprNonCopyMoveConstructor); 3808 Record.push_back(Data.HasTrivialCopyConstructor); 3809 Record.push_back(Data.HasTrivialMoveConstructor); 3810 Record.push_back(Data.HasTrivialCopyAssignment); 3811 Record.push_back(Data.HasTrivialMoveAssignment); 3812 Record.push_back(Data.HasTrivialDestructor); 3813 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases); 3814 Record.push_back(Data.ComputedVisibleConversions); 3815 Record.push_back(Data.UserProvidedDefaultConstructor); 3816 Record.push_back(Data.DeclaredDefaultConstructor); 3817 Record.push_back(Data.DeclaredCopyConstructor); 3818 Record.push_back(Data.DeclaredCopyAssignment); 3819 Record.push_back(Data.DeclaredDestructor); 3820 3821 Record.push_back(Data.NumBases); 3822 if (Data.NumBases > 0) 3823 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases, 3824 Record); 3825 3826 // FIXME: Make VBases lazily computed when needed to avoid storing them. 3827 Record.push_back(Data.NumVBases); 3828 if (Data.NumVBases > 0) 3829 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases, 3830 Record); 3831 3832 AddUnresolvedSet(Data.Conversions, Record); 3833 AddUnresolvedSet(Data.VisibleConversions, Record); 3834 // Data.Definition is the owning decl, no need to write it. 3835 AddDeclRef(Data.FirstFriend, Record); 3836 } 3837 3838 void ASTWriter::ReaderInitialized(ASTReader *Reader) { 3839 assert(Reader && "Cannot remove chain"); 3840 assert(!Chain && "Cannot replace chain"); 3841 assert(FirstDeclID == NextDeclID && 3842 FirstTypeID == NextTypeID && 3843 FirstIdentID == NextIdentID && 3844 FirstSelectorID == NextSelectorID && 3845 FirstMacroID == NextMacroID && 3846 "Setting chain after writing has started."); 3847 3848 Chain = Reader; 3849 3850 FirstDeclID += Chain->getTotalNumDecls(); 3851 FirstTypeID += Chain->getTotalNumTypes(); 3852 FirstIdentID += Chain->getTotalNumIdentifiers(); 3853 FirstSelectorID += Chain->getTotalNumSelectors(); 3854 FirstMacroID += Chain->getTotalNumMacroDefinitions(); 3855 NextDeclID = FirstDeclID; 3856 NextTypeID = FirstTypeID; 3857 NextIdentID = FirstIdentID; 3858 NextSelectorID = FirstSelectorID; 3859 NextMacroID = FirstMacroID; 3860 } 3861 3862 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) { 3863 IdentifierIDs[II] = ID; 3864 if (II->hasMacroDefinition()) 3865 DeserializedMacroNames.push_back(II); 3866 } 3867 3868 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) { 3869 // Always take the highest-numbered type index. This copes with an interesting 3870 // case for chained AST writing where we schedule writing the type and then, 3871 // later, deserialize the type from another AST. In this case, we want to 3872 // keep the higher-numbered entry so that we can properly write it out to 3873 // the AST file. 3874 TypeIdx &StoredIdx = TypeIdxs[T]; 3875 if (Idx.getIndex() >= StoredIdx.getIndex()) 3876 StoredIdx = Idx; 3877 } 3878 3879 void ASTWriter::DeclRead(DeclID ID, const Decl *D) { 3880 DeclIDs[D] = ID; 3881 } 3882 3883 void ASTWriter::SelectorRead(SelectorID ID, Selector S) { 3884 SelectorIDs[S] = ID; 3885 } 3886 3887 void ASTWriter::MacroDefinitionRead(serialization::MacroID ID, 3888 MacroDefinition *MD) { 3889 MacroDefinitions[MD] = ID; 3890 } 3891 3892 void ASTWriter::CompletedTagDefinition(const TagDecl *D) { 3893 assert(D->isDefinition()); 3894 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 3895 // We are interested when a PCH decl is modified. 3896 if (RD->getPCHLevel() > 0) { 3897 // A forward reference was mutated into a definition. Rewrite it. 3898 // FIXME: This happens during template instantiation, should we 3899 // have created a new definition decl instead ? 3900 RewriteDecl(RD); 3901 } 3902 3903 for (CXXRecordDecl::redecl_iterator 3904 I = RD->redecls_begin(), E = RD->redecls_end(); I != E; ++I) { 3905 CXXRecordDecl *Redecl = cast<CXXRecordDecl>(*I); 3906 if (Redecl == RD) 3907 continue; 3908 3909 // We are interested when a PCH decl is modified. 3910 if (Redecl->getPCHLevel() > 0) { 3911 UpdateRecord &Record = DeclUpdates[Redecl]; 3912 Record.push_back(UPD_CXX_SET_DEFINITIONDATA); 3913 assert(Redecl->DefinitionData); 3914 assert(Redecl->DefinitionData->Definition == D); 3915 AddDeclRef(D, Record); // the DefinitionDecl 3916 } 3917 } 3918 } 3919 } 3920 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) { 3921 // TU and namespaces are handled elsewhere. 3922 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC)) 3923 return; 3924 3925 if (!(D->getPCHLevel() == 0 && cast<Decl>(DC)->getPCHLevel() > 0)) 3926 return; // Not a source decl added to a DeclContext from PCH. 3927 3928 AddUpdatedDeclContext(DC); 3929 } 3930 3931 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { 3932 assert(D->isImplicit()); 3933 if (!(D->getPCHLevel() == 0 && RD->getPCHLevel() > 0)) 3934 return; // Not a source member added to a class from PCH. 3935 if (!isa<CXXMethodDecl>(D)) 3936 return; // We are interested in lazily declared implicit methods. 3937 3938 // A decl coming from PCH was modified. 3939 assert(RD->isDefinition()); 3940 UpdateRecord &Record = DeclUpdates[RD]; 3941 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER); 3942 AddDeclRef(D, Record); 3943 } 3944 3945 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD, 3946 const ClassTemplateSpecializationDecl *D) { 3947 // The specializations set is kept in the canonical template. 3948 TD = TD->getCanonicalDecl(); 3949 if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0)) 3950 return; // Not a source specialization added to a template from PCH. 3951 3952 UpdateRecord &Record = DeclUpdates[TD]; 3953 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION); 3954 AddDeclRef(D, Record); 3955 } 3956 3957 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, 3958 const FunctionDecl *D) { 3959 // The specializations set is kept in the canonical template. 3960 TD = TD->getCanonicalDecl(); 3961 if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0)) 3962 return; // Not a source specialization added to a template from PCH. 3963 3964 UpdateRecord &Record = DeclUpdates[TD]; 3965 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION); 3966 AddDeclRef(D, Record); 3967 } 3968 3969 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) { 3970 if (D->getPCHLevel() == 0) 3971 return; // Declaration not imported from PCH. 3972 3973 // Implicit decl from a PCH was defined. 3974 // FIXME: Should implicit definition be a separate FunctionDecl? 3975 RewriteDecl(D); 3976 } 3977 3978 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) { 3979 if (D->getPCHLevel() == 0) 3980 return; 3981 3982 // Since the actual instantiation is delayed, this really means that we need 3983 // to update the instantiation location. 3984 UpdateRecord &Record = DeclUpdates[D]; 3985 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER); 3986 AddSourceLocation( 3987 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record); 3988 } 3989 3990 ASTSerializationListener::~ASTSerializationListener() { } 3991