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