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