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