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