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