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