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