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