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