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