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