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