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