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