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