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