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