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