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