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/StringMap.h" 86 #include "llvm/ADT/StringRef.h" 87 #include "llvm/Bitcode/BitCodes.h" 88 #include "llvm/Bitcode/BitstreamWriter.h" 89 #include "llvm/Support/Casting.h" 90 #include "llvm/Support/Compression.h" 91 #include "llvm/Support/DJB.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 3096 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0); 3097 assert(!Loc.isInvalid() && "start loc for valid FileID is invalid"); 3098 AddSourceLocation(Loc, Record); 3099 3100 Record.push_back(FileIDAndFile.second.StateTransitions.size()); 3101 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) { 3102 Record.push_back(StatePoint.Offset); 3103 AddDiagState(StatePoint.State, false); 3104 } 3105 } 3106 3107 // Backpatch the number of locations. 3108 Record[NumLocationsIdx] = NumLocations; 3109 3110 // Emit CurDiagStateLoc. Do it last in order to match source order. 3111 // 3112 // This also protects against a hypothetical corner case with simulating 3113 // -Werror settings for implicit modules in the ASTReader, where reading 3114 // CurDiagState out of context could change whether warning pragmas are 3115 // treated as errors. 3116 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record); 3117 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false); 3118 3119 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record); 3120 } 3121 3122 //===----------------------------------------------------------------------===// 3123 // Type Serialization 3124 //===----------------------------------------------------------------------===// 3125 3126 /// \brief Write the representation of a type to the AST stream. 3127 void ASTWriter::WriteType(QualType T) { 3128 TypeIdx &IdxRef = TypeIdxs[T]; 3129 if (IdxRef.getIndex() == 0) // we haven't seen this type before. 3130 IdxRef = TypeIdx(NextTypeID++); 3131 TypeIdx Idx = IdxRef; 3132 3133 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST"); 3134 3135 RecordData Record; 3136 3137 // Emit the type's representation. 3138 ASTTypeWriter W(*this, Record); 3139 W.Visit(T); 3140 uint64_t Offset = W.Emit(); 3141 3142 // Record the offset for this type. 3143 unsigned Index = Idx.getIndex() - FirstTypeID; 3144 if (TypeOffsets.size() == Index) 3145 TypeOffsets.push_back(Offset); 3146 else if (TypeOffsets.size() < Index) { 3147 TypeOffsets.resize(Index + 1); 3148 TypeOffsets[Index] = Offset; 3149 } else { 3150 llvm_unreachable("Types emitted in wrong order"); 3151 } 3152 } 3153 3154 //===----------------------------------------------------------------------===// 3155 // Declaration Serialization 3156 //===----------------------------------------------------------------------===// 3157 3158 /// \brief Write the block containing all of the declaration IDs 3159 /// lexically declared within the given DeclContext. 3160 /// 3161 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the 3162 /// bistream, or 0 if no block was written. 3163 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context, 3164 DeclContext *DC) { 3165 if (DC->decls_empty()) 3166 return 0; 3167 3168 uint64_t Offset = Stream.GetCurrentBitNo(); 3169 SmallVector<uint32_t, 128> KindDeclPairs; 3170 for (const auto *D : DC->decls()) { 3171 KindDeclPairs.push_back(D->getKind()); 3172 KindDeclPairs.push_back(GetDeclRef(D)); 3173 } 3174 3175 ++NumLexicalDeclContexts; 3176 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL}; 3177 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, 3178 bytes(KindDeclPairs)); 3179 return Offset; 3180 } 3181 3182 void ASTWriter::WriteTypeDeclOffsets() { 3183 using namespace llvm; 3184 3185 // Write the type offsets array 3186 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3187 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET)); 3188 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types 3189 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index 3190 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block 3191 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3192 { 3193 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(), 3194 FirstTypeID - NUM_PREDEF_TYPE_IDS}; 3195 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets)); 3196 } 3197 3198 // Write the declaration offsets array 3199 Abbrev = std::make_shared<BitCodeAbbrev>(); 3200 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET)); 3201 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations 3202 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID 3203 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block 3204 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3205 { 3206 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(), 3207 FirstDeclID - NUM_PREDEF_DECL_IDS}; 3208 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets)); 3209 } 3210 } 3211 3212 void ASTWriter::WriteFileDeclIDsMap() { 3213 using namespace llvm; 3214 3215 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs( 3216 FileDeclIDs.begin(), FileDeclIDs.end()); 3217 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(), 3218 llvm::less_first()); 3219 3220 // Join the vectors of DeclIDs from all files. 3221 SmallVector<DeclID, 256> FileGroupedDeclIDs; 3222 for (auto &FileDeclEntry : SortedFileDeclIDs) { 3223 DeclIDInFileInfo &Info = *FileDeclEntry.second; 3224 Info.FirstDeclIndex = FileGroupedDeclIDs.size(); 3225 for (auto &LocDeclEntry : Info.DeclIDs) 3226 FileGroupedDeclIDs.push_back(LocDeclEntry.second); 3227 } 3228 3229 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3230 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS)); 3231 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3232 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3233 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); 3234 RecordData::value_type Record[] = {FILE_SORTED_DECLS, 3235 FileGroupedDeclIDs.size()}; 3236 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs)); 3237 } 3238 3239 void ASTWriter::WriteComments() { 3240 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3); 3241 ArrayRef<RawComment *> RawComments = Context->Comments.getComments(); 3242 RecordData Record; 3243 for (const auto *I : RawComments) { 3244 Record.clear(); 3245 AddSourceRange(I->getSourceRange(), Record); 3246 Record.push_back(I->getKind()); 3247 Record.push_back(I->isTrailingComment()); 3248 Record.push_back(I->isAlmostTrailingComment()); 3249 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record); 3250 } 3251 Stream.ExitBlock(); 3252 } 3253 3254 //===----------------------------------------------------------------------===// 3255 // Global Method Pool and Selector Serialization 3256 //===----------------------------------------------------------------------===// 3257 3258 namespace { 3259 3260 // Trait used for the on-disk hash table used in the method pool. 3261 class ASTMethodPoolTrait { 3262 ASTWriter &Writer; 3263 3264 public: 3265 using key_type = Selector; 3266 using key_type_ref = key_type; 3267 3268 struct data_type { 3269 SelectorID ID; 3270 ObjCMethodList Instance, Factory; 3271 }; 3272 using data_type_ref = const data_type &; 3273 3274 using hash_value_type = unsigned; 3275 using offset_type = unsigned; 3276 3277 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {} 3278 3279 static hash_value_type ComputeHash(Selector Sel) { 3280 return serialization::ComputeHash(Sel); 3281 } 3282 3283 std::pair<unsigned, unsigned> 3284 EmitKeyDataLength(raw_ostream& Out, Selector Sel, 3285 data_type_ref Methods) { 3286 using namespace llvm::support; 3287 3288 endian::Writer<little> LE(Out); 3289 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4); 3290 LE.write<uint16_t>(KeyLen); 3291 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts 3292 for (const ObjCMethodList *Method = &Methods.Instance; Method; 3293 Method = Method->getNext()) 3294 if (Method->getMethod()) 3295 DataLen += 4; 3296 for (const ObjCMethodList *Method = &Methods.Factory; Method; 3297 Method = Method->getNext()) 3298 if (Method->getMethod()) 3299 DataLen += 4; 3300 LE.write<uint16_t>(DataLen); 3301 return std::make_pair(KeyLen, DataLen); 3302 } 3303 3304 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) { 3305 using namespace llvm::support; 3306 3307 endian::Writer<little> LE(Out); 3308 uint64_t Start = Out.tell(); 3309 assert((Start >> 32) == 0 && "Selector key offset too large"); 3310 Writer.SetSelectorOffset(Sel, Start); 3311 unsigned N = Sel.getNumArgs(); 3312 LE.write<uint16_t>(N); 3313 if (N == 0) 3314 N = 1; 3315 for (unsigned I = 0; I != N; ++I) 3316 LE.write<uint32_t>( 3317 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I))); 3318 } 3319 3320 void EmitData(raw_ostream& Out, key_type_ref, 3321 data_type_ref Methods, unsigned DataLen) { 3322 using namespace llvm::support; 3323 3324 endian::Writer<little> LE(Out); 3325 uint64_t Start = Out.tell(); (void)Start; 3326 LE.write<uint32_t>(Methods.ID); 3327 unsigned NumInstanceMethods = 0; 3328 for (const ObjCMethodList *Method = &Methods.Instance; Method; 3329 Method = Method->getNext()) 3330 if (Method->getMethod()) 3331 ++NumInstanceMethods; 3332 3333 unsigned NumFactoryMethods = 0; 3334 for (const ObjCMethodList *Method = &Methods.Factory; Method; 3335 Method = Method->getNext()) 3336 if (Method->getMethod()) 3337 ++NumFactoryMethods; 3338 3339 unsigned InstanceBits = Methods.Instance.getBits(); 3340 assert(InstanceBits < 4); 3341 unsigned InstanceHasMoreThanOneDeclBit = 3342 Methods.Instance.hasMoreThanOneDecl(); 3343 unsigned FullInstanceBits = (NumInstanceMethods << 3) | 3344 (InstanceHasMoreThanOneDeclBit << 2) | 3345 InstanceBits; 3346 unsigned FactoryBits = Methods.Factory.getBits(); 3347 assert(FactoryBits < 4); 3348 unsigned FactoryHasMoreThanOneDeclBit = 3349 Methods.Factory.hasMoreThanOneDecl(); 3350 unsigned FullFactoryBits = (NumFactoryMethods << 3) | 3351 (FactoryHasMoreThanOneDeclBit << 2) | 3352 FactoryBits; 3353 LE.write<uint16_t>(FullInstanceBits); 3354 LE.write<uint16_t>(FullFactoryBits); 3355 for (const ObjCMethodList *Method = &Methods.Instance; Method; 3356 Method = Method->getNext()) 3357 if (Method->getMethod()) 3358 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod())); 3359 for (const ObjCMethodList *Method = &Methods.Factory; Method; 3360 Method = Method->getNext()) 3361 if (Method->getMethod()) 3362 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod())); 3363 3364 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 3365 } 3366 }; 3367 3368 } // namespace 3369 3370 /// \brief Write ObjC data: selectors and the method pool. 3371 /// 3372 /// The method pool contains both instance and factory methods, stored 3373 /// in an on-disk hash table indexed by the selector. The hash table also 3374 /// contains an empty entry for every other selector known to Sema. 3375 void ASTWriter::WriteSelectors(Sema &SemaRef) { 3376 using namespace llvm; 3377 3378 // Do we have to do anything at all? 3379 if (SemaRef.MethodPool.empty() && SelectorIDs.empty()) 3380 return; 3381 unsigned NumTableEntries = 0; 3382 // Create and write out the blob that contains selectors and the method pool. 3383 { 3384 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator; 3385 ASTMethodPoolTrait Trait(*this); 3386 3387 // Create the on-disk hash table representation. We walk through every 3388 // selector we've seen and look it up in the method pool. 3389 SelectorOffsets.resize(NextSelectorID - FirstSelectorID); 3390 for (auto &SelectorAndID : SelectorIDs) { 3391 Selector S = SelectorAndID.first; 3392 SelectorID ID = SelectorAndID.second; 3393 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S); 3394 ASTMethodPoolTrait::data_type Data = { 3395 ID, 3396 ObjCMethodList(), 3397 ObjCMethodList() 3398 }; 3399 if (F != SemaRef.MethodPool.end()) { 3400 Data.Instance = F->second.first; 3401 Data.Factory = F->second.second; 3402 } 3403 // Only write this selector if it's not in an existing AST or something 3404 // changed. 3405 if (Chain && ID < FirstSelectorID) { 3406 // Selector already exists. Did it change? 3407 bool changed = false; 3408 for (ObjCMethodList *M = &Data.Instance; 3409 !changed && M && M->getMethod(); M = M->getNext()) { 3410 if (!M->getMethod()->isFromASTFile()) 3411 changed = true; 3412 } 3413 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod(); 3414 M = M->getNext()) { 3415 if (!M->getMethod()->isFromASTFile()) 3416 changed = true; 3417 } 3418 if (!changed) 3419 continue; 3420 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) { 3421 // A new method pool entry. 3422 ++NumTableEntries; 3423 } 3424 Generator.insert(S, Data, Trait); 3425 } 3426 3427 // Create the on-disk hash table in a buffer. 3428 SmallString<4096> MethodPool; 3429 uint32_t BucketOffset; 3430 { 3431 using namespace llvm::support; 3432 3433 ASTMethodPoolTrait Trait(*this); 3434 llvm::raw_svector_ostream Out(MethodPool); 3435 // Make sure that no bucket is at offset 0 3436 endian::Writer<little>(Out).write<uint32_t>(0); 3437 BucketOffset = Generator.Emit(Out, Trait); 3438 } 3439 3440 // Create a blob abbreviation 3441 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3442 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL)); 3443 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3444 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3445 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3446 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3447 3448 // Write the method pool 3449 { 3450 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset, 3451 NumTableEntries}; 3452 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool); 3453 } 3454 3455 // Create a blob abbreviation for the selector table offsets. 3456 Abbrev = std::make_shared<BitCodeAbbrev>(); 3457 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS)); 3458 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 3459 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 3460 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3461 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3462 3463 // Write the selector offsets table. 3464 { 3465 RecordData::value_type Record[] = { 3466 SELECTOR_OFFSETS, SelectorOffsets.size(), 3467 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS}; 3468 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record, 3469 bytes(SelectorOffsets)); 3470 } 3471 } 3472 } 3473 3474 /// \brief Write the selectors referenced in @selector expression into AST file. 3475 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) { 3476 using namespace llvm; 3477 3478 if (SemaRef.ReferencedSelectors.empty()) 3479 return; 3480 3481 RecordData Record; 3482 ASTRecordWriter Writer(*this, Record); 3483 3484 // Note: this writes out all references even for a dependent AST. But it is 3485 // very tricky to fix, and given that @selector shouldn't really appear in 3486 // headers, probably not worth it. It's not a correctness issue. 3487 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) { 3488 Selector Sel = SelectorAndLocation.first; 3489 SourceLocation Loc = SelectorAndLocation.second; 3490 Writer.AddSelectorRef(Sel); 3491 Writer.AddSourceLocation(Loc); 3492 } 3493 Writer.Emit(REFERENCED_SELECTOR_POOL); 3494 } 3495 3496 //===----------------------------------------------------------------------===// 3497 // Identifier Table Serialization 3498 //===----------------------------------------------------------------------===// 3499 3500 /// Determine the declaration that should be put into the name lookup table to 3501 /// represent the given declaration in this module. This is usually D itself, 3502 /// but if D was imported and merged into a local declaration, we want the most 3503 /// recent local declaration instead. The chosen declaration will be the most 3504 /// recent declaration in any module that imports this one. 3505 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts, 3506 NamedDecl *D) { 3507 if (!LangOpts.Modules || !D->isFromASTFile()) 3508 return D; 3509 3510 if (Decl *Redecl = D->getPreviousDecl()) { 3511 // For Redeclarable decls, a prior declaration might be local. 3512 for (; Redecl; Redecl = Redecl->getPreviousDecl()) { 3513 // If we find a local decl, we're done. 3514 if (!Redecl->isFromASTFile()) { 3515 // Exception: in very rare cases (for injected-class-names), not all 3516 // redeclarations are in the same semantic context. Skip ones in a 3517 // different context. They don't go in this lookup table at all. 3518 if (!Redecl->getDeclContext()->getRedeclContext()->Equals( 3519 D->getDeclContext()->getRedeclContext())) 3520 continue; 3521 return cast<NamedDecl>(Redecl); 3522 } 3523 3524 // If we find a decl from a (chained-)PCH stop since we won't find a 3525 // local one. 3526 if (Redecl->getOwningModuleID() == 0) 3527 break; 3528 } 3529 } else if (Decl *First = D->getCanonicalDecl()) { 3530 // For Mergeable decls, the first decl might be local. 3531 if (!First->isFromASTFile()) 3532 return cast<NamedDecl>(First); 3533 } 3534 3535 // All declarations are imported. Our most recent declaration will also be 3536 // the most recent one in anyone who imports us. 3537 return D; 3538 } 3539 3540 namespace { 3541 3542 class ASTIdentifierTableTrait { 3543 ASTWriter &Writer; 3544 Preprocessor &PP; 3545 IdentifierResolver &IdResolver; 3546 bool IsModule; 3547 bool NeedDecls; 3548 ASTWriter::RecordData *InterestingIdentifierOffsets; 3549 3550 /// \brief Determines whether this is an "interesting" identifier that needs a 3551 /// full IdentifierInfo structure written into the hash table. Notably, this 3552 /// doesn't check whether the name has macros defined; use PublicMacroIterator 3553 /// to check that. 3554 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) { 3555 if (MacroOffset || 3556 II->isPoisoned() || 3557 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) || 3558 II->hasRevertedTokenIDToIdentifier() || 3559 (NeedDecls && II->getFETokenInfo<void>())) 3560 return true; 3561 3562 return false; 3563 } 3564 3565 public: 3566 using key_type = IdentifierInfo *; 3567 using key_type_ref = key_type; 3568 3569 using data_type = IdentID; 3570 using data_type_ref = data_type; 3571 3572 using hash_value_type = unsigned; 3573 using offset_type = unsigned; 3574 3575 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP, 3576 IdentifierResolver &IdResolver, bool IsModule, 3577 ASTWriter::RecordData *InterestingIdentifierOffsets) 3578 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule), 3579 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus), 3580 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {} 3581 3582 bool needDecls() const { return NeedDecls; } 3583 3584 static hash_value_type ComputeHash(const IdentifierInfo* II) { 3585 return llvm::djbHash(II->getName()); 3586 } 3587 3588 bool isInterestingIdentifier(const IdentifierInfo *II) { 3589 auto MacroOffset = Writer.getMacroDirectivesOffset(II); 3590 return isInterestingIdentifier(II, MacroOffset); 3591 } 3592 3593 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) { 3594 return isInterestingIdentifier(II, 0); 3595 } 3596 3597 std::pair<unsigned, unsigned> 3598 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) { 3599 unsigned KeyLen = II->getLength() + 1; 3600 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1 3601 auto MacroOffset = Writer.getMacroDirectivesOffset(II); 3602 if (isInterestingIdentifier(II, MacroOffset)) { 3603 DataLen += 2; // 2 bytes for builtin ID 3604 DataLen += 2; // 2 bytes for flags 3605 if (MacroOffset) 3606 DataLen += 4; // MacroDirectives offset. 3607 3608 if (NeedDecls) { 3609 for (IdentifierResolver::iterator D = IdResolver.begin(II), 3610 DEnd = IdResolver.end(); 3611 D != DEnd; ++D) 3612 DataLen += 4; 3613 } 3614 } 3615 3616 using namespace llvm::support; 3617 3618 endian::Writer<little> LE(Out); 3619 3620 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen); 3621 LE.write<uint16_t>(DataLen); 3622 // We emit the key length after the data length so that every 3623 // string is preceded by a 16-bit length. This matches the PTH 3624 // format for storing identifiers. 3625 LE.write<uint16_t>(KeyLen); 3626 return std::make_pair(KeyLen, DataLen); 3627 } 3628 3629 void EmitKey(raw_ostream& Out, const IdentifierInfo* II, 3630 unsigned KeyLen) { 3631 // Record the location of the key data. This is used when generating 3632 // the mapping from persistent IDs to strings. 3633 Writer.SetIdentifierOffset(II, Out.tell()); 3634 3635 // Emit the offset of the key/data length information to the interesting 3636 // identifiers table if necessary. 3637 if (InterestingIdentifierOffsets && isInterestingIdentifier(II)) 3638 InterestingIdentifierOffsets->push_back(Out.tell() - 4); 3639 3640 Out.write(II->getNameStart(), KeyLen); 3641 } 3642 3643 void EmitData(raw_ostream& Out, IdentifierInfo* II, 3644 IdentID ID, unsigned) { 3645 using namespace llvm::support; 3646 3647 endian::Writer<little> LE(Out); 3648 3649 auto MacroOffset = Writer.getMacroDirectivesOffset(II); 3650 if (!isInterestingIdentifier(II, MacroOffset)) { 3651 LE.write<uint32_t>(ID << 1); 3652 return; 3653 } 3654 3655 LE.write<uint32_t>((ID << 1) | 0x01); 3656 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID(); 3657 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader."); 3658 LE.write<uint16_t>(Bits); 3659 Bits = 0; 3660 bool HadMacroDefinition = MacroOffset != 0; 3661 Bits = (Bits << 1) | unsigned(HadMacroDefinition); 3662 Bits = (Bits << 1) | unsigned(II->isExtensionToken()); 3663 Bits = (Bits << 1) | unsigned(II->isPoisoned()); 3664 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin()); 3665 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier()); 3666 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword()); 3667 LE.write<uint16_t>(Bits); 3668 3669 if (HadMacroDefinition) 3670 LE.write<uint32_t>(MacroOffset); 3671 3672 if (NeedDecls) { 3673 // Emit the declaration IDs in reverse order, because the 3674 // IdentifierResolver provides the declarations as they would be 3675 // visible (e.g., the function "stat" would come before the struct 3676 // "stat"), but the ASTReader adds declarations to the end of the list 3677 // (so we need to see the struct "stat" before the function "stat"). 3678 // Only emit declarations that aren't from a chained PCH, though. 3679 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II), 3680 IdResolver.end()); 3681 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(), 3682 DEnd = Decls.rend(); 3683 D != DEnd; ++D) 3684 LE.write<uint32_t>( 3685 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D))); 3686 } 3687 } 3688 }; 3689 3690 } // namespace 3691 3692 /// \brief Write the identifier table into the AST file. 3693 /// 3694 /// The identifier table consists of a blob containing string data 3695 /// (the actual identifiers themselves) and a separate "offsets" index 3696 /// that maps identifier IDs to locations within the blob. 3697 void ASTWriter::WriteIdentifierTable(Preprocessor &PP, 3698 IdentifierResolver &IdResolver, 3699 bool IsModule) { 3700 using namespace llvm; 3701 3702 RecordData InterestingIdents; 3703 3704 // Create and write out the blob that contains the identifier 3705 // strings. 3706 { 3707 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator; 3708 ASTIdentifierTableTrait Trait( 3709 *this, PP, IdResolver, IsModule, 3710 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr); 3711 3712 // Look for any identifiers that were named while processing the 3713 // headers, but are otherwise not needed. We add these to the hash 3714 // table to enable checking of the predefines buffer in the case 3715 // where the user adds new macro definitions when building the AST 3716 // file. 3717 SmallVector<const IdentifierInfo *, 128> IIs; 3718 for (const auto &ID : PP.getIdentifierTable()) 3719 IIs.push_back(ID.second); 3720 // Sort the identifiers lexicographically before getting them references so 3721 // that their order is stable. 3722 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>()); 3723 for (const IdentifierInfo *II : IIs) 3724 if (Trait.isInterestingNonMacroIdentifier(II)) 3725 getIdentifierRef(II); 3726 3727 // Create the on-disk hash table representation. We only store offsets 3728 // for identifiers that appear here for the first time. 3729 IdentifierOffsets.resize(NextIdentID - FirstIdentID); 3730 for (auto IdentIDPair : IdentifierIDs) { 3731 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first); 3732 IdentID ID = IdentIDPair.second; 3733 assert(II && "NULL identifier in identifier table"); 3734 // Write out identifiers if either the ID is local or the identifier has 3735 // changed since it was loaded. 3736 if (ID >= FirstIdentID || !Chain || !II->isFromAST() 3737 || II->hasChangedSinceDeserialization() || 3738 (Trait.needDecls() && 3739 II->hasFETokenInfoChangedSinceDeserialization())) 3740 Generator.insert(II, ID, Trait); 3741 } 3742 3743 // Create the on-disk hash table in a buffer. 3744 SmallString<4096> IdentifierTable; 3745 uint32_t BucketOffset; 3746 { 3747 using namespace llvm::support; 3748 3749 llvm::raw_svector_ostream Out(IdentifierTable); 3750 // Make sure that no bucket is at offset 0 3751 endian::Writer<little>(Out).write<uint32_t>(0); 3752 BucketOffset = Generator.Emit(Out, Trait); 3753 } 3754 3755 // Create a blob abbreviation 3756 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3757 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE)); 3758 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3759 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3760 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3761 3762 // Write the identifier table 3763 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset}; 3764 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable); 3765 } 3766 3767 // Write the offsets table for identifier IDs. 3768 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3769 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET)); 3770 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers 3771 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 3772 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3773 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3774 3775 #ifndef NDEBUG 3776 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I) 3777 assert(IdentifierOffsets[I] && "Missing identifier offset?"); 3778 #endif 3779 3780 RecordData::value_type Record[] = {IDENTIFIER_OFFSET, 3781 IdentifierOffsets.size(), 3782 FirstIdentID - NUM_PREDEF_IDENT_IDS}; 3783 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record, 3784 bytes(IdentifierOffsets)); 3785 3786 // In C++, write the list of interesting identifiers (those that are 3787 // defined as macros, poisoned, or similar unusual things). 3788 if (!InterestingIdents.empty()) 3789 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents); 3790 } 3791 3792 //===----------------------------------------------------------------------===// 3793 // DeclContext's Name Lookup Table Serialization 3794 //===----------------------------------------------------------------------===// 3795 3796 namespace { 3797 3798 // Trait used for the on-disk hash table used in the method pool. 3799 class ASTDeclContextNameLookupTrait { 3800 ASTWriter &Writer; 3801 llvm::SmallVector<DeclID, 64> DeclIDs; 3802 3803 public: 3804 using key_type = DeclarationNameKey; 3805 using key_type_ref = key_type; 3806 3807 /// A start and end index into DeclIDs, representing a sequence of decls. 3808 using data_type = std::pair<unsigned, unsigned>; 3809 using data_type_ref = const data_type &; 3810 3811 using hash_value_type = unsigned; 3812 using offset_type = unsigned; 3813 3814 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {} 3815 3816 template<typename Coll> 3817 data_type getData(const Coll &Decls) { 3818 unsigned Start = DeclIDs.size(); 3819 for (NamedDecl *D : Decls) { 3820 DeclIDs.push_back( 3821 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D))); 3822 } 3823 return std::make_pair(Start, DeclIDs.size()); 3824 } 3825 3826 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) { 3827 unsigned Start = DeclIDs.size(); 3828 for (auto ID : FromReader) 3829 DeclIDs.push_back(ID); 3830 return std::make_pair(Start, DeclIDs.size()); 3831 } 3832 3833 static bool EqualKey(key_type_ref a, key_type_ref b) { 3834 return a == b; 3835 } 3836 3837 hash_value_type ComputeHash(DeclarationNameKey Name) { 3838 return Name.getHash(); 3839 } 3840 3841 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const { 3842 assert(Writer.hasChain() && 3843 "have reference to loaded module file but no chain?"); 3844 3845 using namespace llvm::support; 3846 3847 endian::Writer<little>(Out) 3848 .write<uint32_t>(Writer.getChain()->getModuleFileID(F)); 3849 } 3850 3851 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out, 3852 DeclarationNameKey Name, 3853 data_type_ref Lookup) { 3854 using namespace llvm::support; 3855 3856 endian::Writer<little> LE(Out); 3857 unsigned KeyLen = 1; 3858 switch (Name.getKind()) { 3859 case DeclarationName::Identifier: 3860 case DeclarationName::ObjCZeroArgSelector: 3861 case DeclarationName::ObjCOneArgSelector: 3862 case DeclarationName::ObjCMultiArgSelector: 3863 case DeclarationName::CXXLiteralOperatorName: 3864 case DeclarationName::CXXDeductionGuideName: 3865 KeyLen += 4; 3866 break; 3867 case DeclarationName::CXXOperatorName: 3868 KeyLen += 1; 3869 break; 3870 case DeclarationName::CXXConstructorName: 3871 case DeclarationName::CXXDestructorName: 3872 case DeclarationName::CXXConversionFunctionName: 3873 case DeclarationName::CXXUsingDirective: 3874 break; 3875 } 3876 LE.write<uint16_t>(KeyLen); 3877 3878 // 4 bytes for each DeclID. 3879 unsigned DataLen = 4 * (Lookup.second - Lookup.first); 3880 assert(uint16_t(DataLen) == DataLen && 3881 "too many decls for serialized lookup result"); 3882 LE.write<uint16_t>(DataLen); 3883 3884 return std::make_pair(KeyLen, DataLen); 3885 } 3886 3887 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) { 3888 using namespace llvm::support; 3889 3890 endian::Writer<little> LE(Out); 3891 LE.write<uint8_t>(Name.getKind()); 3892 switch (Name.getKind()) { 3893 case DeclarationName::Identifier: 3894 case DeclarationName::CXXLiteralOperatorName: 3895 case DeclarationName::CXXDeductionGuideName: 3896 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier())); 3897 return; 3898 case DeclarationName::ObjCZeroArgSelector: 3899 case DeclarationName::ObjCOneArgSelector: 3900 case DeclarationName::ObjCMultiArgSelector: 3901 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector())); 3902 return; 3903 case DeclarationName::CXXOperatorName: 3904 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS && 3905 "Invalid operator?"); 3906 LE.write<uint8_t>(Name.getOperatorKind()); 3907 return; 3908 case DeclarationName::CXXConstructorName: 3909 case DeclarationName::CXXDestructorName: 3910 case DeclarationName::CXXConversionFunctionName: 3911 case DeclarationName::CXXUsingDirective: 3912 return; 3913 } 3914 3915 llvm_unreachable("Invalid name kind?"); 3916 } 3917 3918 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup, 3919 unsigned DataLen) { 3920 using namespace llvm::support; 3921 3922 endian::Writer<little> LE(Out); 3923 uint64_t Start = Out.tell(); (void)Start; 3924 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I) 3925 LE.write<uint32_t>(DeclIDs[I]); 3926 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 3927 } 3928 }; 3929 3930 } // namespace 3931 3932 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result, 3933 DeclContext *DC) { 3934 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage; 3935 } 3936 3937 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result, 3938 DeclContext *DC) { 3939 for (auto *D : Result.getLookupResult()) 3940 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile()) 3941 return false; 3942 3943 return true; 3944 } 3945 3946 void 3947 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC, 3948 llvm::SmallVectorImpl<char> &LookupTable) { 3949 assert(!ConstDC->HasLazyLocalLexicalLookups && 3950 !ConstDC->HasLazyExternalLexicalLookups && 3951 "must call buildLookups first"); 3952 3953 // FIXME: We need to build the lookups table, which is logically const. 3954 auto *DC = const_cast<DeclContext*>(ConstDC); 3955 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table"); 3956 3957 // Create the on-disk hash table representation. 3958 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait, 3959 ASTDeclContextNameLookupTrait> Generator; 3960 ASTDeclContextNameLookupTrait Trait(*this); 3961 3962 // The first step is to collect the declaration names which we need to 3963 // serialize into the name lookup table, and to collect them in a stable 3964 // order. 3965 SmallVector<DeclarationName, 16> Names; 3966 3967 // We also build up small sets of the constructor and conversion function 3968 // names which are visible. 3969 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet; 3970 3971 for (auto &Lookup : *DC->buildLookup()) { 3972 auto &Name = Lookup.first; 3973 auto &Result = Lookup.second; 3974 3975 // If there are no local declarations in our lookup result, we 3976 // don't need to write an entry for the name at all. If we can't 3977 // write out a lookup set without performing more deserialization, 3978 // just skip this entry. 3979 if (isLookupResultExternal(Result, DC) && 3980 isLookupResultEntirelyExternal(Result, DC)) 3981 continue; 3982 3983 // We also skip empty results. If any of the results could be external and 3984 // the currently available results are empty, then all of the results are 3985 // external and we skip it above. So the only way we get here with an empty 3986 // results is when no results could have been external *and* we have 3987 // external results. 3988 // 3989 // FIXME: While we might want to start emitting on-disk entries for negative 3990 // lookups into a decl context as an optimization, today we *have* to skip 3991 // them because there are names with empty lookup results in decl contexts 3992 // which we can't emit in any stable ordering: we lookup constructors and 3993 // conversion functions in the enclosing namespace scope creating empty 3994 // results for them. This in almost certainly a bug in Clang's name lookup, 3995 // but that is likely to be hard or impossible to fix and so we tolerate it 3996 // here by omitting lookups with empty results. 3997 if (Lookup.second.getLookupResult().empty()) 3998 continue; 3999 4000 switch (Lookup.first.getNameKind()) { 4001 default: 4002 Names.push_back(Lookup.first); 4003 break; 4004 4005 case DeclarationName::CXXConstructorName: 4006 assert(isa<CXXRecordDecl>(DC) && 4007 "Cannot have a constructor name outside of a class!"); 4008 ConstructorNameSet.insert(Name); 4009 break; 4010 4011 case DeclarationName::CXXConversionFunctionName: 4012 assert(isa<CXXRecordDecl>(DC) && 4013 "Cannot have a conversion function name outside of a class!"); 4014 ConversionNameSet.insert(Name); 4015 break; 4016 } 4017 } 4018 4019 // Sort the names into a stable order. 4020 std::sort(Names.begin(), Names.end()); 4021 4022 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) { 4023 // We need to establish an ordering of constructor and conversion function 4024 // names, and they don't have an intrinsic ordering. 4025 4026 // First we try the easy case by forming the current context's constructor 4027 // name and adding that name first. This is a very useful optimization to 4028 // avoid walking the lexical declarations in many cases, and it also 4029 // handles the only case where a constructor name can come from some other 4030 // lexical context -- when that name is an implicit constructor merged from 4031 // another declaration in the redecl chain. Any non-implicit constructor or 4032 // conversion function which doesn't occur in all the lexical contexts 4033 // would be an ODR violation. 4034 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName( 4035 Context->getCanonicalType(Context->getRecordType(D))); 4036 if (ConstructorNameSet.erase(ImplicitCtorName)) 4037 Names.push_back(ImplicitCtorName); 4038 4039 // If we still have constructors or conversion functions, we walk all the 4040 // names in the decl and add the constructors and conversion functions 4041 // which are visible in the order they lexically occur within the context. 4042 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty()) 4043 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls()) 4044 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) { 4045 auto Name = ChildND->getDeclName(); 4046 switch (Name.getNameKind()) { 4047 default: 4048 continue; 4049 4050 case DeclarationName::CXXConstructorName: 4051 if (ConstructorNameSet.erase(Name)) 4052 Names.push_back(Name); 4053 break; 4054 4055 case DeclarationName::CXXConversionFunctionName: 4056 if (ConversionNameSet.erase(Name)) 4057 Names.push_back(Name); 4058 break; 4059 } 4060 4061 if (ConstructorNameSet.empty() && ConversionNameSet.empty()) 4062 break; 4063 } 4064 4065 assert(ConstructorNameSet.empty() && "Failed to find all of the visible " 4066 "constructors by walking all the " 4067 "lexical members of the context."); 4068 assert(ConversionNameSet.empty() && "Failed to find all of the visible " 4069 "conversion functions by walking all " 4070 "the lexical members of the context."); 4071 } 4072 4073 // Next we need to do a lookup with each name into this decl context to fully 4074 // populate any results from external sources. We don't actually use the 4075 // results of these lookups because we only want to use the results after all 4076 // results have been loaded and the pointers into them will be stable. 4077 for (auto &Name : Names) 4078 DC->lookup(Name); 4079 4080 // Now we need to insert the results for each name into the hash table. For 4081 // constructor names and conversion function names, we actually need to merge 4082 // all of the results for them into one list of results each and insert 4083 // those. 4084 SmallVector<NamedDecl *, 8> ConstructorDecls; 4085 SmallVector<NamedDecl *, 8> ConversionDecls; 4086 4087 // Now loop over the names, either inserting them or appending for the two 4088 // special cases. 4089 for (auto &Name : Names) { 4090 DeclContext::lookup_result Result = DC->noload_lookup(Name); 4091 4092 switch (Name.getNameKind()) { 4093 default: 4094 Generator.insert(Name, Trait.getData(Result), Trait); 4095 break; 4096 4097 case DeclarationName::CXXConstructorName: 4098 ConstructorDecls.append(Result.begin(), Result.end()); 4099 break; 4100 4101 case DeclarationName::CXXConversionFunctionName: 4102 ConversionDecls.append(Result.begin(), Result.end()); 4103 break; 4104 } 4105 } 4106 4107 // Handle our two special cases if we ended up having any. We arbitrarily use 4108 // the first declaration's name here because the name itself isn't part of 4109 // the key, only the kind of name is used. 4110 if (!ConstructorDecls.empty()) 4111 Generator.insert(ConstructorDecls.front()->getDeclName(), 4112 Trait.getData(ConstructorDecls), Trait); 4113 if (!ConversionDecls.empty()) 4114 Generator.insert(ConversionDecls.front()->getDeclName(), 4115 Trait.getData(ConversionDecls), Trait); 4116 4117 // Create the on-disk hash table. Also emit the existing imported and 4118 // merged table if there is one. 4119 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr; 4120 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr); 4121 } 4122 4123 /// \brief Write the block containing all of the declaration IDs 4124 /// visible from the given DeclContext. 4125 /// 4126 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the 4127 /// bitstream, or 0 if no block was written. 4128 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context, 4129 DeclContext *DC) { 4130 // If we imported a key declaration of this namespace, write the visible 4131 // lookup results as an update record for it rather than including them 4132 // on this declaration. We will only look at key declarations on reload. 4133 if (isa<NamespaceDecl>(DC) && Chain && 4134 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) { 4135 // Only do this once, for the first local declaration of the namespace. 4136 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev; 4137 Prev = Prev->getPreviousDecl()) 4138 if (!Prev->isFromASTFile()) 4139 return 0; 4140 4141 // Note that we need to emit an update record for the primary context. 4142 UpdatedDeclContexts.insert(DC->getPrimaryContext()); 4143 4144 // Make sure all visible decls are written. They will be recorded later. We 4145 // do this using a side data structure so we can sort the names into 4146 // a deterministic order. 4147 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup(); 4148 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16> 4149 LookupResults; 4150 if (Map) { 4151 LookupResults.reserve(Map->size()); 4152 for (auto &Entry : *Map) 4153 LookupResults.push_back( 4154 std::make_pair(Entry.first, Entry.second.getLookupResult())); 4155 } 4156 4157 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first()); 4158 for (auto &NameAndResult : LookupResults) { 4159 DeclarationName Name = NameAndResult.first; 4160 DeclContext::lookup_result Result = NameAndResult.second; 4161 if (Name.getNameKind() == DeclarationName::CXXConstructorName || 4162 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 4163 // We have to work around a name lookup bug here where negative lookup 4164 // results for these names get cached in namespace lookup tables (these 4165 // names should never be looked up in a namespace). 4166 assert(Result.empty() && "Cannot have a constructor or conversion " 4167 "function name in a namespace!"); 4168 continue; 4169 } 4170 4171 for (NamedDecl *ND : Result) 4172 if (!ND->isFromASTFile()) 4173 GetDeclRef(ND); 4174 } 4175 4176 return 0; 4177 } 4178 4179 if (DC->getPrimaryContext() != DC) 4180 return 0; 4181 4182 // Skip contexts which don't support name lookup. 4183 if (!DC->isLookupContext()) 4184 return 0; 4185 4186 // If not in C++, we perform name lookup for the translation unit via the 4187 // IdentifierInfo chains, don't bother to build a visible-declarations table. 4188 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus) 4189 return 0; 4190 4191 // Serialize the contents of the mapping used for lookup. Note that, 4192 // although we have two very different code paths, the serialized 4193 // representation is the same for both cases: a declaration name, 4194 // followed by a size, followed by references to the visible 4195 // declarations that have that name. 4196 uint64_t Offset = Stream.GetCurrentBitNo(); 4197 StoredDeclsMap *Map = DC->buildLookup(); 4198 if (!Map || Map->empty()) 4199 return 0; 4200 4201 // Create the on-disk hash table in a buffer. 4202 SmallString<4096> LookupTable; 4203 GenerateNameLookupTable(DC, LookupTable); 4204 4205 // Write the lookup table 4206 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE}; 4207 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record, 4208 LookupTable); 4209 ++NumVisibleDeclContexts; 4210 return Offset; 4211 } 4212 4213 /// \brief Write an UPDATE_VISIBLE block for the given context. 4214 /// 4215 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing 4216 /// DeclContext in a dependent AST file. As such, they only exist for the TU 4217 /// (in C++), for namespaces, and for classes with forward-declared unscoped 4218 /// enumeration members (in C++11). 4219 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) { 4220 StoredDeclsMap *Map = DC->getLookupPtr(); 4221 if (!Map || Map->empty()) 4222 return; 4223 4224 // Create the on-disk hash table in a buffer. 4225 SmallString<4096> LookupTable; 4226 GenerateNameLookupTable(DC, LookupTable); 4227 4228 // If we're updating a namespace, select a key declaration as the key for the 4229 // update record; those are the only ones that will be checked on reload. 4230 if (isa<NamespaceDecl>(DC)) 4231 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC))); 4232 4233 // Write the lookup table 4234 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))}; 4235 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable); 4236 } 4237 4238 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions. 4239 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) { 4240 RecordData::value_type Record[] = {Opts.getInt()}; 4241 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record); 4242 } 4243 4244 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions. 4245 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) { 4246 if (!SemaRef.Context.getLangOpts().OpenCL) 4247 return; 4248 4249 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions(); 4250 RecordData Record; 4251 for (const auto &I:Opts.OptMap) { 4252 AddString(I.getKey(), Record); 4253 auto V = I.getValue(); 4254 Record.push_back(V.Supported ? 1 : 0); 4255 Record.push_back(V.Enabled ? 1 : 0); 4256 Record.push_back(V.Avail); 4257 Record.push_back(V.Core); 4258 } 4259 Stream.EmitRecord(OPENCL_EXTENSIONS, Record); 4260 } 4261 4262 void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) { 4263 if (!SemaRef.Context.getLangOpts().OpenCL) 4264 return; 4265 4266 RecordData Record; 4267 for (const auto &I : SemaRef.OpenCLTypeExtMap) { 4268 Record.push_back( 4269 static_cast<unsigned>(getTypeID(I.first->getCanonicalTypeInternal()))); 4270 Record.push_back(I.second.size()); 4271 for (auto Ext : I.second) 4272 AddString(Ext, Record); 4273 } 4274 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record); 4275 } 4276 4277 void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) { 4278 if (!SemaRef.Context.getLangOpts().OpenCL) 4279 return; 4280 4281 RecordData Record; 4282 for (const auto &I : SemaRef.OpenCLDeclExtMap) { 4283 Record.push_back(getDeclID(I.first)); 4284 Record.push_back(static_cast<unsigned>(I.second.size())); 4285 for (auto Ext : I.second) 4286 AddString(Ext, Record); 4287 } 4288 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record); 4289 } 4290 4291 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) { 4292 if (SemaRef.ForceCUDAHostDeviceDepth > 0) { 4293 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth}; 4294 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record); 4295 } 4296 } 4297 4298 void ASTWriter::WriteObjCCategories() { 4299 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap; 4300 RecordData Categories; 4301 4302 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) { 4303 unsigned Size = 0; 4304 unsigned StartIndex = Categories.size(); 4305 4306 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I]; 4307 4308 // Allocate space for the size. 4309 Categories.push_back(0); 4310 4311 // Add the categories. 4312 for (ObjCInterfaceDecl::known_categories_iterator 4313 Cat = Class->known_categories_begin(), 4314 CatEnd = Class->known_categories_end(); 4315 Cat != CatEnd; ++Cat, ++Size) { 4316 assert(getDeclID(*Cat) != 0 && "Bogus category"); 4317 AddDeclRef(*Cat, Categories); 4318 } 4319 4320 // Update the size. 4321 Categories[StartIndex] = Size; 4322 4323 // Record this interface -> category map. 4324 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex }; 4325 CategoriesMap.push_back(CatInfo); 4326 } 4327 4328 // Sort the categories map by the definition ID, since the reader will be 4329 // performing binary searches on this information. 4330 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end()); 4331 4332 // Emit the categories map. 4333 using namespace llvm; 4334 4335 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 4336 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP)); 4337 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries 4338 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 4339 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev)); 4340 4341 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()}; 4342 Stream.EmitRecordWithBlob(AbbrevID, Record, 4343 reinterpret_cast<char *>(CategoriesMap.data()), 4344 CategoriesMap.size() * sizeof(ObjCCategoriesInfo)); 4345 4346 // Emit the category lists. 4347 Stream.EmitRecord(OBJC_CATEGORIES, Categories); 4348 } 4349 4350 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) { 4351 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap; 4352 4353 if (LPTMap.empty()) 4354 return; 4355 4356 RecordData Record; 4357 for (auto &LPTMapEntry : LPTMap) { 4358 const FunctionDecl *FD = LPTMapEntry.first; 4359 LateParsedTemplate &LPT = *LPTMapEntry.second; 4360 AddDeclRef(FD, Record); 4361 AddDeclRef(LPT.D, Record); 4362 Record.push_back(LPT.Toks.size()); 4363 4364 for (const auto &Tok : LPT.Toks) { 4365 AddToken(Tok, Record); 4366 } 4367 } 4368 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record); 4369 } 4370 4371 /// \brief Write the state of 'pragma clang optimize' at the end of the module. 4372 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) { 4373 RecordData Record; 4374 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation(); 4375 AddSourceLocation(PragmaLoc, Record); 4376 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record); 4377 } 4378 4379 /// \brief Write the state of 'pragma ms_struct' at the end of the module. 4380 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) { 4381 RecordData Record; 4382 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF); 4383 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record); 4384 } 4385 4386 /// \brief Write the state of 'pragma pointers_to_members' at the end of the 4387 //module. 4388 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) { 4389 RecordData Record; 4390 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod); 4391 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record); 4392 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record); 4393 } 4394 4395 /// \brief Write the state of 'pragma pack' at the end of the module. 4396 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) { 4397 // Don't serialize pragma pack state for modules, since it should only take 4398 // effect on a per-submodule basis. 4399 if (WritingModule) 4400 return; 4401 4402 RecordData Record; 4403 Record.push_back(SemaRef.PackStack.CurrentValue); 4404 AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record); 4405 Record.push_back(SemaRef.PackStack.Stack.size()); 4406 for (const auto &StackEntry : SemaRef.PackStack.Stack) { 4407 Record.push_back(StackEntry.Value); 4408 AddSourceLocation(StackEntry.PragmaLocation, Record); 4409 AddSourceLocation(StackEntry.PragmaPushLocation, Record); 4410 AddString(StackEntry.StackSlotLabel, Record); 4411 } 4412 Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record); 4413 } 4414 4415 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef, 4416 ModuleFileExtensionWriter &Writer) { 4417 // Enter the extension block. 4418 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4); 4419 4420 // Emit the metadata record abbreviation. 4421 auto Abv = std::make_shared<llvm::BitCodeAbbrev>(); 4422 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA)); 4423 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4424 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4425 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4426 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4427 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4428 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv)); 4429 4430 // Emit the metadata record. 4431 RecordData Record; 4432 auto Metadata = Writer.getExtension()->getExtensionMetadata(); 4433 Record.push_back(EXTENSION_METADATA); 4434 Record.push_back(Metadata.MajorVersion); 4435 Record.push_back(Metadata.MinorVersion); 4436 Record.push_back(Metadata.BlockName.size()); 4437 Record.push_back(Metadata.UserInfo.size()); 4438 SmallString<64> Buffer; 4439 Buffer += Metadata.BlockName; 4440 Buffer += Metadata.UserInfo; 4441 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer); 4442 4443 // Emit the contents of the extension block. 4444 Writer.writeExtensionContents(SemaRef, Stream); 4445 4446 // Exit the extension block. 4447 Stream.ExitBlock(); 4448 } 4449 4450 //===----------------------------------------------------------------------===// 4451 // General Serialization Routines 4452 //===----------------------------------------------------------------------===// 4453 4454 /// \brief Emit the list of attributes to the specified record. 4455 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) { 4456 auto &Record = *this; 4457 Record.push_back(Attrs.size()); 4458 for (const auto *A : Attrs) { 4459 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs 4460 Record.AddSourceRange(A->getRange()); 4461 4462 #include "clang/Serialization/AttrPCHWrite.inc" 4463 } 4464 } 4465 4466 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) { 4467 AddSourceLocation(Tok.getLocation(), Record); 4468 Record.push_back(Tok.getLength()); 4469 4470 // FIXME: When reading literal tokens, reconstruct the literal pointer 4471 // if it is needed. 4472 AddIdentifierRef(Tok.getIdentifierInfo(), Record); 4473 // FIXME: Should translate token kind to a stable encoding. 4474 Record.push_back(Tok.getKind()); 4475 // FIXME: Should translate token flags to a stable encoding. 4476 Record.push_back(Tok.getFlags()); 4477 } 4478 4479 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) { 4480 Record.push_back(Str.size()); 4481 Record.insert(Record.end(), Str.begin(), Str.end()); 4482 } 4483 4484 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) { 4485 assert(Context && "should have context when outputting path"); 4486 4487 bool Changed = 4488 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path); 4489 4490 // Remove a prefix to make the path relative, if relevant. 4491 const char *PathBegin = Path.data(); 4492 const char *PathPtr = 4493 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory); 4494 if (PathPtr != PathBegin) { 4495 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin)); 4496 Changed = true; 4497 } 4498 4499 return Changed; 4500 } 4501 4502 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) { 4503 SmallString<128> FilePath(Path); 4504 PreparePathForOutput(FilePath); 4505 AddString(FilePath, Record); 4506 } 4507 4508 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record, 4509 StringRef Path) { 4510 SmallString<128> FilePath(Path); 4511 PreparePathForOutput(FilePath); 4512 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath); 4513 } 4514 4515 void ASTWriter::AddVersionTuple(const VersionTuple &Version, 4516 RecordDataImpl &Record) { 4517 Record.push_back(Version.getMajor()); 4518 if (Optional<unsigned> Minor = Version.getMinor()) 4519 Record.push_back(*Minor + 1); 4520 else 4521 Record.push_back(0); 4522 if (Optional<unsigned> Subminor = Version.getSubminor()) 4523 Record.push_back(*Subminor + 1); 4524 else 4525 Record.push_back(0); 4526 } 4527 4528 /// \brief Note that the identifier II occurs at the given offset 4529 /// within the identifier table. 4530 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) { 4531 IdentID ID = IdentifierIDs[II]; 4532 // Only store offsets new to this AST file. Other identifier names are looked 4533 // up earlier in the chain and thus don't need an offset. 4534 if (ID >= FirstIdentID) 4535 IdentifierOffsets[ID - FirstIdentID] = Offset; 4536 } 4537 4538 /// \brief Note that the selector Sel occurs at the given offset 4539 /// within the method pool/selector table. 4540 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { 4541 unsigned ID = SelectorIDs[Sel]; 4542 assert(ID && "Unknown selector"); 4543 // Don't record offsets for selectors that are also available in a different 4544 // file. 4545 if (ID < FirstSelectorID) 4546 return; 4547 SelectorOffsets[ID - FirstSelectorID] = Offset; 4548 } 4549 4550 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream, 4551 SmallVectorImpl<char> &Buffer, MemoryBufferCache &PCMCache, 4552 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 4553 bool IncludeTimestamps) 4554 : Stream(Stream), Buffer(Buffer), PCMCache(PCMCache), 4555 IncludeTimestamps(IncludeTimestamps) { 4556 for (const auto &Ext : Extensions) { 4557 if (auto Writer = Ext->createExtensionWriter(*this)) 4558 ModuleFileExtensionWriters.push_back(std::move(Writer)); 4559 } 4560 } 4561 4562 ASTWriter::~ASTWriter() { 4563 llvm::DeleteContainerSeconds(FileDeclIDs); 4564 } 4565 4566 const LangOptions &ASTWriter::getLangOpts() const { 4567 assert(WritingAST && "can't determine lang opts when not writing AST"); 4568 return Context->getLangOpts(); 4569 } 4570 4571 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const { 4572 return IncludeTimestamps ? E->getModificationTime() : 0; 4573 } 4574 4575 ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef, 4576 const std::string &OutputFile, 4577 Module *WritingModule, StringRef isysroot, 4578 bool hasErrors) { 4579 WritingAST = true; 4580 4581 ASTHasCompilerErrors = hasErrors; 4582 4583 // Emit the file header. 4584 Stream.Emit((unsigned)'C', 8); 4585 Stream.Emit((unsigned)'P', 8); 4586 Stream.Emit((unsigned)'C', 8); 4587 Stream.Emit((unsigned)'H', 8); 4588 4589 WriteBlockInfoBlock(); 4590 4591 Context = &SemaRef.Context; 4592 PP = &SemaRef.PP; 4593 this->WritingModule = WritingModule; 4594 ASTFileSignature Signature = 4595 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule); 4596 Context = nullptr; 4597 PP = nullptr; 4598 this->WritingModule = nullptr; 4599 this->BaseDirectory.clear(); 4600 4601 WritingAST = false; 4602 if (SemaRef.Context.getLangOpts().ImplicitModules && WritingModule) { 4603 // Construct MemoryBuffer and update buffer manager. 4604 PCMCache.addBuffer(OutputFile, 4605 llvm::MemoryBuffer::getMemBufferCopy( 4606 StringRef(Buffer.begin(), Buffer.size()))); 4607 } 4608 return Signature; 4609 } 4610 4611 template<typename Vector> 4612 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, 4613 ASTWriter::RecordData &Record) { 4614 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end(); 4615 I != E; ++I) { 4616 Writer.AddDeclRef(*I, Record); 4617 } 4618 } 4619 4620 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot, 4621 const std::string &OutputFile, 4622 Module *WritingModule) { 4623 using namespace llvm; 4624 4625 bool isModule = WritingModule != nullptr; 4626 4627 // Make sure that the AST reader knows to finalize itself. 4628 if (Chain) 4629 Chain->finalizeForWriting(); 4630 4631 ASTContext &Context = SemaRef.Context; 4632 Preprocessor &PP = SemaRef.PP; 4633 4634 // Set up predefined declaration IDs. 4635 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) { 4636 if (D) { 4637 assert(D->isCanonicalDecl() && "predefined decl is not canonical"); 4638 DeclIDs[D] = ID; 4639 } 4640 }; 4641 RegisterPredefDecl(Context.getTranslationUnitDecl(), 4642 PREDEF_DECL_TRANSLATION_UNIT_ID); 4643 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID); 4644 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID); 4645 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID); 4646 RegisterPredefDecl(Context.ObjCProtocolClassDecl, 4647 PREDEF_DECL_OBJC_PROTOCOL_ID); 4648 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID); 4649 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID); 4650 RegisterPredefDecl(Context.ObjCInstanceTypeDecl, 4651 PREDEF_DECL_OBJC_INSTANCETYPE_ID); 4652 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID); 4653 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG); 4654 RegisterPredefDecl(Context.BuiltinMSVaListDecl, 4655 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID); 4656 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID); 4657 RegisterPredefDecl(Context.MakeIntegerSeqDecl, 4658 PREDEF_DECL_MAKE_INTEGER_SEQ_ID); 4659 RegisterPredefDecl(Context.CFConstantStringTypeDecl, 4660 PREDEF_DECL_CF_CONSTANT_STRING_ID); 4661 RegisterPredefDecl(Context.CFConstantStringTagDecl, 4662 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID); 4663 RegisterPredefDecl(Context.TypePackElementDecl, 4664 PREDEF_DECL_TYPE_PACK_ELEMENT_ID); 4665 4666 // Build a record containing all of the tentative definitions in this file, in 4667 // TentativeDefinitions order. Generally, this record will be empty for 4668 // headers. 4669 RecordData TentativeDefinitions; 4670 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions); 4671 4672 // Build a record containing all of the file scoped decls in this file. 4673 RecordData UnusedFileScopedDecls; 4674 if (!isModule) 4675 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls, 4676 UnusedFileScopedDecls); 4677 4678 // Build a record containing all of the delegating constructors we still need 4679 // to resolve. 4680 RecordData DelegatingCtorDecls; 4681 if (!isModule) 4682 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls); 4683 4684 // Write the set of weak, undeclared identifiers. We always write the 4685 // entire table, since later PCH files in a PCH chain are only interested in 4686 // the results at the end of the chain. 4687 RecordData WeakUndeclaredIdentifiers; 4688 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) { 4689 IdentifierInfo *II = WeakUndeclaredIdentifier.first; 4690 WeakInfo &WI = WeakUndeclaredIdentifier.second; 4691 AddIdentifierRef(II, WeakUndeclaredIdentifiers); 4692 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers); 4693 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers); 4694 WeakUndeclaredIdentifiers.push_back(WI.getUsed()); 4695 } 4696 4697 // Build a record containing all of the ext_vector declarations. 4698 RecordData ExtVectorDecls; 4699 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls); 4700 4701 // Build a record containing all of the VTable uses information. 4702 RecordData VTableUses; 4703 if (!SemaRef.VTableUses.empty()) { 4704 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 4705 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 4706 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 4707 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 4708 } 4709 } 4710 4711 // Build a record containing all of the UnusedLocalTypedefNameCandidates. 4712 RecordData UnusedLocalTypedefNameCandidates; 4713 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates) 4714 AddDeclRef(TD, UnusedLocalTypedefNameCandidates); 4715 4716 // Build a record containing all of pending implicit instantiations. 4717 RecordData PendingInstantiations; 4718 for (const auto &I : SemaRef.PendingInstantiations) { 4719 AddDeclRef(I.first, PendingInstantiations); 4720 AddSourceLocation(I.second, PendingInstantiations); 4721 } 4722 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 4723 "There are local ones at end of translation unit!"); 4724 4725 // Build a record containing some declaration references. 4726 RecordData SemaDeclRefs; 4727 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) { 4728 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 4729 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 4730 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs); 4731 } 4732 4733 RecordData CUDASpecialDeclRefs; 4734 if (Context.getcudaConfigureCallDecl()) { 4735 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs); 4736 } 4737 4738 // Build a record containing all of the known namespaces. 4739 RecordData KnownNamespaces; 4740 for (const auto &I : SemaRef.KnownNamespaces) { 4741 if (!I.second) 4742 AddDeclRef(I.first, KnownNamespaces); 4743 } 4744 4745 // Build a record of all used, undefined objects that require definitions. 4746 RecordData UndefinedButUsed; 4747 4748 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; 4749 SemaRef.getUndefinedButUsed(Undefined); 4750 for (const auto &I : Undefined) { 4751 AddDeclRef(I.first, UndefinedButUsed); 4752 AddSourceLocation(I.second, UndefinedButUsed); 4753 } 4754 4755 // Build a record containing all delete-expressions that we would like to 4756 // analyze later in AST. 4757 RecordData DeleteExprsToAnalyze; 4758 4759 for (const auto &DeleteExprsInfo : 4760 SemaRef.getMismatchingDeleteExpressions()) { 4761 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze); 4762 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size()); 4763 for (const auto &DeleteLoc : DeleteExprsInfo.second) { 4764 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze); 4765 DeleteExprsToAnalyze.push_back(DeleteLoc.second); 4766 } 4767 } 4768 4769 // Write the control block 4770 WriteControlBlock(PP, Context, isysroot, OutputFile); 4771 4772 // Write the remaining AST contents. 4773 Stream.EnterSubblock(AST_BLOCK_ID, 5); 4774 4775 // This is so that older clang versions, before the introduction 4776 // of the control block, can read and reject the newer PCH format. 4777 { 4778 RecordData Record = {VERSION_MAJOR}; 4779 Stream.EmitRecord(METADATA_OLD_FORMAT, Record); 4780 } 4781 4782 // Create a lexical update block containing all of the declarations in the 4783 // translation unit that do not come from other AST files. 4784 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 4785 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs; 4786 for (const auto *D : TU->noload_decls()) { 4787 if (!D->isFromASTFile()) { 4788 NewGlobalKindDeclPairs.push_back(D->getKind()); 4789 NewGlobalKindDeclPairs.push_back(GetDeclRef(D)); 4790 } 4791 } 4792 4793 auto Abv = std::make_shared<BitCodeAbbrev>(); 4794 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL)); 4795 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4796 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv)); 4797 { 4798 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL}; 4799 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, 4800 bytes(NewGlobalKindDeclPairs)); 4801 } 4802 4803 // And a visible updates block for the translation unit. 4804 Abv = std::make_shared<BitCodeAbbrev>(); 4805 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE)); 4806 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4807 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4808 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv)); 4809 WriteDeclContextVisibleUpdate(TU); 4810 4811 // If we have any extern "C" names, write out a visible update for them. 4812 if (Context.ExternCContext) 4813 WriteDeclContextVisibleUpdate(Context.ExternCContext); 4814 4815 // If the translation unit has an anonymous namespace, and we don't already 4816 // have an update block for it, write it as an update block. 4817 // FIXME: Why do we not do this if there's already an update block? 4818 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) { 4819 ASTWriter::UpdateRecord &Record = DeclUpdates[TU]; 4820 if (Record.empty()) 4821 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS)); 4822 } 4823 4824 // Add update records for all mangling numbers and static local numbers. 4825 // These aren't really update records, but this is a convenient way of 4826 // tagging this rare extra data onto the declarations. 4827 for (const auto &Number : Context.MangleNumbers) 4828 if (!Number.first->isFromASTFile()) 4829 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER, 4830 Number.second)); 4831 for (const auto &Number : Context.StaticLocalNumbers) 4832 if (!Number.first->isFromASTFile()) 4833 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER, 4834 Number.second)); 4835 4836 // Make sure visible decls, added to DeclContexts previously loaded from 4837 // an AST file, are registered for serialization. Likewise for template 4838 // specializations added to imported templates. 4839 for (const auto *I : DeclsToEmitEvenIfUnreferenced) { 4840 GetDeclRef(I); 4841 } 4842 4843 // Make sure all decls associated with an identifier are registered for 4844 // serialization, if we're storing decls with identifiers. 4845 if (!WritingModule || !getLangOpts().CPlusPlus) { 4846 llvm::SmallVector<const IdentifierInfo*, 256> IIs; 4847 for (const auto &ID : PP.getIdentifierTable()) { 4848 const IdentifierInfo *II = ID.second; 4849 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization()) 4850 IIs.push_back(II); 4851 } 4852 // Sort the identifiers to visit based on their name. 4853 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>()); 4854 for (const IdentifierInfo *II : IIs) { 4855 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II), 4856 DEnd = SemaRef.IdResolver.end(); 4857 D != DEnd; ++D) { 4858 GetDeclRef(*D); 4859 } 4860 } 4861 } 4862 4863 // For method pool in the module, if it contains an entry for a selector, 4864 // the entry should be complete, containing everything introduced by that 4865 // module and all modules it imports. It's possible that the entry is out of 4866 // date, so we need to pull in the new content here. 4867 4868 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be 4869 // safe, we copy all selectors out. 4870 llvm::SmallVector<Selector, 256> AllSelectors; 4871 for (auto &SelectorAndID : SelectorIDs) 4872 AllSelectors.push_back(SelectorAndID.first); 4873 for (auto &Selector : AllSelectors) 4874 SemaRef.updateOutOfDateSelector(Selector); 4875 4876 // Form the record of special types. 4877 RecordData SpecialTypes; 4878 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes); 4879 AddTypeRef(Context.getFILEType(), SpecialTypes); 4880 AddTypeRef(Context.getjmp_bufType(), SpecialTypes); 4881 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes); 4882 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes); 4883 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes); 4884 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes); 4885 AddTypeRef(Context.getucontext_tType(), SpecialTypes); 4886 4887 if (Chain) { 4888 // Write the mapping information describing our module dependencies and how 4889 // each of those modules were mapped into our own offset/ID space, so that 4890 // the reader can build the appropriate mapping to its own offset/ID space. 4891 // The map consists solely of a blob with the following format: 4892 // *(module-kind:i8 4893 // module-name-len:i16 module-name:len*i8 4894 // source-location-offset:i32 4895 // identifier-id:i32 4896 // preprocessed-entity-id:i32 4897 // macro-definition-id:i32 4898 // submodule-id:i32 4899 // selector-id:i32 4900 // declaration-id:i32 4901 // c++-base-specifiers-id:i32 4902 // type-id:i32) 4903 // 4904 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or 4905 // MK_ExplicitModule, then the module-name is the module name. Otherwise, 4906 // it is the module file name. 4907 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 4908 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP)); 4909 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 4910 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 4911 SmallString<2048> Buffer; 4912 { 4913 llvm::raw_svector_ostream Out(Buffer); 4914 for (ModuleFile &M : Chain->ModuleMgr) { 4915 using namespace llvm::support; 4916 4917 endian::Writer<little> LE(Out); 4918 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind)); 4919 StringRef Name = 4920 M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule 4921 ? M.ModuleName 4922 : M.FileName; 4923 LE.write<uint16_t>(Name.size()); 4924 Out.write(Name.data(), Name.size()); 4925 4926 // Note: if a base ID was uint max, it would not be possible to load 4927 // another module after it or have more than one entity inside it. 4928 uint32_t None = std::numeric_limits<uint32_t>::max(); 4929 4930 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) { 4931 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high"); 4932 if (ShouldWrite) 4933 LE.write<uint32_t>(BaseID); 4934 else 4935 LE.write<uint32_t>(None); 4936 }; 4937 4938 // These values should be unique within a chain, since they will be read 4939 // as keys into ContinuousRangeMaps. 4940 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries); 4941 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers); 4942 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros); 4943 writeBaseIDOrNone(M.BasePreprocessedEntityID, 4944 M.NumPreprocessedEntities); 4945 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules); 4946 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors); 4947 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls); 4948 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes); 4949 } 4950 } 4951 RecordData::value_type Record[] = {MODULE_OFFSET_MAP}; 4952 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record, 4953 Buffer.data(), Buffer.size()); 4954 } 4955 4956 RecordData DeclUpdatesOffsetsRecord; 4957 4958 // Keep writing types, declarations, and declaration update records 4959 // until we've emitted all of them. 4960 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5); 4961 WriteTypeAbbrevs(); 4962 WriteDeclAbbrevs(); 4963 do { 4964 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord); 4965 while (!DeclTypesToEmit.empty()) { 4966 DeclOrType DOT = DeclTypesToEmit.front(); 4967 DeclTypesToEmit.pop(); 4968 if (DOT.isType()) 4969 WriteType(DOT.getType()); 4970 else 4971 WriteDecl(Context, DOT.getDecl()); 4972 } 4973 } while (!DeclUpdates.empty()); 4974 Stream.ExitBlock(); 4975 4976 DoneWritingDeclsAndTypes = true; 4977 4978 // These things can only be done once we've written out decls and types. 4979 WriteTypeDeclOffsets(); 4980 if (!DeclUpdatesOffsetsRecord.empty()) 4981 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord); 4982 WriteFileDeclIDsMap(); 4983 WriteSourceManagerBlock(Context.getSourceManager(), PP); 4984 WriteComments(); 4985 WritePreprocessor(PP, isModule); 4986 WriteHeaderSearch(PP.getHeaderSearchInfo()); 4987 WriteSelectors(SemaRef); 4988 WriteReferencedSelectorsPool(SemaRef); 4989 WriteLateParsedTemplates(SemaRef); 4990 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule); 4991 WriteFPPragmaOptions(SemaRef.getFPOptions()); 4992 WriteOpenCLExtensions(SemaRef); 4993 WriteOpenCLExtensionTypes(SemaRef); 4994 WriteOpenCLExtensionDecls(SemaRef); 4995 WriteCUDAPragmas(SemaRef); 4996 4997 // If we're emitting a module, write out the submodule information. 4998 if (WritingModule) 4999 WriteSubmodules(WritingModule); 5000 5001 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes); 5002 5003 // Write the record containing external, unnamed definitions. 5004 if (!EagerlyDeserializedDecls.empty()) 5005 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls); 5006 5007 if (!ModularCodegenDecls.empty()) 5008 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls); 5009 5010 // Write the record containing tentative definitions. 5011 if (!TentativeDefinitions.empty()) 5012 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 5013 5014 // Write the record containing unused file scoped decls. 5015 if (!UnusedFileScopedDecls.empty()) 5016 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 5017 5018 // Write the record containing weak undeclared identifiers. 5019 if (!WeakUndeclaredIdentifiers.empty()) 5020 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 5021 WeakUndeclaredIdentifiers); 5022 5023 // Write the record containing ext_vector type names. 5024 if (!ExtVectorDecls.empty()) 5025 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 5026 5027 // Write the record containing VTable uses information. 5028 if (!VTableUses.empty()) 5029 Stream.EmitRecord(VTABLE_USES, VTableUses); 5030 5031 // Write the record containing potentially unused local typedefs. 5032 if (!UnusedLocalTypedefNameCandidates.empty()) 5033 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES, 5034 UnusedLocalTypedefNameCandidates); 5035 5036 // Write the record containing pending implicit instantiations. 5037 if (!PendingInstantiations.empty()) 5038 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 5039 5040 // Write the record containing declaration references of Sema. 5041 if (!SemaDeclRefs.empty()) 5042 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 5043 5044 // Write the record containing CUDA-specific declaration references. 5045 if (!CUDASpecialDeclRefs.empty()) 5046 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs); 5047 5048 // Write the delegating constructors. 5049 if (!DelegatingCtorDecls.empty()) 5050 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls); 5051 5052 // Write the known namespaces. 5053 if (!KnownNamespaces.empty()) 5054 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces); 5055 5056 // Write the undefined internal functions and variables, and inline functions. 5057 if (!UndefinedButUsed.empty()) 5058 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed); 5059 5060 if (!DeleteExprsToAnalyze.empty()) 5061 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze); 5062 5063 // Write the visible updates to DeclContexts. 5064 for (auto *DC : UpdatedDeclContexts) 5065 WriteDeclContextVisibleUpdate(DC); 5066 5067 if (!WritingModule) { 5068 // Write the submodules that were imported, if any. 5069 struct ModuleInfo { 5070 uint64_t ID; 5071 Module *M; 5072 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {} 5073 }; 5074 llvm::SmallVector<ModuleInfo, 64> Imports; 5075 for (const auto *I : Context.local_imports()) { 5076 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end()); 5077 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()], 5078 I->getImportedModule())); 5079 } 5080 5081 if (!Imports.empty()) { 5082 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) { 5083 return A.ID < B.ID; 5084 }; 5085 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) { 5086 return A.ID == B.ID; 5087 }; 5088 5089 // Sort and deduplicate module IDs. 5090 std::sort(Imports.begin(), Imports.end(), Cmp); 5091 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq), 5092 Imports.end()); 5093 5094 RecordData ImportedModules; 5095 for (const auto &Import : Imports) { 5096 ImportedModules.push_back(Import.ID); 5097 // FIXME: If the module has macros imported then later has declarations 5098 // imported, this location won't be the right one as a location for the 5099 // declaration imports. 5100 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules); 5101 } 5102 5103 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules); 5104 } 5105 } 5106 5107 WriteObjCCategories(); 5108 if(!WritingModule) { 5109 WriteOptimizePragmaOptions(SemaRef); 5110 WriteMSStructPragmaOptions(SemaRef); 5111 WriteMSPointersToMembersPragmaOptions(SemaRef); 5112 } 5113 WritePackPragmaOptions(SemaRef); 5114 5115 // Some simple statistics 5116 RecordData::value_type Record[] = { 5117 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts}; 5118 Stream.EmitRecord(STATISTICS, Record); 5119 Stream.ExitBlock(); 5120 5121 // Write the module file extension blocks. 5122 for (const auto &ExtWriter : ModuleFileExtensionWriters) 5123 WriteModuleFileExtension(SemaRef, *ExtWriter); 5124 5125 return writeUnhashedControlBlock(PP, Context); 5126 } 5127 5128 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) { 5129 if (DeclUpdates.empty()) 5130 return; 5131 5132 DeclUpdateMap LocalUpdates; 5133 LocalUpdates.swap(DeclUpdates); 5134 5135 for (auto &DeclUpdate : LocalUpdates) { 5136 const Decl *D = DeclUpdate.first; 5137 5138 bool HasUpdatedBody = false; 5139 RecordData RecordData; 5140 ASTRecordWriter Record(*this, RecordData); 5141 for (auto &Update : DeclUpdate.second) { 5142 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind(); 5143 5144 // An updated body is emitted last, so that the reader doesn't need 5145 // to skip over the lazy body to reach statements for other records. 5146 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION) 5147 HasUpdatedBody = true; 5148 else 5149 Record.push_back(Kind); 5150 5151 switch (Kind) { 5152 case UPD_CXX_ADDED_IMPLICIT_MEMBER: 5153 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: 5154 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: 5155 assert(Update.getDecl() && "no decl to add?"); 5156 Record.push_back(GetDeclRef(Update.getDecl())); 5157 break; 5158 5159 case UPD_CXX_ADDED_FUNCTION_DEFINITION: 5160 break; 5161 5162 case UPD_CXX_POINT_OF_INSTANTIATION: 5163 // FIXME: Do we need to also save the template specialization kind here? 5164 Record.AddSourceLocation(Update.getLoc()); 5165 break; 5166 5167 case UPD_CXX_ADDED_VAR_DEFINITION: { 5168 const VarDecl *VD = cast<VarDecl>(D); 5169 Record.push_back(VD->isInline()); 5170 Record.push_back(VD->isInlineSpecified()); 5171 if (VD->getInit()) { 5172 Record.push_back(!VD->isInitKnownICE() ? 1 5173 : (VD->isInitICE() ? 3 : 2)); 5174 Record.AddStmt(const_cast<Expr*>(VD->getInit())); 5175 } else { 5176 Record.push_back(0); 5177 } 5178 break; 5179 } 5180 5181 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: 5182 Record.AddStmt(const_cast<Expr *>( 5183 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg())); 5184 break; 5185 5186 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: 5187 Record.AddStmt( 5188 cast<FieldDecl>(Update.getDecl())->getInClassInitializer()); 5189 break; 5190 5191 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: { 5192 auto *RD = cast<CXXRecordDecl>(D); 5193 UpdatedDeclContexts.insert(RD->getPrimaryContext()); 5194 Record.AddCXXDefinitionData(RD); 5195 Record.AddOffset(WriteDeclContextLexicalBlock( 5196 *Context, const_cast<CXXRecordDecl *>(RD))); 5197 5198 // This state is sometimes updated by template instantiation, when we 5199 // switch from the specialization referring to the template declaration 5200 // to it referring to the template definition. 5201 if (auto *MSInfo = RD->getMemberSpecializationInfo()) { 5202 Record.push_back(MSInfo->getTemplateSpecializationKind()); 5203 Record.AddSourceLocation(MSInfo->getPointOfInstantiation()); 5204 } else { 5205 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD); 5206 Record.push_back(Spec->getTemplateSpecializationKind()); 5207 Record.AddSourceLocation(Spec->getPointOfInstantiation()); 5208 5209 // The instantiation might have been resolved to a partial 5210 // specialization. If so, record which one. 5211 auto From = Spec->getInstantiatedFrom(); 5212 if (auto PartialSpec = 5213 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) { 5214 Record.push_back(true); 5215 Record.AddDeclRef(PartialSpec); 5216 Record.AddTemplateArgumentList( 5217 &Spec->getTemplateInstantiationArgs()); 5218 } else { 5219 Record.push_back(false); 5220 } 5221 } 5222 Record.push_back(RD->getTagKind()); 5223 Record.AddSourceLocation(RD->getLocation()); 5224 Record.AddSourceLocation(RD->getLocStart()); 5225 Record.AddSourceRange(RD->getBraceRange()); 5226 5227 // Instantiation may change attributes; write them all out afresh. 5228 Record.push_back(D->hasAttrs()); 5229 if (D->hasAttrs()) 5230 Record.AddAttributes(D->getAttrs()); 5231 5232 // FIXME: Ensure we don't get here for explicit instantiations. 5233 break; 5234 } 5235 5236 case UPD_CXX_RESOLVED_DTOR_DELETE: 5237 Record.AddDeclRef(Update.getDecl()); 5238 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg()); 5239 break; 5240 5241 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: 5242 addExceptionSpec( 5243 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(), 5244 Record); 5245 break; 5246 5247 case UPD_CXX_DEDUCED_RETURN_TYPE: 5248 Record.push_back(GetOrCreateTypeID(Update.getType())); 5249 break; 5250 5251 case UPD_DECL_MARKED_USED: 5252 break; 5253 5254 case UPD_MANGLING_NUMBER: 5255 case UPD_STATIC_LOCAL_NUMBER: 5256 Record.push_back(Update.getNumber()); 5257 break; 5258 5259 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE: 5260 Record.AddSourceRange( 5261 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange()); 5262 break; 5263 5264 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: 5265 Record.AddSourceRange( 5266 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange()); 5267 break; 5268 5269 case UPD_DECL_EXPORTED: 5270 Record.push_back(getSubmoduleID(Update.getModule())); 5271 break; 5272 5273 case UPD_ADDED_ATTR_TO_RECORD: 5274 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr())); 5275 break; 5276 } 5277 } 5278 5279 if (HasUpdatedBody) { 5280 const auto *Def = cast<FunctionDecl>(D); 5281 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION); 5282 Record.push_back(Def->isInlined()); 5283 Record.AddSourceLocation(Def->getInnerLocStart()); 5284 Record.AddFunctionDefinition(Def); 5285 } 5286 5287 OffsetsRecord.push_back(GetDeclRef(D)); 5288 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES)); 5289 } 5290 } 5291 5292 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) { 5293 uint32_t Raw = Loc.getRawEncoding(); 5294 Record.push_back((Raw << 1) | (Raw >> 31)); 5295 } 5296 5297 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) { 5298 AddSourceLocation(Range.getBegin(), Record); 5299 AddSourceLocation(Range.getEnd(), Record); 5300 } 5301 5302 void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) { 5303 Record->push_back(Value.getBitWidth()); 5304 const uint64_t *Words = Value.getRawData(); 5305 Record->append(Words, Words + Value.getNumWords()); 5306 } 5307 5308 void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) { 5309 Record->push_back(Value.isUnsigned()); 5310 AddAPInt(Value); 5311 } 5312 5313 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) { 5314 AddAPInt(Value.bitcastToAPInt()); 5315 } 5316 5317 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) { 5318 Record.push_back(getIdentifierRef(II)); 5319 } 5320 5321 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) { 5322 if (!II) 5323 return 0; 5324 5325 IdentID &ID = IdentifierIDs[II]; 5326 if (ID == 0) 5327 ID = NextIdentID++; 5328 return ID; 5329 } 5330 5331 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) { 5332 // Don't emit builtin macros like __LINE__ to the AST file unless they 5333 // have been redefined by the header (in which case they are not 5334 // isBuiltinMacro). 5335 if (!MI || MI->isBuiltinMacro()) 5336 return 0; 5337 5338 MacroID &ID = MacroIDs[MI]; 5339 if (ID == 0) { 5340 ID = NextMacroID++; 5341 MacroInfoToEmitData Info = { Name, MI, ID }; 5342 MacroInfosToEmit.push_back(Info); 5343 } 5344 return ID; 5345 } 5346 5347 MacroID ASTWriter::getMacroID(MacroInfo *MI) { 5348 if (!MI || MI->isBuiltinMacro()) 5349 return 0; 5350 5351 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!"); 5352 return MacroIDs[MI]; 5353 } 5354 5355 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) { 5356 return IdentMacroDirectivesOffsetMap.lookup(Name); 5357 } 5358 5359 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) { 5360 Record->push_back(Writer->getSelectorRef(SelRef)); 5361 } 5362 5363 SelectorID ASTWriter::getSelectorRef(Selector Sel) { 5364 if (Sel.getAsOpaquePtr() == nullptr) { 5365 return 0; 5366 } 5367 5368 SelectorID SID = SelectorIDs[Sel]; 5369 if (SID == 0 && Chain) { 5370 // This might trigger a ReadSelector callback, which will set the ID for 5371 // this selector. 5372 Chain->LoadSelector(Sel); 5373 SID = SelectorIDs[Sel]; 5374 } 5375 if (SID == 0) { 5376 SID = NextSelectorID++; 5377 SelectorIDs[Sel] = SID; 5378 } 5379 return SID; 5380 } 5381 5382 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) { 5383 AddDeclRef(Temp->getDestructor()); 5384 } 5385 5386 void ASTRecordWriter::AddTemplateArgumentLocInfo( 5387 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) { 5388 switch (Kind) { 5389 case TemplateArgument::Expression: 5390 AddStmt(Arg.getAsExpr()); 5391 break; 5392 case TemplateArgument::Type: 5393 AddTypeSourceInfo(Arg.getAsTypeSourceInfo()); 5394 break; 5395 case TemplateArgument::Template: 5396 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc()); 5397 AddSourceLocation(Arg.getTemplateNameLoc()); 5398 break; 5399 case TemplateArgument::TemplateExpansion: 5400 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc()); 5401 AddSourceLocation(Arg.getTemplateNameLoc()); 5402 AddSourceLocation(Arg.getTemplateEllipsisLoc()); 5403 break; 5404 case TemplateArgument::Null: 5405 case TemplateArgument::Integral: 5406 case TemplateArgument::Declaration: 5407 case TemplateArgument::NullPtr: 5408 case TemplateArgument::Pack: 5409 // FIXME: Is this right? 5410 break; 5411 } 5412 } 5413 5414 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) { 5415 AddTemplateArgument(Arg.getArgument()); 5416 5417 if (Arg.getArgument().getKind() == TemplateArgument::Expression) { 5418 bool InfoHasSameExpr 5419 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr(); 5420 Record->push_back(InfoHasSameExpr); 5421 if (InfoHasSameExpr) 5422 return; // Avoid storing the same expr twice. 5423 } 5424 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo()); 5425 } 5426 5427 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) { 5428 if (!TInfo) { 5429 AddTypeRef(QualType()); 5430 return; 5431 } 5432 5433 AddTypeLoc(TInfo->getTypeLoc()); 5434 } 5435 5436 void ASTRecordWriter::AddTypeLoc(TypeLoc TL) { 5437 AddTypeRef(TL.getType()); 5438 5439 TypeLocWriter TLW(*this); 5440 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 5441 TLW.Visit(TL); 5442 } 5443 5444 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) { 5445 Record.push_back(GetOrCreateTypeID(T)); 5446 } 5447 5448 TypeID ASTWriter::GetOrCreateTypeID(QualType T) { 5449 assert(Context); 5450 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx { 5451 if (T.isNull()) 5452 return TypeIdx(); 5453 assert(!T.getLocalFastQualifiers()); 5454 5455 TypeIdx &Idx = TypeIdxs[T]; 5456 if (Idx.getIndex() == 0) { 5457 if (DoneWritingDeclsAndTypes) { 5458 assert(0 && "New type seen after serializing all the types to emit!"); 5459 return TypeIdx(); 5460 } 5461 5462 // We haven't seen this type before. Assign it a new ID and put it 5463 // into the queue of types to emit. 5464 Idx = TypeIdx(NextTypeID++); 5465 DeclTypesToEmit.push(T); 5466 } 5467 return Idx; 5468 }); 5469 } 5470 5471 TypeID ASTWriter::getTypeID(QualType T) const { 5472 assert(Context); 5473 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx { 5474 if (T.isNull()) 5475 return TypeIdx(); 5476 assert(!T.getLocalFastQualifiers()); 5477 5478 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 5479 assert(I != TypeIdxs.end() && "Type not emitted!"); 5480 return I->second; 5481 }); 5482 } 5483 5484 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) { 5485 Record.push_back(GetDeclRef(D)); 5486 } 5487 5488 DeclID ASTWriter::GetDeclRef(const Decl *D) { 5489 assert(WritingAST && "Cannot request a declaration ID before AST writing"); 5490 5491 if (!D) { 5492 return 0; 5493 } 5494 5495 // If D comes from an AST file, its declaration ID is already known and 5496 // fixed. 5497 if (D->isFromASTFile()) 5498 return D->getGlobalID(); 5499 5500 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer"); 5501 DeclID &ID = DeclIDs[D]; 5502 if (ID == 0) { 5503 if (DoneWritingDeclsAndTypes) { 5504 assert(0 && "New decl seen after serializing all the decls to emit!"); 5505 return 0; 5506 } 5507 5508 // We haven't seen this declaration before. Give it a new ID and 5509 // enqueue it in the list of declarations to emit. 5510 ID = NextDeclID++; 5511 DeclTypesToEmit.push(const_cast<Decl *>(D)); 5512 } 5513 5514 return ID; 5515 } 5516 5517 DeclID ASTWriter::getDeclID(const Decl *D) { 5518 if (!D) 5519 return 0; 5520 5521 // If D comes from an AST file, its declaration ID is already known and 5522 // fixed. 5523 if (D->isFromASTFile()) 5524 return D->getGlobalID(); 5525 5526 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!"); 5527 return DeclIDs[D]; 5528 } 5529 5530 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) { 5531 assert(ID); 5532 assert(D); 5533 5534 SourceLocation Loc = D->getLocation(); 5535 if (Loc.isInvalid()) 5536 return; 5537 5538 // We only keep track of the file-level declarations of each file. 5539 if (!D->getLexicalDeclContext()->isFileContext()) 5540 return; 5541 // FIXME: ParmVarDecls that are part of a function type of a parameter of 5542 // a function/objc method, should not have TU as lexical context. 5543 // TemplateTemplateParmDecls that are part of an alias template, should not 5544 // have TU as lexical context. 5545 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D)) 5546 return; 5547 5548 SourceManager &SM = Context->getSourceManager(); 5549 SourceLocation FileLoc = SM.getFileLoc(Loc); 5550 assert(SM.isLocalSourceLocation(FileLoc)); 5551 FileID FID; 5552 unsigned Offset; 5553 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc); 5554 if (FID.isInvalid()) 5555 return; 5556 assert(SM.getSLocEntry(FID).isFile()); 5557 5558 DeclIDInFileInfo *&Info = FileDeclIDs[FID]; 5559 if (!Info) 5560 Info = new DeclIDInFileInfo(); 5561 5562 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID); 5563 LocDeclIDsTy &Decls = Info->DeclIDs; 5564 5565 if (Decls.empty() || Decls.back().first <= Offset) { 5566 Decls.push_back(LocDecl); 5567 return; 5568 } 5569 5570 LocDeclIDsTy::iterator I = 5571 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first()); 5572 5573 Decls.insert(I, LocDecl); 5574 } 5575 5576 void ASTRecordWriter::AddDeclarationName(DeclarationName Name) { 5577 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc. 5578 Record->push_back(Name.getNameKind()); 5579 switch (Name.getNameKind()) { 5580 case DeclarationName::Identifier: 5581 AddIdentifierRef(Name.getAsIdentifierInfo()); 5582 break; 5583 5584 case DeclarationName::ObjCZeroArgSelector: 5585 case DeclarationName::ObjCOneArgSelector: 5586 case DeclarationName::ObjCMultiArgSelector: 5587 AddSelectorRef(Name.getObjCSelector()); 5588 break; 5589 5590 case DeclarationName::CXXConstructorName: 5591 case DeclarationName::CXXDestructorName: 5592 case DeclarationName::CXXConversionFunctionName: 5593 AddTypeRef(Name.getCXXNameType()); 5594 break; 5595 5596 case DeclarationName::CXXDeductionGuideName: 5597 AddDeclRef(Name.getCXXDeductionGuideTemplate()); 5598 break; 5599 5600 case DeclarationName::CXXOperatorName: 5601 Record->push_back(Name.getCXXOverloadedOperator()); 5602 break; 5603 5604 case DeclarationName::CXXLiteralOperatorName: 5605 AddIdentifierRef(Name.getCXXLiteralIdentifier()); 5606 break; 5607 5608 case DeclarationName::CXXUsingDirective: 5609 // No extra data to emit 5610 break; 5611 } 5612 } 5613 5614 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) { 5615 assert(needsAnonymousDeclarationNumber(D) && 5616 "expected an anonymous declaration"); 5617 5618 // Number the anonymous declarations within this context, if we've not 5619 // already done so. 5620 auto It = AnonymousDeclarationNumbers.find(D); 5621 if (It == AnonymousDeclarationNumbers.end()) { 5622 auto *DC = D->getLexicalDeclContext(); 5623 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) { 5624 AnonymousDeclarationNumbers[ND] = Number; 5625 }); 5626 5627 It = AnonymousDeclarationNumbers.find(D); 5628 assert(It != AnonymousDeclarationNumbers.end() && 5629 "declaration not found within its lexical context"); 5630 } 5631 5632 return It->second; 5633 } 5634 5635 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 5636 DeclarationName Name) { 5637 switch (Name.getNameKind()) { 5638 case DeclarationName::CXXConstructorName: 5639 case DeclarationName::CXXDestructorName: 5640 case DeclarationName::CXXConversionFunctionName: 5641 AddTypeSourceInfo(DNLoc.NamedType.TInfo); 5642 break; 5643 5644 case DeclarationName::CXXOperatorName: 5645 AddSourceLocation(SourceLocation::getFromRawEncoding( 5646 DNLoc.CXXOperatorName.BeginOpNameLoc)); 5647 AddSourceLocation( 5648 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc)); 5649 break; 5650 5651 case DeclarationName::CXXLiteralOperatorName: 5652 AddSourceLocation(SourceLocation::getFromRawEncoding( 5653 DNLoc.CXXLiteralOperatorName.OpNameLoc)); 5654 break; 5655 5656 case DeclarationName::Identifier: 5657 case DeclarationName::ObjCZeroArgSelector: 5658 case DeclarationName::ObjCOneArgSelector: 5659 case DeclarationName::ObjCMultiArgSelector: 5660 case DeclarationName::CXXUsingDirective: 5661 case DeclarationName::CXXDeductionGuideName: 5662 break; 5663 } 5664 } 5665 5666 void ASTRecordWriter::AddDeclarationNameInfo( 5667 const DeclarationNameInfo &NameInfo) { 5668 AddDeclarationName(NameInfo.getName()); 5669 AddSourceLocation(NameInfo.getLoc()); 5670 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName()); 5671 } 5672 5673 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) { 5674 AddNestedNameSpecifierLoc(Info.QualifierLoc); 5675 Record->push_back(Info.NumTemplParamLists); 5676 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i) 5677 AddTemplateParameterList(Info.TemplParamLists[i]); 5678 } 5679 5680 void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) { 5681 // Nested name specifiers usually aren't too long. I think that 8 would 5682 // typically accommodate the vast majority. 5683 SmallVector<NestedNameSpecifier *, 8> NestedNames; 5684 5685 // Push each of the NNS's onto a stack for serialization in reverse order. 5686 while (NNS) { 5687 NestedNames.push_back(NNS); 5688 NNS = NNS->getPrefix(); 5689 } 5690 5691 Record->push_back(NestedNames.size()); 5692 while(!NestedNames.empty()) { 5693 NNS = NestedNames.pop_back_val(); 5694 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind(); 5695 Record->push_back(Kind); 5696 switch (Kind) { 5697 case NestedNameSpecifier::Identifier: 5698 AddIdentifierRef(NNS->getAsIdentifier()); 5699 break; 5700 5701 case NestedNameSpecifier::Namespace: 5702 AddDeclRef(NNS->getAsNamespace()); 5703 break; 5704 5705 case NestedNameSpecifier::NamespaceAlias: 5706 AddDeclRef(NNS->getAsNamespaceAlias()); 5707 break; 5708 5709 case NestedNameSpecifier::TypeSpec: 5710 case NestedNameSpecifier::TypeSpecWithTemplate: 5711 AddTypeRef(QualType(NNS->getAsType(), 0)); 5712 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 5713 break; 5714 5715 case NestedNameSpecifier::Global: 5716 // Don't need to write an associated value. 5717 break; 5718 5719 case NestedNameSpecifier::Super: 5720 AddDeclRef(NNS->getAsRecordDecl()); 5721 break; 5722 } 5723 } 5724 } 5725 5726 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { 5727 // Nested name specifiers usually aren't too long. I think that 8 would 5728 // typically accommodate the vast majority. 5729 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 5730 5731 // Push each of the nested-name-specifiers's onto a stack for 5732 // serialization in reverse order. 5733 while (NNS) { 5734 NestedNames.push_back(NNS); 5735 NNS = NNS.getPrefix(); 5736 } 5737 5738 Record->push_back(NestedNames.size()); 5739 while(!NestedNames.empty()) { 5740 NNS = NestedNames.pop_back_val(); 5741 NestedNameSpecifier::SpecifierKind Kind 5742 = NNS.getNestedNameSpecifier()->getKind(); 5743 Record->push_back(Kind); 5744 switch (Kind) { 5745 case NestedNameSpecifier::Identifier: 5746 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier()); 5747 AddSourceRange(NNS.getLocalSourceRange()); 5748 break; 5749 5750 case NestedNameSpecifier::Namespace: 5751 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace()); 5752 AddSourceRange(NNS.getLocalSourceRange()); 5753 break; 5754 5755 case NestedNameSpecifier::NamespaceAlias: 5756 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias()); 5757 AddSourceRange(NNS.getLocalSourceRange()); 5758 break; 5759 5760 case NestedNameSpecifier::TypeSpec: 5761 case NestedNameSpecifier::TypeSpecWithTemplate: 5762 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 5763 AddTypeLoc(NNS.getTypeLoc()); 5764 AddSourceLocation(NNS.getLocalSourceRange().getEnd()); 5765 break; 5766 5767 case NestedNameSpecifier::Global: 5768 AddSourceLocation(NNS.getLocalSourceRange().getEnd()); 5769 break; 5770 5771 case NestedNameSpecifier::Super: 5772 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl()); 5773 AddSourceRange(NNS.getLocalSourceRange()); 5774 break; 5775 } 5776 } 5777 } 5778 5779 void ASTRecordWriter::AddTemplateName(TemplateName Name) { 5780 TemplateName::NameKind Kind = Name.getKind(); 5781 Record->push_back(Kind); 5782 switch (Kind) { 5783 case TemplateName::Template: 5784 AddDeclRef(Name.getAsTemplateDecl()); 5785 break; 5786 5787 case TemplateName::OverloadedTemplate: { 5788 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate(); 5789 Record->push_back(OvT->size()); 5790 for (const auto &I : *OvT) 5791 AddDeclRef(I); 5792 break; 5793 } 5794 5795 case TemplateName::QualifiedTemplate: { 5796 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName(); 5797 AddNestedNameSpecifier(QualT->getQualifier()); 5798 Record->push_back(QualT->hasTemplateKeyword()); 5799 AddDeclRef(QualT->getTemplateDecl()); 5800 break; 5801 } 5802 5803 case TemplateName::DependentTemplate: { 5804 DependentTemplateName *DepT = Name.getAsDependentTemplateName(); 5805 AddNestedNameSpecifier(DepT->getQualifier()); 5806 Record->push_back(DepT->isIdentifier()); 5807 if (DepT->isIdentifier()) 5808 AddIdentifierRef(DepT->getIdentifier()); 5809 else 5810 Record->push_back(DepT->getOperator()); 5811 break; 5812 } 5813 5814 case TemplateName::SubstTemplateTemplateParm: { 5815 SubstTemplateTemplateParmStorage *subst 5816 = Name.getAsSubstTemplateTemplateParm(); 5817 AddDeclRef(subst->getParameter()); 5818 AddTemplateName(subst->getReplacement()); 5819 break; 5820 } 5821 5822 case TemplateName::SubstTemplateTemplateParmPack: { 5823 SubstTemplateTemplateParmPackStorage *SubstPack 5824 = Name.getAsSubstTemplateTemplateParmPack(); 5825 AddDeclRef(SubstPack->getParameterPack()); 5826 AddTemplateArgument(SubstPack->getArgumentPack()); 5827 break; 5828 } 5829 } 5830 } 5831 5832 void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) { 5833 Record->push_back(Arg.getKind()); 5834 switch (Arg.getKind()) { 5835 case TemplateArgument::Null: 5836 break; 5837 case TemplateArgument::Type: 5838 AddTypeRef(Arg.getAsType()); 5839 break; 5840 case TemplateArgument::Declaration: 5841 AddDeclRef(Arg.getAsDecl()); 5842 AddTypeRef(Arg.getParamTypeForDecl()); 5843 break; 5844 case TemplateArgument::NullPtr: 5845 AddTypeRef(Arg.getNullPtrType()); 5846 break; 5847 case TemplateArgument::Integral: 5848 AddAPSInt(Arg.getAsIntegral()); 5849 AddTypeRef(Arg.getIntegralType()); 5850 break; 5851 case TemplateArgument::Template: 5852 AddTemplateName(Arg.getAsTemplateOrTemplatePattern()); 5853 break; 5854 case TemplateArgument::TemplateExpansion: 5855 AddTemplateName(Arg.getAsTemplateOrTemplatePattern()); 5856 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions()) 5857 Record->push_back(*NumExpansions + 1); 5858 else 5859 Record->push_back(0); 5860 break; 5861 case TemplateArgument::Expression: 5862 AddStmt(Arg.getAsExpr()); 5863 break; 5864 case TemplateArgument::Pack: 5865 Record->push_back(Arg.pack_size()); 5866 for (const auto &P : Arg.pack_elements()) 5867 AddTemplateArgument(P); 5868 break; 5869 } 5870 } 5871 5872 void ASTRecordWriter::AddTemplateParameterList( 5873 const TemplateParameterList *TemplateParams) { 5874 assert(TemplateParams && "No TemplateParams!"); 5875 AddSourceLocation(TemplateParams->getTemplateLoc()); 5876 AddSourceLocation(TemplateParams->getLAngleLoc()); 5877 AddSourceLocation(TemplateParams->getRAngleLoc()); 5878 // TODO: Concepts 5879 Record->push_back(TemplateParams->size()); 5880 for (const auto &P : *TemplateParams) 5881 AddDeclRef(P); 5882 } 5883 5884 /// \brief Emit a template argument list. 5885 void ASTRecordWriter::AddTemplateArgumentList( 5886 const TemplateArgumentList *TemplateArgs) { 5887 assert(TemplateArgs && "No TemplateArgs!"); 5888 Record->push_back(TemplateArgs->size()); 5889 for (int i = 0, e = TemplateArgs->size(); i != e; ++i) 5890 AddTemplateArgument(TemplateArgs->get(i)); 5891 } 5892 5893 void ASTRecordWriter::AddASTTemplateArgumentListInfo( 5894 const ASTTemplateArgumentListInfo *ASTTemplArgList) { 5895 assert(ASTTemplArgList && "No ASTTemplArgList!"); 5896 AddSourceLocation(ASTTemplArgList->LAngleLoc); 5897 AddSourceLocation(ASTTemplArgList->RAngleLoc); 5898 Record->push_back(ASTTemplArgList->NumTemplateArgs); 5899 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs(); 5900 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i) 5901 AddTemplateArgumentLoc(TemplArgs[i]); 5902 } 5903 5904 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) { 5905 Record->push_back(Set.size()); 5906 for (ASTUnresolvedSet::const_iterator 5907 I = Set.begin(), E = Set.end(); I != E; ++I) { 5908 AddDeclRef(I.getDecl()); 5909 Record->push_back(I.getAccess()); 5910 } 5911 } 5912 5913 // FIXME: Move this out of the main ASTRecordWriter interface. 5914 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) { 5915 Record->push_back(Base.isVirtual()); 5916 Record->push_back(Base.isBaseOfClass()); 5917 Record->push_back(Base.getAccessSpecifierAsWritten()); 5918 Record->push_back(Base.getInheritConstructors()); 5919 AddTypeSourceInfo(Base.getTypeSourceInfo()); 5920 AddSourceRange(Base.getSourceRange()); 5921 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 5922 : SourceLocation()); 5923 } 5924 5925 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W, 5926 ArrayRef<CXXBaseSpecifier> Bases) { 5927 ASTWriter::RecordData Record; 5928 ASTRecordWriter Writer(W, Record); 5929 Writer.push_back(Bases.size()); 5930 5931 for (auto &Base : Bases) 5932 Writer.AddCXXBaseSpecifier(Base); 5933 5934 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS); 5935 } 5936 5937 // FIXME: Move this out of the main ASTRecordWriter interface. 5938 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) { 5939 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases)); 5940 } 5941 5942 static uint64_t 5943 EmitCXXCtorInitializers(ASTWriter &W, 5944 ArrayRef<CXXCtorInitializer *> CtorInits) { 5945 ASTWriter::RecordData Record; 5946 ASTRecordWriter Writer(W, Record); 5947 Writer.push_back(CtorInits.size()); 5948 5949 for (auto *Init : CtorInits) { 5950 if (Init->isBaseInitializer()) { 5951 Writer.push_back(CTOR_INITIALIZER_BASE); 5952 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo()); 5953 Writer.push_back(Init->isBaseVirtual()); 5954 } else if (Init->isDelegatingInitializer()) { 5955 Writer.push_back(CTOR_INITIALIZER_DELEGATING); 5956 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo()); 5957 } else if (Init->isMemberInitializer()){ 5958 Writer.push_back(CTOR_INITIALIZER_MEMBER); 5959 Writer.AddDeclRef(Init->getMember()); 5960 } else { 5961 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER); 5962 Writer.AddDeclRef(Init->getIndirectMember()); 5963 } 5964 5965 Writer.AddSourceLocation(Init->getMemberLocation()); 5966 Writer.AddStmt(Init->getInit()); 5967 Writer.AddSourceLocation(Init->getLParenLoc()); 5968 Writer.AddSourceLocation(Init->getRParenLoc()); 5969 Writer.push_back(Init->isWritten()); 5970 if (Init->isWritten()) 5971 Writer.push_back(Init->getSourceOrder()); 5972 } 5973 5974 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS); 5975 } 5976 5977 // FIXME: Move this out of the main ASTRecordWriter interface. 5978 void ASTRecordWriter::AddCXXCtorInitializers( 5979 ArrayRef<CXXCtorInitializer *> CtorInits) { 5980 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits)); 5981 } 5982 5983 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) { 5984 auto &Data = D->data(); 5985 Record->push_back(Data.IsLambda); 5986 Record->push_back(Data.UserDeclaredConstructor); 5987 Record->push_back(Data.UserDeclaredSpecialMembers); 5988 Record->push_back(Data.Aggregate); 5989 Record->push_back(Data.PlainOldData); 5990 Record->push_back(Data.Empty); 5991 Record->push_back(Data.Polymorphic); 5992 Record->push_back(Data.Abstract); 5993 Record->push_back(Data.IsStandardLayout); 5994 Record->push_back(Data.HasNoNonEmptyBases); 5995 Record->push_back(Data.HasPrivateFields); 5996 Record->push_back(Data.HasProtectedFields); 5997 Record->push_back(Data.HasPublicFields); 5998 Record->push_back(Data.HasMutableFields); 5999 Record->push_back(Data.HasVariantMembers); 6000 Record->push_back(Data.HasOnlyCMembers); 6001 Record->push_back(Data.HasInClassInitializer); 6002 Record->push_back(Data.HasUninitializedReferenceMember); 6003 Record->push_back(Data.HasUninitializedFields); 6004 Record->push_back(Data.HasInheritedConstructor); 6005 Record->push_back(Data.HasInheritedAssignment); 6006 Record->push_back(Data.NeedOverloadResolutionForCopyConstructor); 6007 Record->push_back(Data.NeedOverloadResolutionForMoveConstructor); 6008 Record->push_back(Data.NeedOverloadResolutionForMoveAssignment); 6009 Record->push_back(Data.NeedOverloadResolutionForDestructor); 6010 Record->push_back(Data.DefaultedCopyConstructorIsDeleted); 6011 Record->push_back(Data.DefaultedMoveConstructorIsDeleted); 6012 Record->push_back(Data.DefaultedMoveAssignmentIsDeleted); 6013 Record->push_back(Data.DefaultedDestructorIsDeleted); 6014 Record->push_back(Data.HasTrivialSpecialMembers); 6015 Record->push_back(Data.HasTrivialSpecialMembersForCall); 6016 Record->push_back(Data.DeclaredNonTrivialSpecialMembers); 6017 Record->push_back(Data.DeclaredNonTrivialSpecialMembersForCall); 6018 Record->push_back(Data.HasIrrelevantDestructor); 6019 Record->push_back(Data.HasConstexprNonCopyMoveConstructor); 6020 Record->push_back(Data.HasDefaultedDefaultConstructor); 6021 Record->push_back(Data.CanPassInRegisters); 6022 Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr); 6023 Record->push_back(Data.HasConstexprDefaultConstructor); 6024 Record->push_back(Data.HasNonLiteralTypeFieldsOrBases); 6025 Record->push_back(Data.ComputedVisibleConversions); 6026 Record->push_back(Data.UserProvidedDefaultConstructor); 6027 Record->push_back(Data.DeclaredSpecialMembers); 6028 Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForVBase); 6029 Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase); 6030 Record->push_back(Data.ImplicitCopyAssignmentHasConstParam); 6031 Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam); 6032 Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam); 6033 6034 // getODRHash will compute the ODRHash if it has not been previously computed. 6035 Record->push_back(D->getODRHash()); 6036 bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo && 6037 Writer->WritingModule && !D->isDependentType(); 6038 Record->push_back(ModulesDebugInfo); 6039 if (ModulesDebugInfo) 6040 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D)); 6041 6042 // IsLambda bit is already saved. 6043 6044 Record->push_back(Data.NumBases); 6045 if (Data.NumBases > 0) 6046 AddCXXBaseSpecifiers(Data.bases()); 6047 6048 // FIXME: Make VBases lazily computed when needed to avoid storing them. 6049 Record->push_back(Data.NumVBases); 6050 if (Data.NumVBases > 0) 6051 AddCXXBaseSpecifiers(Data.vbases()); 6052 6053 AddUnresolvedSet(Data.Conversions.get(*Writer->Context)); 6054 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context)); 6055 // Data.Definition is the owning decl, no need to write it. 6056 AddDeclRef(D->getFirstFriend()); 6057 6058 // Add lambda-specific data. 6059 if (Data.IsLambda) { 6060 auto &Lambda = D->getLambdaData(); 6061 Record->push_back(Lambda.Dependent); 6062 Record->push_back(Lambda.IsGenericLambda); 6063 Record->push_back(Lambda.CaptureDefault); 6064 Record->push_back(Lambda.NumCaptures); 6065 Record->push_back(Lambda.NumExplicitCaptures); 6066 Record->push_back(Lambda.ManglingNumber); 6067 AddDeclRef(D->getLambdaContextDecl()); 6068 AddTypeSourceInfo(Lambda.MethodTyInfo); 6069 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) { 6070 const LambdaCapture &Capture = Lambda.Captures[I]; 6071 AddSourceLocation(Capture.getLocation()); 6072 Record->push_back(Capture.isImplicit()); 6073 Record->push_back(Capture.getCaptureKind()); 6074 switch (Capture.getCaptureKind()) { 6075 case LCK_StarThis: 6076 case LCK_This: 6077 case LCK_VLAType: 6078 break; 6079 case LCK_ByCopy: 6080 case LCK_ByRef: 6081 VarDecl *Var = 6082 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr; 6083 AddDeclRef(Var); 6084 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc() 6085 : SourceLocation()); 6086 break; 6087 } 6088 } 6089 } 6090 } 6091 6092 void ASTWriter::ReaderInitialized(ASTReader *Reader) { 6093 assert(Reader && "Cannot remove chain"); 6094 assert((!Chain || Chain == Reader) && "Cannot replace chain"); 6095 assert(FirstDeclID == NextDeclID && 6096 FirstTypeID == NextTypeID && 6097 FirstIdentID == NextIdentID && 6098 FirstMacroID == NextMacroID && 6099 FirstSubmoduleID == NextSubmoduleID && 6100 FirstSelectorID == NextSelectorID && 6101 "Setting chain after writing has started."); 6102 6103 Chain = Reader; 6104 6105 // Note, this will get called multiple times, once one the reader starts up 6106 // and again each time it's done reading a PCH or module. 6107 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls(); 6108 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes(); 6109 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers(); 6110 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros(); 6111 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules(); 6112 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors(); 6113 NextDeclID = FirstDeclID; 6114 NextTypeID = FirstTypeID; 6115 NextIdentID = FirstIdentID; 6116 NextMacroID = FirstMacroID; 6117 NextSelectorID = FirstSelectorID; 6118 NextSubmoduleID = FirstSubmoduleID; 6119 } 6120 6121 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) { 6122 // Always keep the highest ID. See \p TypeRead() for more information. 6123 IdentID &StoredID = IdentifierIDs[II]; 6124 if (ID > StoredID) 6125 StoredID = ID; 6126 } 6127 6128 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) { 6129 // Always keep the highest ID. See \p TypeRead() for more information. 6130 MacroID &StoredID = MacroIDs[MI]; 6131 if (ID > StoredID) 6132 StoredID = ID; 6133 } 6134 6135 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) { 6136 // Always take the highest-numbered type index. This copes with an interesting 6137 // case for chained AST writing where we schedule writing the type and then, 6138 // later, deserialize the type from another AST. In this case, we want to 6139 // keep the higher-numbered entry so that we can properly write it out to 6140 // the AST file. 6141 TypeIdx &StoredIdx = TypeIdxs[T]; 6142 if (Idx.getIndex() >= StoredIdx.getIndex()) 6143 StoredIdx = Idx; 6144 } 6145 6146 void ASTWriter::SelectorRead(SelectorID ID, Selector S) { 6147 // Always keep the highest ID. See \p TypeRead() for more information. 6148 SelectorID &StoredID = SelectorIDs[S]; 6149 if (ID > StoredID) 6150 StoredID = ID; 6151 } 6152 6153 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID, 6154 MacroDefinitionRecord *MD) { 6155 assert(MacroDefinitions.find(MD) == MacroDefinitions.end()); 6156 MacroDefinitions[MD] = ID; 6157 } 6158 6159 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) { 6160 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end()); 6161 SubmoduleIDs[Mod] = ID; 6162 } 6163 6164 void ASTWriter::CompletedTagDefinition(const TagDecl *D) { 6165 if (Chain && Chain->isProcessingUpdateRecords()) return; 6166 assert(D->isCompleteDefinition()); 6167 assert(!WritingAST && "Already writing the AST!"); 6168 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 6169 // We are interested when a PCH decl is modified. 6170 if (RD->isFromASTFile()) { 6171 // A forward reference was mutated into a definition. Rewrite it. 6172 // FIXME: This happens during template instantiation, should we 6173 // have created a new definition decl instead ? 6174 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) && 6175 "completed a tag from another module but not by instantiation?"); 6176 DeclUpdates[RD].push_back( 6177 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION)); 6178 } 6179 } 6180 } 6181 6182 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) { 6183 if (D->isFromASTFile()) 6184 return true; 6185 6186 // The predefined __va_list_tag struct is imported if we imported any decls. 6187 // FIXME: This is a gross hack. 6188 return D == D->getASTContext().getVaListTagDecl(); 6189 } 6190 6191 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) { 6192 if (Chain && Chain->isProcessingUpdateRecords()) return; 6193 assert(DC->isLookupContext() && 6194 "Should not add lookup results to non-lookup contexts!"); 6195 6196 // TU is handled elsewhere. 6197 if (isa<TranslationUnitDecl>(DC)) 6198 return; 6199 6200 // Namespaces are handled elsewhere, except for template instantiations of 6201 // FunctionTemplateDecls in namespaces. We are interested in cases where the 6202 // local instantiations are added to an imported context. Only happens when 6203 // adding ADL lookup candidates, for example templated friends. 6204 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None && 6205 !isa<FunctionTemplateDecl>(D)) 6206 return; 6207 6208 // We're only interested in cases where a local declaration is added to an 6209 // imported context. 6210 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC))) 6211 return; 6212 6213 assert(DC == DC->getPrimaryContext() && "added to non-primary context"); 6214 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!"); 6215 assert(!WritingAST && "Already writing the AST!"); 6216 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) { 6217 // We're adding a visible declaration to a predefined decl context. Ensure 6218 // that we write out all of its lookup results so we don't get a nasty 6219 // surprise when we try to emit its lookup table. 6220 for (auto *Child : DC->decls()) 6221 DeclsToEmitEvenIfUnreferenced.push_back(Child); 6222 } 6223 DeclsToEmitEvenIfUnreferenced.push_back(D); 6224 } 6225 6226 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { 6227 if (Chain && Chain->isProcessingUpdateRecords()) return; 6228 assert(D->isImplicit()); 6229 6230 // We're only interested in cases where a local declaration is added to an 6231 // imported context. 6232 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD)) 6233 return; 6234 6235 if (!isa<CXXMethodDecl>(D)) 6236 return; 6237 6238 // A decl coming from PCH was modified. 6239 assert(RD->isCompleteDefinition()); 6240 assert(!WritingAST && "Already writing the AST!"); 6241 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D)); 6242 } 6243 6244 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) { 6245 if (Chain && Chain->isProcessingUpdateRecords()) return; 6246 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!"); 6247 if (!Chain) return; 6248 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) { 6249 // If we don't already know the exception specification for this redecl 6250 // chain, add an update record for it. 6251 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D) 6252 ->getType() 6253 ->castAs<FunctionProtoType>() 6254 ->getExceptionSpecType())) 6255 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC); 6256 }); 6257 } 6258 6259 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) { 6260 if (Chain && Chain->isProcessingUpdateRecords()) return; 6261 assert(!WritingAST && "Already writing the AST!"); 6262 if (!Chain) return; 6263 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) { 6264 DeclUpdates[D].push_back( 6265 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType)); 6266 }); 6267 } 6268 6269 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD, 6270 const FunctionDecl *Delete, 6271 Expr *ThisArg) { 6272 if (Chain && Chain->isProcessingUpdateRecords()) return; 6273 assert(!WritingAST && "Already writing the AST!"); 6274 assert(Delete && "Not given an operator delete"); 6275 if (!Chain) return; 6276 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) { 6277 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete)); 6278 }); 6279 } 6280 6281 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) { 6282 if (Chain && Chain->isProcessingUpdateRecords()) return; 6283 assert(!WritingAST && "Already writing the AST!"); 6284 if (!D->isFromASTFile()) 6285 return; // Declaration not imported from PCH. 6286 6287 // Implicit function decl from a PCH was defined. 6288 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION)); 6289 } 6290 6291 void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) { 6292 if (Chain && Chain->isProcessingUpdateRecords()) return; 6293 assert(!WritingAST && "Already writing the AST!"); 6294 if (!D->isFromASTFile()) 6295 return; 6296 6297 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION)); 6298 } 6299 6300 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) { 6301 if (Chain && Chain->isProcessingUpdateRecords()) return; 6302 assert(!WritingAST && "Already writing the AST!"); 6303 if (!D->isFromASTFile()) 6304 return; 6305 6306 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION)); 6307 } 6308 6309 void ASTWriter::InstantiationRequested(const ValueDecl *D) { 6310 if (Chain && Chain->isProcessingUpdateRecords()) return; 6311 assert(!WritingAST && "Already writing the AST!"); 6312 if (!D->isFromASTFile()) 6313 return; 6314 6315 // Since the actual instantiation is delayed, this really means that we need 6316 // to update the instantiation location. 6317 SourceLocation POI; 6318 if (auto *VD = dyn_cast<VarDecl>(D)) 6319 POI = VD->getPointOfInstantiation(); 6320 else 6321 POI = cast<FunctionDecl>(D)->getPointOfInstantiation(); 6322 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI)); 6323 } 6324 6325 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) { 6326 if (Chain && Chain->isProcessingUpdateRecords()) return; 6327 assert(!WritingAST && "Already writing the AST!"); 6328 if (!D->isFromASTFile()) 6329 return; 6330 6331 DeclUpdates[D].push_back( 6332 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D)); 6333 } 6334 6335 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) { 6336 assert(!WritingAST && "Already writing the AST!"); 6337 if (!D->isFromASTFile()) 6338 return; 6339 6340 DeclUpdates[D].push_back( 6341 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D)); 6342 } 6343 6344 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, 6345 const ObjCInterfaceDecl *IFD) { 6346 if (Chain && Chain->isProcessingUpdateRecords()) return; 6347 assert(!WritingAST && "Already writing the AST!"); 6348 if (!IFD->isFromASTFile()) 6349 return; // Declaration not imported from PCH. 6350 6351 assert(IFD->getDefinition() && "Category on a class without a definition?"); 6352 ObjCClassesWithCategories.insert( 6353 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition())); 6354 } 6355 6356 void ASTWriter::DeclarationMarkedUsed(const Decl *D) { 6357 if (Chain && Chain->isProcessingUpdateRecords()) return; 6358 assert(!WritingAST && "Already writing the AST!"); 6359 6360 // If there is *any* declaration of the entity that's not from an AST file, 6361 // we can skip writing the update record. We make sure that isUsed() triggers 6362 // completion of the redeclaration chain of the entity. 6363 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl()) 6364 if (IsLocalDecl(Prev)) 6365 return; 6366 6367 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED)); 6368 } 6369 6370 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) { 6371 if (Chain && Chain->isProcessingUpdateRecords()) return; 6372 assert(!WritingAST && "Already writing the AST!"); 6373 if (!D->isFromASTFile()) 6374 return; 6375 6376 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE)); 6377 } 6378 6379 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D, 6380 const Attr *Attr) { 6381 if (Chain && Chain->isProcessingUpdateRecords()) return; 6382 assert(!WritingAST && "Already writing the AST!"); 6383 if (!D->isFromASTFile()) 6384 return; 6385 6386 DeclUpdates[D].push_back( 6387 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr)); 6388 } 6389 6390 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) { 6391 if (Chain && Chain->isProcessingUpdateRecords()) return; 6392 assert(!WritingAST && "Already writing the AST!"); 6393 assert(D->isHidden() && "expected a hidden declaration"); 6394 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M)); 6395 } 6396 6397 void ASTWriter::AddedAttributeToRecord(const Attr *Attr, 6398 const RecordDecl *Record) { 6399 if (Chain && Chain->isProcessingUpdateRecords()) return; 6400 assert(!WritingAST && "Already writing the AST!"); 6401 if (!Record->isFromASTFile()) 6402 return; 6403 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr)); 6404 } 6405 6406 void ASTWriter::AddedCXXTemplateSpecialization( 6407 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) { 6408 assert(!WritingAST && "Already writing the AST!"); 6409 6410 if (!TD->getFirstDecl()->isFromASTFile()) 6411 return; 6412 if (Chain && Chain->isProcessingUpdateRecords()) 6413 return; 6414 6415 DeclsToEmitEvenIfUnreferenced.push_back(D); 6416 } 6417 6418 void ASTWriter::AddedCXXTemplateSpecialization( 6419 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) { 6420 assert(!WritingAST && "Already writing the AST!"); 6421 6422 if (!TD->getFirstDecl()->isFromASTFile()) 6423 return; 6424 if (Chain && Chain->isProcessingUpdateRecords()) 6425 return; 6426 6427 DeclsToEmitEvenIfUnreferenced.push_back(D); 6428 } 6429 6430 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, 6431 const FunctionDecl *D) { 6432 assert(!WritingAST && "Already writing the AST!"); 6433 6434 if (!TD->getFirstDecl()->isFromASTFile()) 6435 return; 6436 if (Chain && Chain->isProcessingUpdateRecords()) 6437 return; 6438 6439 DeclsToEmitEvenIfUnreferenced.push_back(D); 6440 } 6441