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