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