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