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