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