ASTWriter.cpp revision 14b6ba77710d6431794d65c7d58c6f29c3dc956e
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 "clang/Serialization/ASTSerializationListener.h" 16#include "ASTCommon.h" 17#include "clang/Sema/Sema.h" 18#include "clang/Sema/IdentifierResolver.h" 19#include "clang/AST/ASTContext.h" 20#include "clang/AST/Decl.h" 21#include "clang/AST/DeclContextInternals.h" 22#include "clang/AST/DeclTemplate.h" 23#include "clang/AST/DeclFriend.h" 24#include "clang/AST/Expr.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/Type.h" 27#include "clang/AST/TypeLocVisitor.h" 28#include "clang/Serialization/ASTReader.h" 29#include "clang/Lex/MacroInfo.h" 30#include "clang/Lex/PreprocessingRecord.h" 31#include "clang/Lex/Preprocessor.h" 32#include "clang/Lex/HeaderSearch.h" 33#include "clang/Basic/FileManager.h" 34#include "clang/Basic/FileSystemStatCache.h" 35#include "clang/Basic/OnDiskHashTable.h" 36#include "clang/Basic/SourceManager.h" 37#include "clang/Basic/SourceManagerInternals.h" 38#include "clang/Basic/TargetInfo.h" 39#include "clang/Basic/Version.h" 40#include "llvm/ADT/APFloat.h" 41#include "llvm/ADT/APInt.h" 42#include "llvm/ADT/StringExtras.h" 43#include "llvm/Bitcode/BitstreamWriter.h" 44#include "llvm/Support/FileSystem.h" 45#include "llvm/Support/MemoryBuffer.h" 46#include "llvm/Support/Path.h" 47#include <cstdio> 48using namespace clang; 49using namespace clang::serialization; 50 51template <typename T, typename Allocator> 52T *data(std::vector<T, Allocator> &v) { 53 return v.empty() ? 0 : &v.front(); 54} 55template <typename T, typename Allocator> 56const T *data(const std::vector<T, Allocator> &v) { 57 return v.empty() ? 0 : &v.front(); 58} 59 60//===----------------------------------------------------------------------===// 61// Type serialization 62//===----------------------------------------------------------------------===// 63 64namespace { 65 class ASTTypeWriter { 66 ASTWriter &Writer; 67 ASTWriter::RecordDataImpl &Record; 68 69 public: 70 /// \brief Type code that corresponds to the record generated. 71 TypeCode Code; 72 73 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record) 74 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { } 75 76 void VisitArrayType(const ArrayType *T); 77 void VisitFunctionType(const FunctionType *T); 78 void VisitTagType(const TagType *T); 79 80#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T); 81#define ABSTRACT_TYPE(Class, Base) 82#include "clang/AST/TypeNodes.def" 83 }; 84} 85 86void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) { 87 assert(false && "Built-in types are never serialized"); 88} 89 90void ASTTypeWriter::VisitComplexType(const ComplexType *T) { 91 Writer.AddTypeRef(T->getElementType(), Record); 92 Code = TYPE_COMPLEX; 93} 94 95void ASTTypeWriter::VisitPointerType(const PointerType *T) { 96 Writer.AddTypeRef(T->getPointeeType(), Record); 97 Code = TYPE_POINTER; 98} 99 100void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) { 101 Writer.AddTypeRef(T->getPointeeType(), Record); 102 Code = TYPE_BLOCK_POINTER; 103} 104 105void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) { 106 Writer.AddTypeRef(T->getPointeeType(), Record); 107 Code = TYPE_LVALUE_REFERENCE; 108} 109 110void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) { 111 Writer.AddTypeRef(T->getPointeeType(), Record); 112 Code = TYPE_RVALUE_REFERENCE; 113} 114 115void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) { 116 Writer.AddTypeRef(T->getPointeeType(), Record); 117 Writer.AddTypeRef(QualType(T->getClass(), 0), Record); 118 Code = TYPE_MEMBER_POINTER; 119} 120 121void ASTTypeWriter::VisitArrayType(const ArrayType *T) { 122 Writer.AddTypeRef(T->getElementType(), Record); 123 Record.push_back(T->getSizeModifier()); // FIXME: stable values 124 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values 125} 126 127void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) { 128 VisitArrayType(T); 129 Writer.AddAPInt(T->getSize(), Record); 130 Code = TYPE_CONSTANT_ARRAY; 131} 132 133void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) { 134 VisitArrayType(T); 135 Code = TYPE_INCOMPLETE_ARRAY; 136} 137 138void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) { 139 VisitArrayType(T); 140 Writer.AddSourceLocation(T->getLBracketLoc(), Record); 141 Writer.AddSourceLocation(T->getRBracketLoc(), Record); 142 Writer.AddStmt(T->getSizeExpr()); 143 Code = TYPE_VARIABLE_ARRAY; 144} 145 146void ASTTypeWriter::VisitVectorType(const VectorType *T) { 147 Writer.AddTypeRef(T->getElementType(), Record); 148 Record.push_back(T->getNumElements()); 149 Record.push_back(T->getVectorKind()); 150 Code = TYPE_VECTOR; 151} 152 153void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) { 154 VisitVectorType(T); 155 Code = TYPE_EXT_VECTOR; 156} 157 158void ASTTypeWriter::VisitFunctionType(const FunctionType *T) { 159 Writer.AddTypeRef(T->getResultType(), Record); 160 FunctionType::ExtInfo C = T->getExtInfo(); 161 Record.push_back(C.getNoReturn()); 162 Record.push_back(C.getRegParm()); 163 // FIXME: need to stabilize encoding of calling convention... 164 Record.push_back(C.getCC()); 165} 166 167void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { 168 VisitFunctionType(T); 169 Code = TYPE_FUNCTION_NO_PROTO; 170} 171 172void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) { 173 VisitFunctionType(T); 174 Record.push_back(T->getNumArgs()); 175 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I) 176 Writer.AddTypeRef(T->getArgType(I), Record); 177 Record.push_back(T->isVariadic()); 178 Record.push_back(T->getTypeQuals()); 179 Record.push_back(static_cast<unsigned>(T->getRefQualifier())); 180 Record.push_back(T->hasExceptionSpec()); 181 Record.push_back(T->hasAnyExceptionSpec()); 182 Record.push_back(T->getNumExceptions()); 183 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I) 184 Writer.AddTypeRef(T->getExceptionType(I), Record); 185 Code = TYPE_FUNCTION_PROTO; 186} 187 188void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) { 189 Writer.AddDeclRef(T->getDecl(), Record); 190 Code = TYPE_UNRESOLVED_USING; 191} 192 193void ASTTypeWriter::VisitTypedefType(const TypedefType *T) { 194 Writer.AddDeclRef(T->getDecl(), Record); 195 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?"); 196 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record); 197 Code = TYPE_TYPEDEF; 198} 199 200void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) { 201 Writer.AddStmt(T->getUnderlyingExpr()); 202 Code = TYPE_TYPEOF_EXPR; 203} 204 205void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) { 206 Writer.AddTypeRef(T->getUnderlyingType(), Record); 207 Code = TYPE_TYPEOF; 208} 209 210void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) { 211 Writer.AddStmt(T->getUnderlyingExpr()); 212 Code = TYPE_DECLTYPE; 213} 214 215void ASTTypeWriter::VisitTagType(const TagType *T) { 216 Record.push_back(T->isDependentType()); 217 Writer.AddDeclRef(T->getDecl(), Record); 218 assert(!T->isBeingDefined() && 219 "Cannot serialize in the middle of a type definition"); 220} 221 222void ASTTypeWriter::VisitRecordType(const RecordType *T) { 223 VisitTagType(T); 224 Code = TYPE_RECORD; 225} 226 227void ASTTypeWriter::VisitEnumType(const EnumType *T) { 228 VisitTagType(T); 229 Code = TYPE_ENUM; 230} 231 232void ASTTypeWriter::VisitAttributedType(const AttributedType *T) { 233 Writer.AddTypeRef(T->getModifiedType(), Record); 234 Writer.AddTypeRef(T->getEquivalentType(), Record); 235 Record.push_back(T->getAttrKind()); 236 Code = TYPE_ATTRIBUTED; 237} 238 239void 240ASTTypeWriter::VisitSubstTemplateTypeParmType( 241 const SubstTemplateTypeParmType *T) { 242 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record); 243 Writer.AddTypeRef(T->getReplacementType(), Record); 244 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM; 245} 246 247void 248ASTTypeWriter::VisitSubstTemplateTypeParmPackType( 249 const SubstTemplateTypeParmPackType *T) { 250 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record); 251 Writer.AddTemplateArgument(T->getArgumentPack(), Record); 252 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK; 253} 254 255void 256ASTTypeWriter::VisitTemplateSpecializationType( 257 const TemplateSpecializationType *T) { 258 Record.push_back(T->isDependentType()); 259 Writer.AddTemplateName(T->getTemplateName(), Record); 260 Record.push_back(T->getNumArgs()); 261 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end(); 262 ArgI != ArgE; ++ArgI) 263 Writer.AddTemplateArgument(*ArgI, Record); 264 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType() 265 : T->getCanonicalTypeInternal(), 266 Record); 267 Code = TYPE_TEMPLATE_SPECIALIZATION; 268} 269 270void 271ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) { 272 VisitArrayType(T); 273 Writer.AddStmt(T->getSizeExpr()); 274 Writer.AddSourceRange(T->getBracketsRange(), Record); 275 Code = TYPE_DEPENDENT_SIZED_ARRAY; 276} 277 278void 279ASTTypeWriter::VisitDependentSizedExtVectorType( 280 const DependentSizedExtVectorType *T) { 281 // FIXME: Serialize this type (C++ only) 282 assert(false && "Cannot serialize dependent sized extended vector types"); 283} 284 285void 286ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) { 287 Record.push_back(T->getDepth()); 288 Record.push_back(T->getIndex()); 289 Record.push_back(T->isParameterPack()); 290 Writer.AddIdentifierRef(T->getName(), Record); 291 Code = TYPE_TEMPLATE_TYPE_PARM; 292} 293 294void 295ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) { 296 Record.push_back(T->getKeyword()); 297 Writer.AddNestedNameSpecifier(T->getQualifier(), Record); 298 Writer.AddIdentifierRef(T->getIdentifier(), Record); 299 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType() 300 : T->getCanonicalTypeInternal(), 301 Record); 302 Code = TYPE_DEPENDENT_NAME; 303} 304 305void 306ASTTypeWriter::VisitDependentTemplateSpecializationType( 307 const DependentTemplateSpecializationType *T) { 308 Record.push_back(T->getKeyword()); 309 Writer.AddNestedNameSpecifier(T->getQualifier(), Record); 310 Writer.AddIdentifierRef(T->getIdentifier(), Record); 311 Record.push_back(T->getNumArgs()); 312 for (DependentTemplateSpecializationType::iterator 313 I = T->begin(), E = T->end(); I != E; ++I) 314 Writer.AddTemplateArgument(*I, Record); 315 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION; 316} 317 318void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) { 319 Writer.AddTypeRef(T->getPattern(), Record); 320 if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions()) 321 Record.push_back(*NumExpansions + 1); 322 else 323 Record.push_back(0); 324 Code = TYPE_PACK_EXPANSION; 325} 326 327void ASTTypeWriter::VisitParenType(const ParenType *T) { 328 Writer.AddTypeRef(T->getInnerType(), Record); 329 Code = TYPE_PAREN; 330} 331 332void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) { 333 Record.push_back(T->getKeyword()); 334 Writer.AddNestedNameSpecifier(T->getQualifier(), Record); 335 Writer.AddTypeRef(T->getNamedType(), Record); 336 Code = TYPE_ELABORATED; 337} 338 339void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) { 340 Writer.AddDeclRef(T->getDecl(), Record); 341 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record); 342 Code = TYPE_INJECTED_CLASS_NAME; 343} 344 345void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { 346 Writer.AddDeclRef(T->getDecl(), Record); 347 Code = TYPE_OBJC_INTERFACE; 348} 349 350void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) { 351 Writer.AddTypeRef(T->getBaseType(), Record); 352 Record.push_back(T->getNumProtocols()); 353 for (ObjCObjectType::qual_iterator I = T->qual_begin(), 354 E = T->qual_end(); I != E; ++I) 355 Writer.AddDeclRef(*I, Record); 356 Code = TYPE_OBJC_OBJECT; 357} 358 359void 360ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { 361 Writer.AddTypeRef(T->getPointeeType(), Record); 362 Code = TYPE_OBJC_OBJECT_POINTER; 363} 364 365namespace { 366 367class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> { 368 ASTWriter &Writer; 369 ASTWriter::RecordDataImpl &Record; 370 371public: 372 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record) 373 : Writer(Writer), Record(Record) { } 374 375#define ABSTRACT_TYPELOC(CLASS, PARENT) 376#define TYPELOC(CLASS, PARENT) \ 377 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); 378#include "clang/AST/TypeLocNodes.def" 379 380 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc); 381 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc); 382}; 383 384} 385 386void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 387 // nothing to do 388} 389void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 390 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record); 391 if (TL.needsExtraLocalData()) { 392 Record.push_back(TL.getWrittenTypeSpec()); 393 Record.push_back(TL.getWrittenSignSpec()); 394 Record.push_back(TL.getWrittenWidthSpec()); 395 Record.push_back(TL.hasModeAttr()); 396 } 397} 398void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) { 399 Writer.AddSourceLocation(TL.getNameLoc(), Record); 400} 401void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) { 402 Writer.AddSourceLocation(TL.getStarLoc(), Record); 403} 404void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 405 Writer.AddSourceLocation(TL.getCaretLoc(), Record); 406} 407void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 408 Writer.AddSourceLocation(TL.getAmpLoc(), Record); 409} 410void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 411 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record); 412} 413void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 414 Writer.AddSourceLocation(TL.getStarLoc(), Record); 415} 416void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) { 417 Writer.AddSourceLocation(TL.getLBracketLoc(), Record); 418 Writer.AddSourceLocation(TL.getRBracketLoc(), Record); 419 Record.push_back(TL.getSizeExpr() ? 1 : 0); 420 if (TL.getSizeExpr()) 421 Writer.AddStmt(TL.getSizeExpr()); 422} 423void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { 424 VisitArrayTypeLoc(TL); 425} 426void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { 427 VisitArrayTypeLoc(TL); 428} 429void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { 430 VisitArrayTypeLoc(TL); 431} 432void TypeLocWriter::VisitDependentSizedArrayTypeLoc( 433 DependentSizedArrayTypeLoc TL) { 434 VisitArrayTypeLoc(TL); 435} 436void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc( 437 DependentSizedExtVectorTypeLoc TL) { 438 Writer.AddSourceLocation(TL.getNameLoc(), Record); 439} 440void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) { 441 Writer.AddSourceLocation(TL.getNameLoc(), Record); 442} 443void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 444 Writer.AddSourceLocation(TL.getNameLoc(), Record); 445} 446void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) { 447 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 448 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 449 Record.push_back(TL.getTrailingReturn()); 450 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 451 Writer.AddDeclRef(TL.getArg(i), Record); 452} 453void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { 454 VisitFunctionTypeLoc(TL); 455} 456void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { 457 VisitFunctionTypeLoc(TL); 458} 459void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 460 Writer.AddSourceLocation(TL.getNameLoc(), Record); 461} 462void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 463 Writer.AddSourceLocation(TL.getNameLoc(), Record); 464} 465void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 466 Writer.AddSourceLocation(TL.getTypeofLoc(), Record); 467 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 468 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 469} 470void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 471 Writer.AddSourceLocation(TL.getTypeofLoc(), Record); 472 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 473 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 474 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record); 475} 476void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 477 Writer.AddSourceLocation(TL.getNameLoc(), Record); 478} 479void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) { 480 Writer.AddSourceLocation(TL.getNameLoc(), Record); 481} 482void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) { 483 Writer.AddSourceLocation(TL.getNameLoc(), Record); 484} 485void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 486 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record); 487 if (TL.hasAttrOperand()) { 488 SourceRange range = TL.getAttrOperandParensRange(); 489 Writer.AddSourceLocation(range.getBegin(), Record); 490 Writer.AddSourceLocation(range.getEnd(), Record); 491 } 492 if (TL.hasAttrExprOperand()) { 493 Expr *operand = TL.getAttrExprOperand(); 494 Record.push_back(operand ? 1 : 0); 495 if (operand) Writer.AddStmt(operand); 496 } else if (TL.hasAttrEnumOperand()) { 497 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record); 498 } 499} 500void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 501 Writer.AddSourceLocation(TL.getNameLoc(), Record); 502} 503void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc( 504 SubstTemplateTypeParmTypeLoc TL) { 505 Writer.AddSourceLocation(TL.getNameLoc(), Record); 506} 507void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc( 508 SubstTemplateTypeParmPackTypeLoc TL) { 509 Writer.AddSourceLocation(TL.getNameLoc(), Record); 510} 511void TypeLocWriter::VisitTemplateSpecializationTypeLoc( 512 TemplateSpecializationTypeLoc TL) { 513 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record); 514 Writer.AddSourceLocation(TL.getLAngleLoc(), Record); 515 Writer.AddSourceLocation(TL.getRAngleLoc(), Record); 516 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 517 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(), 518 TL.getArgLoc(i).getLocInfo(), Record); 519} 520void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) { 521 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 522 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 523} 524void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 525 Writer.AddSourceLocation(TL.getKeywordLoc(), Record); 526 Writer.AddSourceRange(TL.getQualifierRange(), Record); 527} 528void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 529 Writer.AddSourceLocation(TL.getNameLoc(), Record); 530} 531void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 532 Writer.AddSourceLocation(TL.getKeywordLoc(), Record); 533 Writer.AddSourceRange(TL.getQualifierRange(), Record); 534 Writer.AddSourceLocation(TL.getNameLoc(), Record); 535} 536void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc( 537 DependentTemplateSpecializationTypeLoc TL) { 538 Writer.AddSourceLocation(TL.getKeywordLoc(), Record); 539 Writer.AddSourceRange(TL.getQualifierRange(), Record); 540 Writer.AddSourceLocation(TL.getNameLoc(), Record); 541 Writer.AddSourceLocation(TL.getLAngleLoc(), Record); 542 Writer.AddSourceLocation(TL.getRAngleLoc(), Record); 543 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) 544 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(), 545 TL.getArgLoc(I).getLocInfo(), Record); 546} 547void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 548 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record); 549} 550void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 551 Writer.AddSourceLocation(TL.getNameLoc(), Record); 552} 553void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 554 Record.push_back(TL.hasBaseTypeAsWritten()); 555 Writer.AddSourceLocation(TL.getLAngleLoc(), Record); 556 Writer.AddSourceLocation(TL.getRAngleLoc(), Record); 557 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 558 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record); 559} 560void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 561 Writer.AddSourceLocation(TL.getStarLoc(), Record); 562} 563 564//===----------------------------------------------------------------------===// 565// ASTWriter Implementation 566//===----------------------------------------------------------------------===// 567 568static void EmitBlockID(unsigned ID, const char *Name, 569 llvm::BitstreamWriter &Stream, 570 ASTWriter::RecordDataImpl &Record) { 571 Record.clear(); 572 Record.push_back(ID); 573 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record); 574 575 // Emit the block name if present. 576 if (Name == 0 || Name[0] == 0) return; 577 Record.clear(); 578 while (*Name) 579 Record.push_back(*Name++); 580 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record); 581} 582 583static void EmitRecordID(unsigned ID, const char *Name, 584 llvm::BitstreamWriter &Stream, 585 ASTWriter::RecordDataImpl &Record) { 586 Record.clear(); 587 Record.push_back(ID); 588 while (*Name) 589 Record.push_back(*Name++); 590 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record); 591} 592 593static void AddStmtsExprs(llvm::BitstreamWriter &Stream, 594 ASTWriter::RecordDataImpl &Record) { 595#define RECORD(X) EmitRecordID(X, #X, Stream, Record) 596 RECORD(STMT_STOP); 597 RECORD(STMT_NULL_PTR); 598 RECORD(STMT_NULL); 599 RECORD(STMT_COMPOUND); 600 RECORD(STMT_CASE); 601 RECORD(STMT_DEFAULT); 602 RECORD(STMT_LABEL); 603 RECORD(STMT_IF); 604 RECORD(STMT_SWITCH); 605 RECORD(STMT_WHILE); 606 RECORD(STMT_DO); 607 RECORD(STMT_FOR); 608 RECORD(STMT_GOTO); 609 RECORD(STMT_INDIRECT_GOTO); 610 RECORD(STMT_CONTINUE); 611 RECORD(STMT_BREAK); 612 RECORD(STMT_RETURN); 613 RECORD(STMT_DECL); 614 RECORD(STMT_ASM); 615 RECORD(EXPR_PREDEFINED); 616 RECORD(EXPR_DECL_REF); 617 RECORD(EXPR_INTEGER_LITERAL); 618 RECORD(EXPR_FLOATING_LITERAL); 619 RECORD(EXPR_IMAGINARY_LITERAL); 620 RECORD(EXPR_STRING_LITERAL); 621 RECORD(EXPR_CHARACTER_LITERAL); 622 RECORD(EXPR_PAREN); 623 RECORD(EXPR_UNARY_OPERATOR); 624 RECORD(EXPR_SIZEOF_ALIGN_OF); 625 RECORD(EXPR_ARRAY_SUBSCRIPT); 626 RECORD(EXPR_CALL); 627 RECORD(EXPR_MEMBER); 628 RECORD(EXPR_BINARY_OPERATOR); 629 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR); 630 RECORD(EXPR_CONDITIONAL_OPERATOR); 631 RECORD(EXPR_IMPLICIT_CAST); 632 RECORD(EXPR_CSTYLE_CAST); 633 RECORD(EXPR_COMPOUND_LITERAL); 634 RECORD(EXPR_EXT_VECTOR_ELEMENT); 635 RECORD(EXPR_INIT_LIST); 636 RECORD(EXPR_DESIGNATED_INIT); 637 RECORD(EXPR_IMPLICIT_VALUE_INIT); 638 RECORD(EXPR_VA_ARG); 639 RECORD(EXPR_ADDR_LABEL); 640 RECORD(EXPR_STMT); 641 RECORD(EXPR_CHOOSE); 642 RECORD(EXPR_GNU_NULL); 643 RECORD(EXPR_SHUFFLE_VECTOR); 644 RECORD(EXPR_BLOCK); 645 RECORD(EXPR_BLOCK_DECL_REF); 646 RECORD(EXPR_OBJC_STRING_LITERAL); 647 RECORD(EXPR_OBJC_ENCODE); 648 RECORD(EXPR_OBJC_SELECTOR_EXPR); 649 RECORD(EXPR_OBJC_PROTOCOL_EXPR); 650 RECORD(EXPR_OBJC_IVAR_REF_EXPR); 651 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR); 652 RECORD(EXPR_OBJC_KVC_REF_EXPR); 653 RECORD(EXPR_OBJC_MESSAGE_EXPR); 654 RECORD(STMT_OBJC_FOR_COLLECTION); 655 RECORD(STMT_OBJC_CATCH); 656 RECORD(STMT_OBJC_FINALLY); 657 RECORD(STMT_OBJC_AT_TRY); 658 RECORD(STMT_OBJC_AT_SYNCHRONIZED); 659 RECORD(STMT_OBJC_AT_THROW); 660 RECORD(EXPR_CXX_OPERATOR_CALL); 661 RECORD(EXPR_CXX_CONSTRUCT); 662 RECORD(EXPR_CXX_STATIC_CAST); 663 RECORD(EXPR_CXX_DYNAMIC_CAST); 664 RECORD(EXPR_CXX_REINTERPRET_CAST); 665 RECORD(EXPR_CXX_CONST_CAST); 666 RECORD(EXPR_CXX_FUNCTIONAL_CAST); 667 RECORD(EXPR_CXX_BOOL_LITERAL); 668 RECORD(EXPR_CXX_NULL_PTR_LITERAL); 669 RECORD(EXPR_CXX_TYPEID_EXPR); 670 RECORD(EXPR_CXX_TYPEID_TYPE); 671 RECORD(EXPR_CXX_UUIDOF_EXPR); 672 RECORD(EXPR_CXX_UUIDOF_TYPE); 673 RECORD(EXPR_CXX_THIS); 674 RECORD(EXPR_CXX_THROW); 675 RECORD(EXPR_CXX_DEFAULT_ARG); 676 RECORD(EXPR_CXX_BIND_TEMPORARY); 677 RECORD(EXPR_CXX_SCALAR_VALUE_INIT); 678 RECORD(EXPR_CXX_NEW); 679 RECORD(EXPR_CXX_DELETE); 680 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR); 681 RECORD(EXPR_EXPR_WITH_CLEANUPS); 682 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER); 683 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF); 684 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT); 685 RECORD(EXPR_CXX_UNRESOLVED_MEMBER); 686 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP); 687 RECORD(EXPR_CXX_UNARY_TYPE_TRAIT); 688 RECORD(EXPR_CXX_NOEXCEPT); 689 RECORD(EXPR_OPAQUE_VALUE); 690 RECORD(EXPR_BINARY_TYPE_TRAIT); 691 RECORD(EXPR_PACK_EXPANSION); 692 RECORD(EXPR_SIZEOF_PACK); 693 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK); 694#undef RECORD 695} 696 697void ASTWriter::WriteBlockInfoBlock() { 698 RecordData Record; 699 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3); 700 701#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record) 702#define RECORD(X) EmitRecordID(X, #X, Stream, Record) 703 704 // AST Top-Level Block. 705 BLOCK(AST_BLOCK); 706 RECORD(ORIGINAL_FILE_NAME); 707 RECORD(TYPE_OFFSET); 708 RECORD(DECL_OFFSET); 709 RECORD(LANGUAGE_OPTIONS); 710 RECORD(METADATA); 711 RECORD(IDENTIFIER_OFFSET); 712 RECORD(IDENTIFIER_TABLE); 713 RECORD(EXTERNAL_DEFINITIONS); 714 RECORD(SPECIAL_TYPES); 715 RECORD(STATISTICS); 716 RECORD(TENTATIVE_DEFINITIONS); 717 RECORD(UNUSED_FILESCOPED_DECLS); 718 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS); 719 RECORD(SELECTOR_OFFSETS); 720 RECORD(METHOD_POOL); 721 RECORD(PP_COUNTER_VALUE); 722 RECORD(SOURCE_LOCATION_OFFSETS); 723 RECORD(SOURCE_LOCATION_PRELOADS); 724 RECORD(STAT_CACHE); 725 RECORD(EXT_VECTOR_DECLS); 726 RECORD(VERSION_CONTROL_BRANCH_REVISION); 727 RECORD(MACRO_DEFINITION_OFFSETS); 728 RECORD(CHAINED_METADATA); 729 RECORD(REFERENCED_SELECTOR_POOL); 730 RECORD(TU_UPDATE_LEXICAL); 731 RECORD(REDECLS_UPDATE_LATEST); 732 RECORD(SEMA_DECL_REFS); 733 RECORD(WEAK_UNDECLARED_IDENTIFIERS); 734 RECORD(PENDING_IMPLICIT_INSTANTIATIONS); 735 RECORD(DECL_REPLACEMENTS); 736 RECORD(UPDATE_VISIBLE); 737 RECORD(DECL_UPDATE_OFFSETS); 738 RECORD(DECL_UPDATES); 739 RECORD(CXX_BASE_SPECIFIER_OFFSETS); 740 RECORD(DIAG_PRAGMA_MAPPINGS); 741 742 // SourceManager Block. 743 BLOCK(SOURCE_MANAGER_BLOCK); 744 RECORD(SM_SLOC_FILE_ENTRY); 745 RECORD(SM_SLOC_BUFFER_ENTRY); 746 RECORD(SM_SLOC_BUFFER_BLOB); 747 RECORD(SM_SLOC_INSTANTIATION_ENTRY); 748 RECORD(SM_LINE_TABLE); 749 750 // Preprocessor Block. 751 BLOCK(PREPROCESSOR_BLOCK); 752 RECORD(PP_MACRO_OBJECT_LIKE); 753 RECORD(PP_MACRO_FUNCTION_LIKE); 754 RECORD(PP_TOKEN); 755 756 // Decls and Types block. 757 BLOCK(DECLTYPES_BLOCK); 758 RECORD(TYPE_EXT_QUAL); 759 RECORD(TYPE_COMPLEX); 760 RECORD(TYPE_POINTER); 761 RECORD(TYPE_BLOCK_POINTER); 762 RECORD(TYPE_LVALUE_REFERENCE); 763 RECORD(TYPE_RVALUE_REFERENCE); 764 RECORD(TYPE_MEMBER_POINTER); 765 RECORD(TYPE_CONSTANT_ARRAY); 766 RECORD(TYPE_INCOMPLETE_ARRAY); 767 RECORD(TYPE_VARIABLE_ARRAY); 768 RECORD(TYPE_VECTOR); 769 RECORD(TYPE_EXT_VECTOR); 770 RECORD(TYPE_FUNCTION_PROTO); 771 RECORD(TYPE_FUNCTION_NO_PROTO); 772 RECORD(TYPE_TYPEDEF); 773 RECORD(TYPE_TYPEOF_EXPR); 774 RECORD(TYPE_TYPEOF); 775 RECORD(TYPE_RECORD); 776 RECORD(TYPE_ENUM); 777 RECORD(TYPE_OBJC_INTERFACE); 778 RECORD(TYPE_OBJC_OBJECT); 779 RECORD(TYPE_OBJC_OBJECT_POINTER); 780 RECORD(TYPE_DECLTYPE); 781 RECORD(TYPE_ELABORATED); 782 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM); 783 RECORD(TYPE_UNRESOLVED_USING); 784 RECORD(TYPE_INJECTED_CLASS_NAME); 785 RECORD(TYPE_OBJC_OBJECT); 786 RECORD(TYPE_TEMPLATE_TYPE_PARM); 787 RECORD(TYPE_TEMPLATE_SPECIALIZATION); 788 RECORD(TYPE_DEPENDENT_NAME); 789 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION); 790 RECORD(TYPE_DEPENDENT_SIZED_ARRAY); 791 RECORD(TYPE_PAREN); 792 RECORD(TYPE_PACK_EXPANSION); 793 RECORD(TYPE_ATTRIBUTED); 794 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK); 795 RECORD(DECL_TRANSLATION_UNIT); 796 RECORD(DECL_TYPEDEF); 797 RECORD(DECL_ENUM); 798 RECORD(DECL_RECORD); 799 RECORD(DECL_ENUM_CONSTANT); 800 RECORD(DECL_FUNCTION); 801 RECORD(DECL_OBJC_METHOD); 802 RECORD(DECL_OBJC_INTERFACE); 803 RECORD(DECL_OBJC_PROTOCOL); 804 RECORD(DECL_OBJC_IVAR); 805 RECORD(DECL_OBJC_AT_DEFS_FIELD); 806 RECORD(DECL_OBJC_CLASS); 807 RECORD(DECL_OBJC_FORWARD_PROTOCOL); 808 RECORD(DECL_OBJC_CATEGORY); 809 RECORD(DECL_OBJC_CATEGORY_IMPL); 810 RECORD(DECL_OBJC_IMPLEMENTATION); 811 RECORD(DECL_OBJC_COMPATIBLE_ALIAS); 812 RECORD(DECL_OBJC_PROPERTY); 813 RECORD(DECL_OBJC_PROPERTY_IMPL); 814 RECORD(DECL_FIELD); 815 RECORD(DECL_VAR); 816 RECORD(DECL_IMPLICIT_PARAM); 817 RECORD(DECL_PARM_VAR); 818 RECORD(DECL_FILE_SCOPE_ASM); 819 RECORD(DECL_BLOCK); 820 RECORD(DECL_CONTEXT_LEXICAL); 821 RECORD(DECL_CONTEXT_VISIBLE); 822 RECORD(DECL_NAMESPACE); 823 RECORD(DECL_NAMESPACE_ALIAS); 824 RECORD(DECL_USING); 825 RECORD(DECL_USING_SHADOW); 826 RECORD(DECL_USING_DIRECTIVE); 827 RECORD(DECL_UNRESOLVED_USING_VALUE); 828 RECORD(DECL_UNRESOLVED_USING_TYPENAME); 829 RECORD(DECL_LINKAGE_SPEC); 830 RECORD(DECL_CXX_RECORD); 831 RECORD(DECL_CXX_METHOD); 832 RECORD(DECL_CXX_CONSTRUCTOR); 833 RECORD(DECL_CXX_DESTRUCTOR); 834 RECORD(DECL_CXX_CONVERSION); 835 RECORD(DECL_ACCESS_SPEC); 836 RECORD(DECL_FRIEND); 837 RECORD(DECL_FRIEND_TEMPLATE); 838 RECORD(DECL_CLASS_TEMPLATE); 839 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION); 840 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION); 841 RECORD(DECL_FUNCTION_TEMPLATE); 842 RECORD(DECL_TEMPLATE_TYPE_PARM); 843 RECORD(DECL_NON_TYPE_TEMPLATE_PARM); 844 RECORD(DECL_TEMPLATE_TEMPLATE_PARM); 845 RECORD(DECL_STATIC_ASSERT); 846 RECORD(DECL_CXX_BASE_SPECIFIERS); 847 RECORD(DECL_INDIRECTFIELD); 848 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK); 849 850 BLOCK(PREPROCESSOR_DETAIL_BLOCK); 851 RECORD(PPD_MACRO_INSTANTIATION); 852 RECORD(PPD_MACRO_DEFINITION); 853 RECORD(PPD_INCLUSION_DIRECTIVE); 854 855 // Statements and Exprs can occur in the Decls and Types block. 856 AddStmtsExprs(Stream, Record); 857#undef RECORD 858#undef BLOCK 859 Stream.ExitBlock(); 860} 861 862/// \brief Adjusts the given filename to only write out the portion of the 863/// filename that is not part of the system root directory. 864/// 865/// \param Filename the file name to adjust. 866/// 867/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and 868/// the returned filename will be adjusted by this system root. 869/// 870/// \returns either the original filename (if it needs no adjustment) or the 871/// adjusted filename (which points into the @p Filename parameter). 872static const char * 873adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) { 874 assert(Filename && "No file name to adjust?"); 875 876 if (!isysroot) 877 return Filename; 878 879 // Verify that the filename and the system root have the same prefix. 880 unsigned Pos = 0; 881 for (; Filename[Pos] && isysroot[Pos]; ++Pos) 882 if (Filename[Pos] != isysroot[Pos]) 883 return Filename; // Prefixes don't match. 884 885 // We hit the end of the filename before we hit the end of the system root. 886 if (!Filename[Pos]) 887 return Filename; 888 889 // If the file name has a '/' at the current position, skip over the '/'. 890 // We distinguish sysroot-based includes from absolute includes by the 891 // absence of '/' at the beginning of sysroot-based includes. 892 if (Filename[Pos] == '/') 893 ++Pos; 894 895 return Filename + Pos; 896} 897 898/// \brief Write the AST metadata (e.g., i686-apple-darwin9). 899void ASTWriter::WriteMetadata(ASTContext &Context, const char *isysroot) { 900 using namespace llvm; 901 902 // Metadata 903 const TargetInfo &Target = Context.Target; 904 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev(); 905 MetaAbbrev->Add(BitCodeAbbrevOp( 906 Chain ? CHAINED_METADATA : METADATA)); 907 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major 908 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor 909 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major 910 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor 911 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable 912 // Target triple or chained PCH name 913 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 914 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev); 915 916 RecordData Record; 917 Record.push_back(Chain ? CHAINED_METADATA : METADATA); 918 Record.push_back(VERSION_MAJOR); 919 Record.push_back(VERSION_MINOR); 920 Record.push_back(CLANG_VERSION_MAJOR); 921 Record.push_back(CLANG_VERSION_MINOR); 922 Record.push_back(isysroot != 0); 923 // FIXME: This writes the absolute path for chained headers. 924 const std::string &BlobStr = Chain ? Chain->getFileName() : Target.getTriple().getTriple(); 925 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, BlobStr); 926 927 // Original file name 928 SourceManager &SM = Context.getSourceManager(); 929 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 930 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev(); 931 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME)); 932 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 933 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev); 934 935 llvm::SmallString<128> MainFilePath(MainFile->getName()); 936 937 llvm::sys::fs::make_absolute(MainFilePath); 938 939 const char *MainFileNameStr = MainFilePath.c_str(); 940 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr, 941 isysroot); 942 RecordData Record; 943 Record.push_back(ORIGINAL_FILE_NAME); 944 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr); 945 } 946 947 // Repository branch/version information. 948 BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev(); 949 RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION)); 950 RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag 951 unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev); 952 Record.clear(); 953 Record.push_back(VERSION_CONTROL_BRANCH_REVISION); 954 Stream.EmitRecordWithBlob(RepoAbbrevCode, Record, 955 getClangFullRepositoryVersion()); 956} 957 958/// \brief Write the LangOptions structure. 959void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) { 960 RecordData Record; 961 Record.push_back(LangOpts.Trigraphs); 962 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments. 963 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers. 964 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode. 965 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc) 966 Record.push_back(LangOpts.GNUKeywords); // Allow GNU-extension keywords 967 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'. 968 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++ 969 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants. 970 Record.push_back(LangOpts.C99); // C99 Support 971 Record.push_back(LangOpts.Microsoft); // Microsoft extensions. 972 // LangOpts.MSCVersion is ignored because all it does it set a macro, which is 973 // already saved elsewhere. 974 Record.push_back(LangOpts.CPlusPlus); // C++ Support 975 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support 976 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords. 977 978 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled. 979 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled. 980 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C 981 // modern abi enabled. 982 Record.push_back(LangOpts.ObjCNonFragileABI2); // Objective-C enhanced 983 // modern abi enabled. 984 Record.push_back(LangOpts.AppleKext); // Apple's kernel extensions ABI 985 Record.push_back(LangOpts.ObjCDefaultSynthProperties); // Objective-C auto-synthesized 986 // properties enabled. 987 Record.push_back(LangOpts.NoConstantCFStrings); // non cfstring generation enabled.. 988 989 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings 990 Record.push_back(LangOpts.WritableStrings); // Allow writable strings 991 Record.push_back(LangOpts.LaxVectorConversions); 992 Record.push_back(LangOpts.AltiVec); 993 Record.push_back(LangOpts.Exceptions); // Support exception handling. 994 Record.push_back(LangOpts.SjLjExceptions); 995 996 Record.push_back(LangOpts.MSBitfields); // MS-compatible structure layout 997 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime. 998 Record.push_back(LangOpts.Freestanding); // Freestanding implementation 999 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin) 1000 1001 // Whether static initializers are protected by locks. 1002 Record.push_back(LangOpts.ThreadsafeStatics); 1003 Record.push_back(LangOpts.POSIXThreads); 1004 Record.push_back(LangOpts.Blocks); // block extension to C 1005 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if 1006 // they are unused. 1007 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno 1008 // (modulo the platform support). 1009 1010 Record.push_back(LangOpts.getSignedOverflowBehavior()); 1011 Record.push_back(LangOpts.HeinousExtensions); 1012 1013 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined. 1014 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be 1015 // defined. 1016 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as 1017 // opposed to __DYNAMIC__). 1018 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero. 1019 1020 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be 1021 // used (instead of C99 semantics). 1022 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined. 1023 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should 1024 // be enabled. 1025 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or 1026 // unsigned type 1027 Record.push_back(LangOpts.ShortWChar); // force wchar_t to be unsigned short 1028 Record.push_back(LangOpts.ShortEnums); // Should the enum type be equivalent 1029 // to the smallest integer type with 1030 // enough room. 1031 Record.push_back(LangOpts.getGCMode()); 1032 Record.push_back(LangOpts.getVisibilityMode()); 1033 Record.push_back(LangOpts.getStackProtectorMode()); 1034 Record.push_back(LangOpts.InstantiationDepth); 1035 Record.push_back(LangOpts.OpenCL); 1036 Record.push_back(LangOpts.CUDA); 1037 Record.push_back(LangOpts.CatchUndefined); 1038 Record.push_back(LangOpts.ElideConstructors); 1039 Record.push_back(LangOpts.SpellChecking); 1040 Stream.EmitRecord(LANGUAGE_OPTIONS, Record); 1041} 1042 1043//===----------------------------------------------------------------------===// 1044// stat cache Serialization 1045//===----------------------------------------------------------------------===// 1046 1047namespace { 1048// Trait used for the on-disk hash table of stat cache results. 1049class ASTStatCacheTrait { 1050public: 1051 typedef const char * key_type; 1052 typedef key_type key_type_ref; 1053 1054 typedef struct stat data_type; 1055 typedef const data_type &data_type_ref; 1056 1057 static unsigned ComputeHash(const char *path) { 1058 return llvm::HashString(path); 1059 } 1060 1061 std::pair<unsigned,unsigned> 1062 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path, 1063 data_type_ref Data) { 1064 unsigned StrLen = strlen(path); 1065 clang::io::Emit16(Out, StrLen); 1066 unsigned DataLen = 4 + 4 + 2 + 8 + 8; 1067 clang::io::Emit8(Out, DataLen); 1068 return std::make_pair(StrLen + 1, DataLen); 1069 } 1070 1071 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) { 1072 Out.write(path, KeyLen); 1073 } 1074 1075 void EmitData(llvm::raw_ostream &Out, key_type_ref, 1076 data_type_ref Data, unsigned DataLen) { 1077 using namespace clang::io; 1078 uint64_t Start = Out.tell(); (void)Start; 1079 1080 Emit32(Out, (uint32_t) Data.st_ino); 1081 Emit32(Out, (uint32_t) Data.st_dev); 1082 Emit16(Out, (uint16_t) Data.st_mode); 1083 Emit64(Out, (uint64_t) Data.st_mtime); 1084 Emit64(Out, (uint64_t) Data.st_size); 1085 1086 assert(Out.tell() - Start == DataLen && "Wrong data length"); 1087 } 1088}; 1089} // end anonymous namespace 1090 1091/// \brief Write the stat() system call cache to the AST file. 1092void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) { 1093 // Build the on-disk hash table containing information about every 1094 // stat() call. 1095 OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator; 1096 unsigned NumStatEntries = 0; 1097 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(), 1098 StatEnd = StatCalls.end(); 1099 Stat != StatEnd; ++Stat, ++NumStatEntries) { 1100 const char *Filename = Stat->first(); 1101 Generator.insert(Filename, Stat->second); 1102 } 1103 1104 // Create the on-disk hash table in a buffer. 1105 llvm::SmallString<4096> StatCacheData; 1106 uint32_t BucketOffset; 1107 { 1108 llvm::raw_svector_ostream Out(StatCacheData); 1109 // Make sure that no bucket is at offset 0 1110 clang::io::Emit32(Out, 0); 1111 BucketOffset = Generator.Emit(Out); 1112 } 1113 1114 // Create a blob abbreviation 1115 using namespace llvm; 1116 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1117 Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE)); 1118 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1119 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1120 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1121 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev); 1122 1123 // Write the stat cache 1124 RecordData Record; 1125 Record.push_back(STAT_CACHE); 1126 Record.push_back(BucketOffset); 1127 Record.push_back(NumStatEntries); 1128 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str()); 1129} 1130 1131//===----------------------------------------------------------------------===// 1132// Source Manager Serialization 1133//===----------------------------------------------------------------------===// 1134 1135/// \brief Create an abbreviation for the SLocEntry that refers to a 1136/// file. 1137static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) { 1138 using namespace llvm; 1139 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1140 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY)); 1141 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1142 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1143 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 1144 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1145 // FileEntry fields. 1146 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size 1147 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time 1148 // HeaderFileInfo fields. 1149 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isImport 1150 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // DirInfo 1151 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumIncludes 1152 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // ControllingMacro 1153 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1154 return Stream.EmitAbbrev(Abbrev); 1155} 1156 1157/// \brief Create an abbreviation for the SLocEntry that refers to a 1158/// buffer. 1159static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) { 1160 using namespace llvm; 1161 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1162 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY)); 1163 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1164 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1165 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 1166 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1167 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob 1168 return Stream.EmitAbbrev(Abbrev); 1169} 1170 1171/// \brief Create an abbreviation for the SLocEntry that refers to a 1172/// buffer's blob. 1173static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) { 1174 using namespace llvm; 1175 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1176 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB)); 1177 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob 1178 return Stream.EmitAbbrev(Abbrev); 1179} 1180 1181/// \brief Create an abbreviation for the SLocEntry that refers to an 1182/// buffer. 1183static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) { 1184 using namespace llvm; 1185 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1186 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_INSTANTIATION_ENTRY)); 1187 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1188 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location 1189 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location 1190 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location 1191 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length 1192 return Stream.EmitAbbrev(Abbrev); 1193} 1194 1195/// \brief Writes the block containing the serialized form of the 1196/// source manager. 1197/// 1198/// TODO: We should probably use an on-disk hash table (stored in a 1199/// blob), indexed based on the file name, so that we only create 1200/// entries for files that we actually need. In the common case (no 1201/// errors), we probably won't have to create file entries for any of 1202/// the files in the AST. 1203void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, 1204 const Preprocessor &PP, 1205 const char *isysroot) { 1206 RecordData Record; 1207 1208 // Enter the source manager block. 1209 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3); 1210 1211 // Abbreviations for the various kinds of source-location entries. 1212 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream); 1213 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream); 1214 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream); 1215 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream); 1216 1217 // Write the line table. 1218 if (SourceMgr.hasLineTable()) { 1219 LineTableInfo &LineTable = SourceMgr.getLineTable(); 1220 1221 // Emit the file names 1222 Record.push_back(LineTable.getNumFilenames()); 1223 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) { 1224 // Emit the file name 1225 const char *Filename = LineTable.getFilename(I); 1226 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1227 unsigned FilenameLen = Filename? strlen(Filename) : 0; 1228 Record.push_back(FilenameLen); 1229 if (FilenameLen) 1230 Record.insert(Record.end(), Filename, Filename + FilenameLen); 1231 } 1232 1233 // Emit the line entries 1234 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end(); 1235 L != LEnd; ++L) { 1236 // Emit the file ID 1237 Record.push_back(L->first); 1238 1239 // Emit the line entries 1240 Record.push_back(L->second.size()); 1241 for (std::vector<LineEntry>::iterator LE = L->second.begin(), 1242 LEEnd = L->second.end(); 1243 LE != LEEnd; ++LE) { 1244 Record.push_back(LE->FileOffset); 1245 Record.push_back(LE->LineNo); 1246 Record.push_back(LE->FilenameID); 1247 Record.push_back((unsigned)LE->FileKind); 1248 Record.push_back(LE->IncludeOffset); 1249 } 1250 } 1251 Stream.EmitRecord(SM_LINE_TABLE, Record); 1252 } 1253 1254 // Write out the source location entry table. We skip the first 1255 // entry, which is always the same dummy entry. 1256 std::vector<uint32_t> SLocEntryOffsets; 1257 RecordData PreloadSLocs; 1258 unsigned BaseSLocID = Chain ? Chain->getTotalNumSLocs() : 0; 1259 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1 - BaseSLocID); 1260 for (unsigned I = BaseSLocID + 1, N = SourceMgr.sloc_entry_size(); 1261 I != N; ++I) { 1262 // Get this source location entry. 1263 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getSLocEntry(I); 1264 1265 // Record the offset of this source-location entry. 1266 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo()); 1267 1268 // Figure out which record code to use. 1269 unsigned Code; 1270 if (SLoc->isFile()) { 1271 if (SLoc->getFile().getContentCache()->Entry) 1272 Code = SM_SLOC_FILE_ENTRY; 1273 else 1274 Code = SM_SLOC_BUFFER_ENTRY; 1275 } else 1276 Code = SM_SLOC_INSTANTIATION_ENTRY; 1277 Record.clear(); 1278 Record.push_back(Code); 1279 1280 Record.push_back(SLoc->getOffset()); 1281 if (SLoc->isFile()) { 1282 const SrcMgr::FileInfo &File = SLoc->getFile(); 1283 Record.push_back(File.getIncludeLoc().getRawEncoding()); 1284 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding 1285 Record.push_back(File.hasLineDirectives()); 1286 1287 const SrcMgr::ContentCache *Content = File.getContentCache(); 1288 if (Content->Entry) { 1289 // The source location entry is a file. The blob associated 1290 // with this entry is the file name. 1291 1292 // Emit size/modification time for this file. 1293 Record.push_back(Content->Entry->getSize()); 1294 Record.push_back(Content->Entry->getModificationTime()); 1295 1296 // Emit header-search information associated with this file. 1297 HeaderFileInfo HFI; 1298 HeaderSearch &HS = PP.getHeaderSearchInfo(); 1299 if (Content->Entry->getUID() < HS.header_file_size()) 1300 HFI = HS.header_file_begin()[Content->Entry->getUID()]; 1301 Record.push_back(HFI.isImport); 1302 Record.push_back(HFI.DirInfo); 1303 Record.push_back(HFI.NumIncludes); 1304 AddIdentifierRef(HFI.ControllingMacro, Record); 1305 1306 // Turn the file name into an absolute path, if it isn't already. 1307 const char *Filename = Content->Entry->getName(); 1308 llvm::SmallString<128> FilePath(Filename); 1309 llvm::sys::fs::make_absolute(FilePath); 1310 Filename = FilePath.c_str(); 1311 1312 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1313 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename); 1314 1315 // FIXME: For now, preload all file source locations, so that 1316 // we get the appropriate File entries in the reader. This is 1317 // a temporary measure. 1318 PreloadSLocs.push_back(BaseSLocID + SLocEntryOffsets.size()); 1319 } else { 1320 // The source location entry is a buffer. The blob associated 1321 // with this entry contains the contents of the buffer. 1322 1323 // We add one to the size so that we capture the trailing NULL 1324 // that is required by llvm::MemoryBuffer::getMemBuffer (on 1325 // the reader side). 1326 const llvm::MemoryBuffer *Buffer 1327 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager()); 1328 const char *Name = Buffer->getBufferIdentifier(); 1329 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, 1330 llvm::StringRef(Name, strlen(Name) + 1)); 1331 Record.clear(); 1332 Record.push_back(SM_SLOC_BUFFER_BLOB); 1333 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, 1334 llvm::StringRef(Buffer->getBufferStart(), 1335 Buffer->getBufferSize() + 1)); 1336 1337 if (strcmp(Name, "<built-in>") == 0) 1338 PreloadSLocs.push_back(BaseSLocID + SLocEntryOffsets.size()); 1339 } 1340 } else { 1341 // The source location entry is an instantiation. 1342 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation(); 1343 Record.push_back(Inst.getSpellingLoc().getRawEncoding()); 1344 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding()); 1345 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding()); 1346 1347 // Compute the token length for this macro expansion. 1348 unsigned NextOffset = SourceMgr.getNextOffset(); 1349 if (I + 1 != N) 1350 NextOffset = SourceMgr.getSLocEntry(I + 1).getOffset(); 1351 Record.push_back(NextOffset - SLoc->getOffset() - 1); 1352 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record); 1353 } 1354 } 1355 1356 Stream.ExitBlock(); 1357 1358 if (SLocEntryOffsets.empty()) 1359 return; 1360 1361 // Write the source-location offsets table into the AST block. This 1362 // table is used for lazily loading source-location information. 1363 using namespace llvm; 1364 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1365 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS)); 1366 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 1367 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset 1368 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 1369 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); 1370 1371 Record.clear(); 1372 Record.push_back(SOURCE_LOCATION_OFFSETS); 1373 Record.push_back(SLocEntryOffsets.size()); 1374 unsigned BaseOffset = Chain ? Chain->getNextSLocOffset() : 0; 1375 Record.push_back(SourceMgr.getNextOffset() - BaseOffset); 1376 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, 1377 (const char *)data(SLocEntryOffsets), 1378 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0])); 1379 1380 // Write the source location entry preloads array, telling the AST 1381 // reader which source locations entries it should load eagerly. 1382 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs); 1383} 1384 1385//===----------------------------------------------------------------------===// 1386// Preprocessor Serialization 1387//===----------------------------------------------------------------------===// 1388 1389/// \brief Writes the block containing the serialized form of the 1390/// preprocessor. 1391/// 1392void ASTWriter::WritePreprocessor(const Preprocessor &PP) { 1393 RecordData Record; 1394 1395 // If the preprocessor __COUNTER__ value has been bumped, remember it. 1396 if (PP.getCounterValue() != 0) { 1397 Record.push_back(PP.getCounterValue()); 1398 Stream.EmitRecord(PP_COUNTER_VALUE, Record); 1399 Record.clear(); 1400 } 1401 1402 // Enter the preprocessor block. 1403 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3); 1404 1405 // If the AST file contains __DATE__ or __TIME__ emit a warning about this. 1406 // FIXME: use diagnostics subsystem for localization etc. 1407 if (PP.SawDateOrTime()) 1408 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n"); 1409 1410 1411 // Loop over all the macro definitions that are live at the end of the file, 1412 // emitting each to the PP section. 1413 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 1414 1415 // FIXME: If we are chaining, don't visit all of the macros! 1416 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end(); 1417 I != E; ++I) { 1418 // FIXME: This emits macros in hash table order, we should do it in a stable 1419 // order so that output is reproducible. 1420 MacroInfo *MI = I->second; 1421 1422 // Don't emit builtin macros like __LINE__ to the AST file unless they have 1423 // been redefined by the header (in which case they are not isBuiltinMacro). 1424 // Also skip macros from a AST file if we're chaining. 1425 1426 // FIXME: There is a (probably minor) optimization we could do here, if 1427 // the macro comes from the original PCH but the identifier comes from a 1428 // chained PCH, by storing the offset into the original PCH rather than 1429 // writing the macro definition a second time. 1430 if (MI->isBuiltinMacro() || 1431 (Chain && I->first->isFromAST() && MI->isFromAST())) 1432 continue; 1433 1434 AddIdentifierRef(I->first, Record); 1435 MacroOffsets[I->first] = Stream.GetCurrentBitNo(); 1436 Record.push_back(MI->getDefinitionLoc().getRawEncoding()); 1437 Record.push_back(MI->isUsed()); 1438 1439 unsigned Code; 1440 if (MI->isObjectLike()) { 1441 Code = PP_MACRO_OBJECT_LIKE; 1442 } else { 1443 Code = PP_MACRO_FUNCTION_LIKE; 1444 1445 Record.push_back(MI->isC99Varargs()); 1446 Record.push_back(MI->isGNUVarargs()); 1447 Record.push_back(MI->getNumArgs()); 1448 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); 1449 I != E; ++I) 1450 AddIdentifierRef(*I, Record); 1451 } 1452 1453 // If we have a detailed preprocessing record, record the macro definition 1454 // ID that corresponds to this macro. 1455 if (PPRec) 1456 Record.push_back(getMacroDefinitionID(PPRec->findMacroDefinition(MI))); 1457 1458 Stream.EmitRecord(Code, Record); 1459 Record.clear(); 1460 1461 // Emit the tokens array. 1462 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) { 1463 // Note that we know that the preprocessor does not have any annotation 1464 // tokens in it because they are created by the parser, and thus can't be 1465 // in a macro definition. 1466 const Token &Tok = MI->getReplacementToken(TokNo); 1467 1468 Record.push_back(Tok.getLocation().getRawEncoding()); 1469 Record.push_back(Tok.getLength()); 1470 1471 // FIXME: When reading literal tokens, reconstruct the literal pointer if 1472 // it is needed. 1473 AddIdentifierRef(Tok.getIdentifierInfo(), Record); 1474 1475 // FIXME: Should translate token kind to a stable encoding. 1476 Record.push_back(Tok.getKind()); 1477 // FIXME: Should translate token flags to a stable encoding. 1478 Record.push_back(Tok.getFlags()); 1479 1480 Stream.EmitRecord(PP_TOKEN, Record); 1481 Record.clear(); 1482 } 1483 ++NumMacros; 1484 } 1485 Stream.ExitBlock(); 1486 1487 if (PPRec) 1488 WritePreprocessorDetail(*PPRec); 1489} 1490 1491void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) { 1492 if (PPRec.begin(Chain) == PPRec.end(Chain)) 1493 return; 1494 1495 // Enter the preprocessor block. 1496 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3); 1497 1498 // If the preprocessor has a preprocessing record, emit it. 1499 unsigned NumPreprocessingRecords = 0; 1500 using namespace llvm; 1501 1502 // Set up the abbreviation for 1503 unsigned InclusionAbbrev = 0; 1504 { 1505 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1506 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE)); 1507 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index 1508 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // start location 1509 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // end location 1510 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length 1511 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes 1512 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind 1513 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1514 InclusionAbbrev = Stream.EmitAbbrev(Abbrev); 1515 } 1516 1517 unsigned IndexBase = Chain ? PPRec.getNumPreallocatedEntities() : 0; 1518 RecordData Record; 1519 for (PreprocessingRecord::iterator E = PPRec.begin(Chain), 1520 EEnd = PPRec.end(Chain); 1521 E != EEnd; ++E) { 1522 Record.clear(); 1523 1524 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) { 1525 // Record this macro definition's location. 1526 MacroID ID = getMacroDefinitionID(MD); 1527 1528 // Don't write the macro definition if it is from another AST file. 1529 if (ID < FirstMacroID) 1530 continue; 1531 1532 // Notify the serialization listener that we're serializing this entity. 1533 if (SerializationListener) 1534 SerializationListener->SerializedPreprocessedEntity(*E, 1535 Stream.GetCurrentBitNo()); 1536 1537 unsigned Position = ID - FirstMacroID; 1538 if (Position != MacroDefinitionOffsets.size()) { 1539 if (Position > MacroDefinitionOffsets.size()) 1540 MacroDefinitionOffsets.resize(Position + 1); 1541 1542 MacroDefinitionOffsets[Position] = Stream.GetCurrentBitNo(); 1543 } else 1544 MacroDefinitionOffsets.push_back(Stream.GetCurrentBitNo()); 1545 1546 Record.push_back(IndexBase + NumPreprocessingRecords++); 1547 Record.push_back(ID); 1548 AddSourceLocation(MD->getSourceRange().getBegin(), Record); 1549 AddSourceLocation(MD->getSourceRange().getEnd(), Record); 1550 AddIdentifierRef(MD->getName(), Record); 1551 AddSourceLocation(MD->getLocation(), Record); 1552 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record); 1553 continue; 1554 } 1555 1556 // Notify the serialization listener that we're serializing this entity. 1557 if (SerializationListener) 1558 SerializationListener->SerializedPreprocessedEntity(*E, 1559 Stream.GetCurrentBitNo()); 1560 1561 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) { 1562 Record.push_back(IndexBase + NumPreprocessingRecords++); 1563 AddSourceLocation(MI->getSourceRange().getBegin(), Record); 1564 AddSourceLocation(MI->getSourceRange().getEnd(), Record); 1565 AddIdentifierRef(MI->getName(), Record); 1566 Record.push_back(getMacroDefinitionID(MI->getDefinition())); 1567 Stream.EmitRecord(PPD_MACRO_INSTANTIATION, Record); 1568 continue; 1569 } 1570 1571 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) { 1572 Record.push_back(PPD_INCLUSION_DIRECTIVE); 1573 Record.push_back(IndexBase + NumPreprocessingRecords++); 1574 AddSourceLocation(ID->getSourceRange().getBegin(), Record); 1575 AddSourceLocation(ID->getSourceRange().getEnd(), Record); 1576 Record.push_back(ID->getFileName().size()); 1577 Record.push_back(ID->wasInQuotes()); 1578 Record.push_back(static_cast<unsigned>(ID->getKind())); 1579 llvm::SmallString<64> Buffer; 1580 Buffer += ID->getFileName(); 1581 Buffer += ID->getFile()->getName(); 1582 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer); 1583 continue; 1584 } 1585 1586 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter"); 1587 } 1588 Stream.ExitBlock(); 1589 1590 // Write the offsets table for the preprocessing record. 1591 if (NumPreprocessingRecords > 0) { 1592 // Write the offsets table for identifier IDs. 1593 using namespace llvm; 1594 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1595 Abbrev->Add(BitCodeAbbrevOp(MACRO_DEFINITION_OFFSETS)); 1596 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of records 1597 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macro defs 1598 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1599 unsigned MacroDefOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1600 1601 Record.clear(); 1602 Record.push_back(MACRO_DEFINITION_OFFSETS); 1603 Record.push_back(NumPreprocessingRecords); 1604 Record.push_back(MacroDefinitionOffsets.size()); 1605 Stream.EmitRecordWithBlob(MacroDefOffsetAbbrev, Record, 1606 (const char *)data(MacroDefinitionOffsets), 1607 MacroDefinitionOffsets.size() * sizeof(uint32_t)); 1608 } 1609} 1610 1611void ASTWriter::WritePragmaDiagnosticMappings(const Diagnostic &Diag) { 1612 RecordData Record; 1613 for (Diagnostic::DiagStatePointsTy::const_iterator 1614 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end(); 1615 I != E; ++I) { 1616 const Diagnostic::DiagStatePoint &point = *I; 1617 if (point.Loc.isInvalid()) 1618 continue; 1619 1620 Record.push_back(point.Loc.getRawEncoding()); 1621 for (Diagnostic::DiagState::iterator 1622 I = point.State->begin(), E = point.State->end(); I != E; ++I) { 1623 unsigned diag = I->first, map = I->second; 1624 if (map & 0x10) { // mapping from a diagnostic pragma. 1625 Record.push_back(diag); 1626 Record.push_back(map & 0x7); 1627 } 1628 } 1629 Record.push_back(-1); // mark the end of the diag/map pairs for this 1630 // location. 1631 } 1632 1633 if (!Record.empty()) 1634 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record); 1635} 1636 1637//===----------------------------------------------------------------------===// 1638// Type Serialization 1639//===----------------------------------------------------------------------===// 1640 1641/// \brief Write the representation of a type to the AST stream. 1642void ASTWriter::WriteType(QualType T) { 1643 TypeIdx &Idx = TypeIdxs[T]; 1644 if (Idx.getIndex() == 0) // we haven't seen this type before. 1645 Idx = TypeIdx(NextTypeID++); 1646 1647 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST"); 1648 1649 // Record the offset for this type. 1650 unsigned Index = Idx.getIndex() - FirstTypeID; 1651 if (TypeOffsets.size() == Index) 1652 TypeOffsets.push_back(Stream.GetCurrentBitNo()); 1653 else if (TypeOffsets.size() < Index) { 1654 TypeOffsets.resize(Index + 1); 1655 TypeOffsets[Index] = Stream.GetCurrentBitNo(); 1656 } 1657 1658 RecordData Record; 1659 1660 // Emit the type's representation. 1661 ASTTypeWriter W(*this, Record); 1662 1663 if (T.hasLocalNonFastQualifiers()) { 1664 Qualifiers Qs = T.getLocalQualifiers(); 1665 AddTypeRef(T.getLocalUnqualifiedType(), Record); 1666 Record.push_back(Qs.getAsOpaqueValue()); 1667 W.Code = TYPE_EXT_QUAL; 1668 } else { 1669 switch (T->getTypeClass()) { 1670 // For all of the concrete, non-dependent types, call the 1671 // appropriate visitor function. 1672#define TYPE(Class, Base) \ 1673 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break; 1674#define ABSTRACT_TYPE(Class, Base) 1675#include "clang/AST/TypeNodes.def" 1676 } 1677 } 1678 1679 // Emit the serialized record. 1680 Stream.EmitRecord(W.Code, Record); 1681 1682 // Flush any expressions that were written as part of this type. 1683 FlushStmts(); 1684} 1685 1686//===----------------------------------------------------------------------===// 1687// Declaration Serialization 1688//===----------------------------------------------------------------------===// 1689 1690/// \brief Write the block containing all of the declaration IDs 1691/// lexically declared within the given DeclContext. 1692/// 1693/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the 1694/// bistream, or 0 if no block was written. 1695uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context, 1696 DeclContext *DC) { 1697 if (DC->decls_empty()) 1698 return 0; 1699 1700 uint64_t Offset = Stream.GetCurrentBitNo(); 1701 RecordData Record; 1702 Record.push_back(DECL_CONTEXT_LEXICAL); 1703 llvm::SmallVector<KindDeclIDPair, 64> Decls; 1704 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end(); 1705 D != DEnd; ++D) 1706 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D))); 1707 1708 ++NumLexicalDeclContexts; 1709 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, 1710 reinterpret_cast<char*>(Decls.data()), 1711 Decls.size() * sizeof(KindDeclIDPair)); 1712 return Offset; 1713} 1714 1715void ASTWriter::WriteTypeDeclOffsets() { 1716 using namespace llvm; 1717 RecordData Record; 1718 1719 // Write the type offsets array 1720 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1721 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET)); 1722 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types 1723 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block 1724 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1725 Record.clear(); 1726 Record.push_back(TYPE_OFFSET); 1727 Record.push_back(TypeOffsets.size()); 1728 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, 1729 (const char *)data(TypeOffsets), 1730 TypeOffsets.size() * sizeof(TypeOffsets[0])); 1731 1732 // Write the declaration offsets array 1733 Abbrev = new BitCodeAbbrev(); 1734 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET)); 1735 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations 1736 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block 1737 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1738 Record.clear(); 1739 Record.push_back(DECL_OFFSET); 1740 Record.push_back(DeclOffsets.size()); 1741 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, 1742 (const char *)data(DeclOffsets), 1743 DeclOffsets.size() * sizeof(DeclOffsets[0])); 1744} 1745 1746//===----------------------------------------------------------------------===// 1747// Global Method Pool and Selector Serialization 1748//===----------------------------------------------------------------------===// 1749 1750namespace { 1751// Trait used for the on-disk hash table used in the method pool. 1752class ASTMethodPoolTrait { 1753 ASTWriter &Writer; 1754 1755public: 1756 typedef Selector key_type; 1757 typedef key_type key_type_ref; 1758 1759 struct data_type { 1760 SelectorID ID; 1761 ObjCMethodList Instance, Factory; 1762 }; 1763 typedef const data_type& data_type_ref; 1764 1765 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { } 1766 1767 static unsigned ComputeHash(Selector Sel) { 1768 return serialization::ComputeHash(Sel); 1769 } 1770 1771 std::pair<unsigned,unsigned> 1772 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel, 1773 data_type_ref Methods) { 1774 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4); 1775 clang::io::Emit16(Out, KeyLen); 1776 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts 1777 for (const ObjCMethodList *Method = &Methods.Instance; Method; 1778 Method = Method->Next) 1779 if (Method->Method) 1780 DataLen += 4; 1781 for (const ObjCMethodList *Method = &Methods.Factory; Method; 1782 Method = Method->Next) 1783 if (Method->Method) 1784 DataLen += 4; 1785 clang::io::Emit16(Out, DataLen); 1786 return std::make_pair(KeyLen, DataLen); 1787 } 1788 1789 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) { 1790 uint64_t Start = Out.tell(); 1791 assert((Start >> 32) == 0 && "Selector key offset too large"); 1792 Writer.SetSelectorOffset(Sel, Start); 1793 unsigned N = Sel.getNumArgs(); 1794 clang::io::Emit16(Out, N); 1795 if (N == 0) 1796 N = 1; 1797 for (unsigned I = 0; I != N; ++I) 1798 clang::io::Emit32(Out, 1799 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I))); 1800 } 1801 1802 void EmitData(llvm::raw_ostream& Out, key_type_ref, 1803 data_type_ref Methods, unsigned DataLen) { 1804 uint64_t Start = Out.tell(); (void)Start; 1805 clang::io::Emit32(Out, Methods.ID); 1806 unsigned NumInstanceMethods = 0; 1807 for (const ObjCMethodList *Method = &Methods.Instance; Method; 1808 Method = Method->Next) 1809 if (Method->Method) 1810 ++NumInstanceMethods; 1811 1812 unsigned NumFactoryMethods = 0; 1813 for (const ObjCMethodList *Method = &Methods.Factory; Method; 1814 Method = Method->Next) 1815 if (Method->Method) 1816 ++NumFactoryMethods; 1817 1818 clang::io::Emit16(Out, NumInstanceMethods); 1819 clang::io::Emit16(Out, NumFactoryMethods); 1820 for (const ObjCMethodList *Method = &Methods.Instance; Method; 1821 Method = Method->Next) 1822 if (Method->Method) 1823 clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); 1824 for (const ObjCMethodList *Method = &Methods.Factory; Method; 1825 Method = Method->Next) 1826 if (Method->Method) 1827 clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); 1828 1829 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 1830 } 1831}; 1832} // end anonymous namespace 1833 1834/// \brief Write ObjC data: selectors and the method pool. 1835/// 1836/// The method pool contains both instance and factory methods, stored 1837/// in an on-disk hash table indexed by the selector. The hash table also 1838/// contains an empty entry for every other selector known to Sema. 1839void ASTWriter::WriteSelectors(Sema &SemaRef) { 1840 using namespace llvm; 1841 1842 // Do we have to do anything at all? 1843 if (SemaRef.MethodPool.empty() && SelectorIDs.empty()) 1844 return; 1845 unsigned NumTableEntries = 0; 1846 // Create and write out the blob that contains selectors and the method pool. 1847 { 1848 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator; 1849 ASTMethodPoolTrait Trait(*this); 1850 1851 // Create the on-disk hash table representation. We walk through every 1852 // selector we've seen and look it up in the method pool. 1853 SelectorOffsets.resize(NextSelectorID - FirstSelectorID); 1854 for (llvm::DenseMap<Selector, SelectorID>::iterator 1855 I = SelectorIDs.begin(), E = SelectorIDs.end(); 1856 I != E; ++I) { 1857 Selector S = I->first; 1858 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S); 1859 ASTMethodPoolTrait::data_type Data = { 1860 I->second, 1861 ObjCMethodList(), 1862 ObjCMethodList() 1863 }; 1864 if (F != SemaRef.MethodPool.end()) { 1865 Data.Instance = F->second.first; 1866 Data.Factory = F->second.second; 1867 } 1868 // Only write this selector if it's not in an existing AST or something 1869 // changed. 1870 if (Chain && I->second < FirstSelectorID) { 1871 // Selector already exists. Did it change? 1872 bool changed = false; 1873 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method; 1874 M = M->Next) { 1875 if (M->Method->getPCHLevel() == 0) 1876 changed = true; 1877 } 1878 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method; 1879 M = M->Next) { 1880 if (M->Method->getPCHLevel() == 0) 1881 changed = true; 1882 } 1883 if (!changed) 1884 continue; 1885 } else if (Data.Instance.Method || Data.Factory.Method) { 1886 // A new method pool entry. 1887 ++NumTableEntries; 1888 } 1889 Generator.insert(S, Data, Trait); 1890 } 1891 1892 // Create the on-disk hash table in a buffer. 1893 llvm::SmallString<4096> MethodPool; 1894 uint32_t BucketOffset; 1895 { 1896 ASTMethodPoolTrait Trait(*this); 1897 llvm::raw_svector_ostream Out(MethodPool); 1898 // Make sure that no bucket is at offset 0 1899 clang::io::Emit32(Out, 0); 1900 BucketOffset = Generator.Emit(Out, Trait); 1901 } 1902 1903 // Create a blob abbreviation 1904 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1905 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL)); 1906 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1907 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1908 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1909 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev); 1910 1911 // Write the method pool 1912 RecordData Record; 1913 Record.push_back(METHOD_POOL); 1914 Record.push_back(BucketOffset); 1915 Record.push_back(NumTableEntries); 1916 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str()); 1917 1918 // Create a blob abbreviation for the selector table offsets. 1919 Abbrev = new BitCodeAbbrev(); 1920 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS)); 1921 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 1922 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1923 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1924 1925 // Write the selector offsets table. 1926 Record.clear(); 1927 Record.push_back(SELECTOR_OFFSETS); 1928 Record.push_back(SelectorOffsets.size()); 1929 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record, 1930 (const char *)data(SelectorOffsets), 1931 SelectorOffsets.size() * 4); 1932 } 1933} 1934 1935/// \brief Write the selectors referenced in @selector expression into AST file. 1936void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) { 1937 using namespace llvm; 1938 if (SemaRef.ReferencedSelectors.empty()) 1939 return; 1940 1941 RecordData Record; 1942 1943 // Note: this writes out all references even for a dependent AST. But it is 1944 // very tricky to fix, and given that @selector shouldn't really appear in 1945 // headers, probably not worth it. It's not a correctness issue. 1946 for (DenseMap<Selector, SourceLocation>::iterator S = 1947 SemaRef.ReferencedSelectors.begin(), 1948 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) { 1949 Selector Sel = (*S).first; 1950 SourceLocation Loc = (*S).second; 1951 AddSelectorRef(Sel, Record); 1952 AddSourceLocation(Loc, Record); 1953 } 1954 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record); 1955} 1956 1957//===----------------------------------------------------------------------===// 1958// Identifier Table Serialization 1959//===----------------------------------------------------------------------===// 1960 1961namespace { 1962class ASTIdentifierTableTrait { 1963 ASTWriter &Writer; 1964 Preprocessor &PP; 1965 1966 /// \brief Determines whether this is an "interesting" identifier 1967 /// that needs a full IdentifierInfo structure written into the hash 1968 /// table. 1969 static bool isInterestingIdentifier(const IdentifierInfo *II) { 1970 return II->isPoisoned() || 1971 II->isExtensionToken() || 1972 II->hasMacroDefinition() || 1973 II->getObjCOrBuiltinID() || 1974 II->getFETokenInfo<void>(); 1975 } 1976 1977public: 1978 typedef const IdentifierInfo* key_type; 1979 typedef key_type key_type_ref; 1980 1981 typedef IdentID data_type; 1982 typedef data_type data_type_ref; 1983 1984 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP) 1985 : Writer(Writer), PP(PP) { } 1986 1987 static unsigned ComputeHash(const IdentifierInfo* II) { 1988 return llvm::HashString(II->getName()); 1989 } 1990 1991 std::pair<unsigned,unsigned> 1992 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II, 1993 IdentID ID) { 1994 unsigned KeyLen = II->getLength() + 1; 1995 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1 1996 if (isInterestingIdentifier(II)) { 1997 DataLen += 2; // 2 bytes for builtin ID, flags 1998 if (II->hasMacroDefinition() && 1999 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro()) 2000 DataLen += 4; 2001 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II), 2002 DEnd = IdentifierResolver::end(); 2003 D != DEnd; ++D) 2004 DataLen += sizeof(DeclID); 2005 } 2006 clang::io::Emit16(Out, DataLen); 2007 // We emit the key length after the data length so that every 2008 // string is preceded by a 16-bit length. This matches the PTH 2009 // format for storing identifiers. 2010 clang::io::Emit16(Out, KeyLen); 2011 return std::make_pair(KeyLen, DataLen); 2012 } 2013 2014 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II, 2015 unsigned KeyLen) { 2016 // Record the location of the key data. This is used when generating 2017 // the mapping from persistent IDs to strings. 2018 Writer.SetIdentifierOffset(II, Out.tell()); 2019 Out.write(II->getNameStart(), KeyLen); 2020 } 2021 2022 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II, 2023 IdentID ID, unsigned) { 2024 if (!isInterestingIdentifier(II)) { 2025 clang::io::Emit32(Out, ID << 1); 2026 return; 2027 } 2028 2029 clang::io::Emit32(Out, (ID << 1) | 0x01); 2030 uint32_t Bits = 0; 2031 bool hasMacroDefinition = 2032 II->hasMacroDefinition() && 2033 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro(); 2034 Bits = (uint32_t)II->getObjCOrBuiltinID(); 2035 Bits = (Bits << 1) | unsigned(hasMacroDefinition); 2036 Bits = (Bits << 1) | unsigned(II->isExtensionToken()); 2037 Bits = (Bits << 1) | unsigned(II->isPoisoned()); 2038 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier()); 2039 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword()); 2040 clang::io::Emit16(Out, Bits); 2041 2042 if (hasMacroDefinition) 2043 clang::io::Emit32(Out, Writer.getMacroOffset(II)); 2044 2045 // Emit the declaration IDs in reverse order, because the 2046 // IdentifierResolver provides the declarations as they would be 2047 // visible (e.g., the function "stat" would come before the struct 2048 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain() 2049 // adds declarations to the end of the list (so we need to see the 2050 // struct "status" before the function "status"). 2051 // Only emit declarations that aren't from a chained PCH, though. 2052 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II), 2053 IdentifierResolver::end()); 2054 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(), 2055 DEnd = Decls.rend(); 2056 D != DEnd; ++D) 2057 clang::io::Emit32(Out, Writer.getDeclID(*D)); 2058 } 2059}; 2060} // end anonymous namespace 2061 2062/// \brief Write the identifier table into the AST file. 2063/// 2064/// The identifier table consists of a blob containing string data 2065/// (the actual identifiers themselves) and a separate "offsets" index 2066/// that maps identifier IDs to locations within the blob. 2067void ASTWriter::WriteIdentifierTable(Preprocessor &PP) { 2068 using namespace llvm; 2069 2070 // Create and write out the blob that contains the identifier 2071 // strings. 2072 { 2073 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator; 2074 ASTIdentifierTableTrait Trait(*this, PP); 2075 2076 // Look for any identifiers that were named while processing the 2077 // headers, but are otherwise not needed. We add these to the hash 2078 // table to enable checking of the predefines buffer in the case 2079 // where the user adds new macro definitions when building the AST 2080 // file. 2081 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 2082 IDEnd = PP.getIdentifierTable().end(); 2083 ID != IDEnd; ++ID) 2084 getIdentifierRef(ID->second); 2085 2086 // Create the on-disk hash table representation. We only store offsets 2087 // for identifiers that appear here for the first time. 2088 IdentifierOffsets.resize(NextIdentID - FirstIdentID); 2089 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator 2090 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end(); 2091 ID != IDEnd; ++ID) { 2092 assert(ID->first && "NULL identifier in identifier table"); 2093 if (!Chain || !ID->first->isFromAST()) 2094 Generator.insert(ID->first, ID->second, Trait); 2095 } 2096 2097 // Create the on-disk hash table in a buffer. 2098 llvm::SmallString<4096> IdentifierTable; 2099 uint32_t BucketOffset; 2100 { 2101 ASTIdentifierTableTrait Trait(*this, PP); 2102 llvm::raw_svector_ostream Out(IdentifierTable); 2103 // Make sure that no bucket is at offset 0 2104 clang::io::Emit32(Out, 0); 2105 BucketOffset = Generator.Emit(Out, Trait); 2106 } 2107 2108 // Create a blob abbreviation 2109 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2110 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE)); 2111 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2112 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2113 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev); 2114 2115 // Write the identifier table 2116 RecordData Record; 2117 Record.push_back(IDENTIFIER_TABLE); 2118 Record.push_back(BucketOffset); 2119 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str()); 2120 } 2121 2122 // Write the offsets table for identifier IDs. 2123 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2124 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET)); 2125 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers 2126 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2127 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2128 2129 RecordData Record; 2130 Record.push_back(IDENTIFIER_OFFSET); 2131 Record.push_back(IdentifierOffsets.size()); 2132 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record, 2133 (const char *)data(IdentifierOffsets), 2134 IdentifierOffsets.size() * sizeof(uint32_t)); 2135} 2136 2137//===----------------------------------------------------------------------===// 2138// DeclContext's Name Lookup Table Serialization 2139//===----------------------------------------------------------------------===// 2140 2141namespace { 2142// Trait used for the on-disk hash table used in the method pool. 2143class ASTDeclContextNameLookupTrait { 2144 ASTWriter &Writer; 2145 2146public: 2147 typedef DeclarationName key_type; 2148 typedef key_type key_type_ref; 2149 2150 typedef DeclContext::lookup_result data_type; 2151 typedef const data_type& data_type_ref; 2152 2153 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { } 2154 2155 unsigned ComputeHash(DeclarationName Name) { 2156 llvm::FoldingSetNodeID ID; 2157 ID.AddInteger(Name.getNameKind()); 2158 2159 switch (Name.getNameKind()) { 2160 case DeclarationName::Identifier: 2161 ID.AddString(Name.getAsIdentifierInfo()->getName()); 2162 break; 2163 case DeclarationName::ObjCZeroArgSelector: 2164 case DeclarationName::ObjCOneArgSelector: 2165 case DeclarationName::ObjCMultiArgSelector: 2166 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector())); 2167 break; 2168 case DeclarationName::CXXConstructorName: 2169 case DeclarationName::CXXDestructorName: 2170 case DeclarationName::CXXConversionFunctionName: 2171 ID.AddInteger(Writer.GetOrCreateTypeID(Name.getCXXNameType())); 2172 break; 2173 case DeclarationName::CXXOperatorName: 2174 ID.AddInteger(Name.getCXXOverloadedOperator()); 2175 break; 2176 case DeclarationName::CXXLiteralOperatorName: 2177 ID.AddString(Name.getCXXLiteralIdentifier()->getName()); 2178 case DeclarationName::CXXUsingDirective: 2179 break; 2180 } 2181 2182 return ID.ComputeHash(); 2183 } 2184 2185 std::pair<unsigned,unsigned> 2186 EmitKeyDataLength(llvm::raw_ostream& Out, DeclarationName Name, 2187 data_type_ref Lookup) { 2188 unsigned KeyLen = 1; 2189 switch (Name.getNameKind()) { 2190 case DeclarationName::Identifier: 2191 case DeclarationName::ObjCZeroArgSelector: 2192 case DeclarationName::ObjCOneArgSelector: 2193 case DeclarationName::ObjCMultiArgSelector: 2194 case DeclarationName::CXXConstructorName: 2195 case DeclarationName::CXXDestructorName: 2196 case DeclarationName::CXXConversionFunctionName: 2197 case DeclarationName::CXXLiteralOperatorName: 2198 KeyLen += 4; 2199 break; 2200 case DeclarationName::CXXOperatorName: 2201 KeyLen += 1; 2202 break; 2203 case DeclarationName::CXXUsingDirective: 2204 break; 2205 } 2206 clang::io::Emit16(Out, KeyLen); 2207 2208 // 2 bytes for num of decls and 4 for each DeclID. 2209 unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first); 2210 clang::io::Emit16(Out, DataLen); 2211 2212 return std::make_pair(KeyLen, DataLen); 2213 } 2214 2215 void EmitKey(llvm::raw_ostream& Out, DeclarationName Name, unsigned) { 2216 using namespace clang::io; 2217 2218 assert(Name.getNameKind() < 0x100 && "Invalid name kind ?"); 2219 Emit8(Out, Name.getNameKind()); 2220 switch (Name.getNameKind()) { 2221 case DeclarationName::Identifier: 2222 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo())); 2223 break; 2224 case DeclarationName::ObjCZeroArgSelector: 2225 case DeclarationName::ObjCOneArgSelector: 2226 case DeclarationName::ObjCMultiArgSelector: 2227 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector())); 2228 break; 2229 case DeclarationName::CXXConstructorName: 2230 case DeclarationName::CXXDestructorName: 2231 case DeclarationName::CXXConversionFunctionName: 2232 Emit32(Out, Writer.getTypeID(Name.getCXXNameType())); 2233 break; 2234 case DeclarationName::CXXOperatorName: 2235 assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?"); 2236 Emit8(Out, Name.getCXXOverloadedOperator()); 2237 break; 2238 case DeclarationName::CXXLiteralOperatorName: 2239 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier())); 2240 break; 2241 case DeclarationName::CXXUsingDirective: 2242 break; 2243 } 2244 } 2245 2246 void EmitData(llvm::raw_ostream& Out, key_type_ref, 2247 data_type Lookup, unsigned DataLen) { 2248 uint64_t Start = Out.tell(); (void)Start; 2249 clang::io::Emit16(Out, Lookup.second - Lookup.first); 2250 for (; Lookup.first != Lookup.second; ++Lookup.first) 2251 clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first)); 2252 2253 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 2254 } 2255}; 2256} // end anonymous namespace 2257 2258/// \brief Write the block containing all of the declaration IDs 2259/// visible from the given DeclContext. 2260/// 2261/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the 2262/// bitstream, or 0 if no block was written. 2263uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context, 2264 DeclContext *DC) { 2265 if (DC->getPrimaryContext() != DC) 2266 return 0; 2267 2268 // Since there is no name lookup into functions or methods, don't bother to 2269 // build a visible-declarations table for these entities. 2270 if (DC->isFunctionOrMethod()) 2271 return 0; 2272 2273 // If not in C++, we perform name lookup for the translation unit via the 2274 // IdentifierInfo chains, don't bother to build a visible-declarations table. 2275 // FIXME: In C++ we need the visible declarations in order to "see" the 2276 // friend declarations, is there a way to do this without writing the table ? 2277 if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus) 2278 return 0; 2279 2280 // Force the DeclContext to build a its name-lookup table. 2281 if (DC->hasExternalVisibleStorage()) 2282 DC->MaterializeVisibleDeclsFromExternalStorage(); 2283 else 2284 DC->lookup(DeclarationName()); 2285 2286 // Serialize the contents of the mapping used for lookup. Note that, 2287 // although we have two very different code paths, the serialized 2288 // representation is the same for both cases: a declaration name, 2289 // followed by a size, followed by references to the visible 2290 // declarations that have that name. 2291 uint64_t Offset = Stream.GetCurrentBitNo(); 2292 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr()); 2293 if (!Map || Map->empty()) 2294 return 0; 2295 2296 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator; 2297 ASTDeclContextNameLookupTrait Trait(*this); 2298 2299 // Create the on-disk hash table representation. 2300 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); 2301 D != DEnd; ++D) { 2302 DeclarationName Name = D->first; 2303 DeclContext::lookup_result Result = D->second.getLookupResult(); 2304 Generator.insert(Name, Result, Trait); 2305 } 2306 2307 // Create the on-disk hash table in a buffer. 2308 llvm::SmallString<4096> LookupTable; 2309 uint32_t BucketOffset; 2310 { 2311 llvm::raw_svector_ostream Out(LookupTable); 2312 // Make sure that no bucket is at offset 0 2313 clang::io::Emit32(Out, 0); 2314 BucketOffset = Generator.Emit(Out, Trait); 2315 } 2316 2317 // Write the lookup table 2318 RecordData Record; 2319 Record.push_back(DECL_CONTEXT_VISIBLE); 2320 Record.push_back(BucketOffset); 2321 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record, 2322 LookupTable.str()); 2323 2324 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record); 2325 ++NumVisibleDeclContexts; 2326 return Offset; 2327} 2328 2329/// \brief Write an UPDATE_VISIBLE block for the given context. 2330/// 2331/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing 2332/// DeclContext in a dependent AST file. As such, they only exist for the TU 2333/// (in C++) and for namespaces. 2334void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) { 2335 // Make the context build its lookup table, but don't make it load external 2336 // decls. 2337 DC->lookup(DeclarationName()); 2338 2339 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr()); 2340 if (!Map || Map->empty()) 2341 return; 2342 2343 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator; 2344 ASTDeclContextNameLookupTrait Trait(*this); 2345 2346 // Create the hash table. 2347 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); 2348 D != DEnd; ++D) { 2349 DeclarationName Name = D->first; 2350 DeclContext::lookup_result Result = D->second.getLookupResult(); 2351 // For any name that appears in this table, the results are complete, i.e. 2352 // they overwrite results from previous PCHs. Merging is always a mess. 2353 Generator.insert(Name, Result, Trait); 2354 } 2355 2356 // Create the on-disk hash table in a buffer. 2357 llvm::SmallString<4096> LookupTable; 2358 uint32_t BucketOffset; 2359 { 2360 llvm::raw_svector_ostream Out(LookupTable); 2361 // Make sure that no bucket is at offset 0 2362 clang::io::Emit32(Out, 0); 2363 BucketOffset = Generator.Emit(Out, Trait); 2364 } 2365 2366 // Write the lookup table 2367 RecordData Record; 2368 Record.push_back(UPDATE_VISIBLE); 2369 Record.push_back(getDeclID(cast<Decl>(DC))); 2370 Record.push_back(BucketOffset); 2371 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str()); 2372} 2373 2374//===----------------------------------------------------------------------===// 2375// General Serialization Routines 2376//===----------------------------------------------------------------------===// 2377 2378/// \brief Write a record containing the given attributes. 2379void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) { 2380 Record.push_back(Attrs.size()); 2381 for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){ 2382 const Attr * A = *i; 2383 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs 2384 AddSourceLocation(A->getLocation(), Record); 2385 2386#include "clang/Serialization/AttrPCHWrite.inc" 2387 2388 } 2389} 2390 2391void ASTWriter::AddString(llvm::StringRef Str, RecordDataImpl &Record) { 2392 Record.push_back(Str.size()); 2393 Record.insert(Record.end(), Str.begin(), Str.end()); 2394} 2395 2396/// \brief Note that the identifier II occurs at the given offset 2397/// within the identifier table. 2398void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) { 2399 IdentID ID = IdentifierIDs[II]; 2400 // Only store offsets new to this AST file. Other identifier names are looked 2401 // up earlier in the chain and thus don't need an offset. 2402 if (ID >= FirstIdentID) 2403 IdentifierOffsets[ID - FirstIdentID] = Offset; 2404} 2405 2406/// \brief Note that the selector Sel occurs at the given offset 2407/// within the method pool/selector table. 2408void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { 2409 unsigned ID = SelectorIDs[Sel]; 2410 assert(ID && "Unknown selector"); 2411 // Don't record offsets for selectors that are also available in a different 2412 // file. 2413 if (ID < FirstSelectorID) 2414 return; 2415 SelectorOffsets[ID - FirstSelectorID] = Offset; 2416} 2417 2418ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream) 2419 : Stream(Stream), Chain(0), SerializationListener(0), 2420 FirstDeclID(1), NextDeclID(FirstDeclID), 2421 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID), 2422 FirstIdentID(1), NextIdentID(FirstIdentID), FirstSelectorID(1), 2423 NextSelectorID(FirstSelectorID), FirstMacroID(1), NextMacroID(FirstMacroID), 2424 CollectedStmts(&StmtsToEmit), 2425 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0), 2426 NumVisibleDeclContexts(0), FirstCXXBaseSpecifiersID(1), 2427 NextCXXBaseSpecifiersID(1) 2428{ 2429} 2430 2431void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls, 2432 const char *isysroot) { 2433 // Emit the file header. 2434 Stream.Emit((unsigned)'C', 8); 2435 Stream.Emit((unsigned)'P', 8); 2436 Stream.Emit((unsigned)'C', 8); 2437 Stream.Emit((unsigned)'H', 8); 2438 2439 WriteBlockInfoBlock(); 2440 2441 if (Chain) 2442 WriteASTChain(SemaRef, StatCalls, isysroot); 2443 else 2444 WriteASTCore(SemaRef, StatCalls, isysroot); 2445} 2446 2447void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls, 2448 const char *isysroot) { 2449 using namespace llvm; 2450 2451 ASTContext &Context = SemaRef.Context; 2452 Preprocessor &PP = SemaRef.PP; 2453 2454 // The translation unit is the first declaration we'll emit. 2455 DeclIDs[Context.getTranslationUnitDecl()] = 1; 2456 ++NextDeclID; 2457 DeclTypesToEmit.push(Context.getTranslationUnitDecl()); 2458 2459 // Make sure that we emit IdentifierInfos (and any attached 2460 // declarations) for builtins. 2461 { 2462 IdentifierTable &Table = PP.getIdentifierTable(); 2463 llvm::SmallVector<const char *, 32> BuiltinNames; 2464 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames, 2465 Context.getLangOptions().NoBuiltin); 2466 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I) 2467 getIdentifierRef(&Table.get(BuiltinNames[I])); 2468 } 2469 2470 // Build a record containing all of the tentative definitions in this file, in 2471 // TentativeDefinitions order. Generally, this record will be empty for 2472 // headers. 2473 RecordData TentativeDefinitions; 2474 for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) { 2475 AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions); 2476 } 2477 2478 // Build a record containing all of the file scoped decls in this file. 2479 RecordData UnusedFileScopedDecls; 2480 for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i) 2481 AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls); 2482 2483 RecordData WeakUndeclaredIdentifiers; 2484 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) { 2485 WeakUndeclaredIdentifiers.push_back( 2486 SemaRef.WeakUndeclaredIdentifiers.size()); 2487 for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator 2488 I = SemaRef.WeakUndeclaredIdentifiers.begin(), 2489 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) { 2490 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers); 2491 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers); 2492 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers); 2493 WeakUndeclaredIdentifiers.push_back(I->second.getUsed()); 2494 } 2495 } 2496 2497 // Build a record containing all of the locally-scoped external 2498 // declarations in this header file. Generally, this record will be 2499 // empty. 2500 RecordData LocallyScopedExternalDecls; 2501 // FIXME: This is filling in the AST file in densemap order which is 2502 // nondeterminstic! 2503 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 2504 TD = SemaRef.LocallyScopedExternalDecls.begin(), 2505 TDEnd = SemaRef.LocallyScopedExternalDecls.end(); 2506 TD != TDEnd; ++TD) 2507 AddDeclRef(TD->second, LocallyScopedExternalDecls); 2508 2509 // Build a record containing all of the ext_vector declarations. 2510 RecordData ExtVectorDecls; 2511 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I) 2512 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls); 2513 2514 // Build a record containing all of the VTable uses information. 2515 RecordData VTableUses; 2516 if (!SemaRef.VTableUses.empty()) { 2517 VTableUses.push_back(SemaRef.VTableUses.size()); 2518 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 2519 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 2520 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 2521 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 2522 } 2523 } 2524 2525 // Build a record containing all of dynamic classes declarations. 2526 RecordData DynamicClasses; 2527 for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I) 2528 AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses); 2529 2530 // Build a record containing all of pending implicit instantiations. 2531 RecordData PendingInstantiations; 2532 for (std::deque<Sema::PendingImplicitInstantiation>::iterator 2533 I = SemaRef.PendingInstantiations.begin(), 2534 N = SemaRef.PendingInstantiations.end(); I != N; ++I) { 2535 AddDeclRef(I->first, PendingInstantiations); 2536 AddSourceLocation(I->second, PendingInstantiations); 2537 } 2538 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 2539 "There are local ones at end of translation unit!"); 2540 2541 // Build a record containing some declaration references. 2542 RecordData SemaDeclRefs; 2543 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) { 2544 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 2545 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 2546 } 2547 2548 RecordData CUDASpecialDeclRefs; 2549 if (Context.getcudaConfigureCallDecl()) { 2550 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs); 2551 } 2552 2553 // Write the remaining AST contents. 2554 RecordData Record; 2555 Stream.EnterSubblock(AST_BLOCK_ID, 5); 2556 WriteMetadata(Context, isysroot); 2557 WriteLanguageOptions(Context.getLangOptions()); 2558 if (StatCalls && !isysroot) 2559 WriteStatCache(*StatCalls); 2560 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot); 2561 // Write the record of special types. 2562 Record.clear(); 2563 2564 AddTypeRef(Context.getBuiltinVaListType(), Record); 2565 AddTypeRef(Context.getObjCIdType(), Record); 2566 AddTypeRef(Context.getObjCSelType(), Record); 2567 AddTypeRef(Context.getObjCProtoType(), Record); 2568 AddTypeRef(Context.getObjCClassType(), Record); 2569 AddTypeRef(Context.getRawCFConstantStringType(), Record); 2570 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record); 2571 AddTypeRef(Context.getFILEType(), Record); 2572 AddTypeRef(Context.getjmp_bufType(), Record); 2573 AddTypeRef(Context.getsigjmp_bufType(), Record); 2574 AddTypeRef(Context.ObjCIdRedefinitionType, Record); 2575 AddTypeRef(Context.ObjCClassRedefinitionType, Record); 2576 AddTypeRef(Context.getRawBlockdescriptorType(), Record); 2577 AddTypeRef(Context.getRawBlockdescriptorExtendedType(), Record); 2578 AddTypeRef(Context.ObjCSelRedefinitionType, Record); 2579 AddTypeRef(Context.getRawNSConstantStringType(), Record); 2580 Record.push_back(Context.isInt128Installed()); 2581 Stream.EmitRecord(SPECIAL_TYPES, Record); 2582 2583 // Keep writing types and declarations until all types and 2584 // declarations have been written. 2585 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, 3); 2586 WriteDeclsBlockAbbrevs(); 2587 while (!DeclTypesToEmit.empty()) { 2588 DeclOrType DOT = DeclTypesToEmit.front(); 2589 DeclTypesToEmit.pop(); 2590 if (DOT.isType()) 2591 WriteType(DOT.getType()); 2592 else 2593 WriteDecl(Context, DOT.getDecl()); 2594 } 2595 Stream.ExitBlock(); 2596 2597 WritePreprocessor(PP); 2598 WriteSelectors(SemaRef); 2599 WriteReferencedSelectorsPool(SemaRef); 2600 WriteIdentifierTable(PP); 2601 2602 WriteTypeDeclOffsets(); 2603 WritePragmaDiagnosticMappings(Context.getDiagnostics()); 2604 2605 // Write the C++ base-specifier set offsets. 2606 if (!CXXBaseSpecifiersOffsets.empty()) { 2607 // Create a blob abbreviation for the C++ base specifiers offsets. 2608 using namespace llvm; 2609 2610 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2611 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS)); 2612 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 2613 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2614 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2615 2616 // Write the selector offsets table. 2617 Record.clear(); 2618 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS); 2619 Record.push_back(CXXBaseSpecifiersOffsets.size()); 2620 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record, 2621 (const char *)CXXBaseSpecifiersOffsets.data(), 2622 CXXBaseSpecifiersOffsets.size() * sizeof(uint32_t)); 2623 } 2624 2625 // Write the record containing external, unnamed definitions. 2626 if (!ExternalDefinitions.empty()) 2627 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions); 2628 2629 // Write the record containing tentative definitions. 2630 if (!TentativeDefinitions.empty()) 2631 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 2632 2633 // Write the record containing unused file scoped decls. 2634 if (!UnusedFileScopedDecls.empty()) 2635 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 2636 2637 // Write the record containing weak undeclared identifiers. 2638 if (!WeakUndeclaredIdentifiers.empty()) 2639 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 2640 WeakUndeclaredIdentifiers); 2641 2642 // Write the record containing locally-scoped external definitions. 2643 if (!LocallyScopedExternalDecls.empty()) 2644 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS, 2645 LocallyScopedExternalDecls); 2646 2647 // Write the record containing ext_vector type names. 2648 if (!ExtVectorDecls.empty()) 2649 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 2650 2651 // Write the record containing VTable uses information. 2652 if (!VTableUses.empty()) 2653 Stream.EmitRecord(VTABLE_USES, VTableUses); 2654 2655 // Write the record containing dynamic classes declarations. 2656 if (!DynamicClasses.empty()) 2657 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses); 2658 2659 // Write the record containing pending implicit instantiations. 2660 if (!PendingInstantiations.empty()) 2661 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 2662 2663 // Write the record containing declaration references of Sema. 2664 if (!SemaDeclRefs.empty()) 2665 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 2666 2667 // Write the record containing CUDA-specific declaration references. 2668 if (!CUDASpecialDeclRefs.empty()) 2669 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs); 2670 2671 // Some simple statistics 2672 Record.clear(); 2673 Record.push_back(NumStatements); 2674 Record.push_back(NumMacros); 2675 Record.push_back(NumLexicalDeclContexts); 2676 Record.push_back(NumVisibleDeclContexts); 2677 Stream.EmitRecord(STATISTICS, Record); 2678 Stream.ExitBlock(); 2679} 2680 2681void ASTWriter::WriteASTChain(Sema &SemaRef, MemorizeStatCalls *StatCalls, 2682 const char *isysroot) { 2683 using namespace llvm; 2684 2685 ASTContext &Context = SemaRef.Context; 2686 Preprocessor &PP = SemaRef.PP; 2687 2688 RecordData Record; 2689 Stream.EnterSubblock(AST_BLOCK_ID, 5); 2690 WriteMetadata(Context, isysroot); 2691 if (StatCalls && !isysroot) 2692 WriteStatCache(*StatCalls); 2693 // FIXME: Source manager block should only write new stuff, which could be 2694 // done by tracking the largest ID in the chain 2695 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot); 2696 2697 // The special types are in the chained PCH. 2698 2699 // We don't start with the translation unit, but with its decls that 2700 // don't come from the chained PCH. 2701 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 2702 llvm::SmallVector<KindDeclIDPair, 64> NewGlobalDecls; 2703 for (DeclContext::decl_iterator I = TU->noload_decls_begin(), 2704 E = TU->noload_decls_end(); 2705 I != E; ++I) { 2706 if ((*I)->getPCHLevel() == 0) 2707 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I))); 2708 else if ((*I)->isChangedSinceDeserialization()) 2709 (void)GetDeclRef(*I); // Make sure it's written, but don't record it. 2710 } 2711 // We also need to write a lexical updates block for the TU. 2712 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev(); 2713 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL)); 2714 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 2715 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv); 2716 Record.clear(); 2717 Record.push_back(TU_UPDATE_LEXICAL); 2718 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, 2719 reinterpret_cast<const char*>(NewGlobalDecls.data()), 2720 NewGlobalDecls.size() * sizeof(KindDeclIDPair)); 2721 // And a visible updates block for the DeclContexts. 2722 Abv = new llvm::BitCodeAbbrev(); 2723 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE)); 2724 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 2725 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32)); 2726 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 2727 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv); 2728 WriteDeclContextVisibleUpdate(TU); 2729 2730 // Build a record containing all of the new tentative definitions in this 2731 // file, in TentativeDefinitions order. 2732 RecordData TentativeDefinitions; 2733 for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) { 2734 if (SemaRef.TentativeDefinitions[i]->getPCHLevel() == 0) 2735 AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions); 2736 } 2737 2738 // Build a record containing all of the file scoped decls in this file. 2739 RecordData UnusedFileScopedDecls; 2740 for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i) { 2741 if (SemaRef.UnusedFileScopedDecls[i]->getPCHLevel() == 0) 2742 AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls); 2743 } 2744 2745 // We write the entire table, overwriting the tables from the chain. 2746 RecordData WeakUndeclaredIdentifiers; 2747 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) { 2748 WeakUndeclaredIdentifiers.push_back( 2749 SemaRef.WeakUndeclaredIdentifiers.size()); 2750 for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator 2751 I = SemaRef.WeakUndeclaredIdentifiers.begin(), 2752 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) { 2753 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers); 2754 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers); 2755 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers); 2756 WeakUndeclaredIdentifiers.push_back(I->second.getUsed()); 2757 } 2758 } 2759 2760 // Build a record containing all of the locally-scoped external 2761 // declarations in this header file. Generally, this record will be 2762 // empty. 2763 RecordData LocallyScopedExternalDecls; 2764 // FIXME: This is filling in the AST file in densemap order which is 2765 // nondeterminstic! 2766 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 2767 TD = SemaRef.LocallyScopedExternalDecls.begin(), 2768 TDEnd = SemaRef.LocallyScopedExternalDecls.end(); 2769 TD != TDEnd; ++TD) { 2770 if (TD->second->getPCHLevel() == 0) 2771 AddDeclRef(TD->second, LocallyScopedExternalDecls); 2772 } 2773 2774 // Build a record containing all of the ext_vector declarations. 2775 RecordData ExtVectorDecls; 2776 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I) { 2777 if (SemaRef.ExtVectorDecls[I]->getPCHLevel() == 0) 2778 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls); 2779 } 2780 2781 // Build a record containing all of the VTable uses information. 2782 // We write everything here, because it's too hard to determine whether 2783 // a use is new to this part. 2784 RecordData VTableUses; 2785 if (!SemaRef.VTableUses.empty()) { 2786 VTableUses.push_back(SemaRef.VTableUses.size()); 2787 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 2788 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 2789 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 2790 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 2791 } 2792 } 2793 2794 // Build a record containing all of dynamic classes declarations. 2795 RecordData DynamicClasses; 2796 for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I) 2797 if (SemaRef.DynamicClasses[I]->getPCHLevel() == 0) 2798 AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses); 2799 2800 // Build a record containing all of pending implicit instantiations. 2801 RecordData PendingInstantiations; 2802 for (std::deque<Sema::PendingImplicitInstantiation>::iterator 2803 I = SemaRef.PendingInstantiations.begin(), 2804 N = SemaRef.PendingInstantiations.end(); I != N; ++I) { 2805 if (I->first->getPCHLevel() == 0) { 2806 AddDeclRef(I->first, PendingInstantiations); 2807 AddSourceLocation(I->second, PendingInstantiations); 2808 } 2809 } 2810 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 2811 "There are local ones at end of translation unit!"); 2812 2813 // Build a record containing some declaration references. 2814 // It's not worth the effort to avoid duplication here. 2815 RecordData SemaDeclRefs; 2816 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) { 2817 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 2818 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 2819 } 2820 2821 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, 3); 2822 WriteDeclsBlockAbbrevs(); 2823 for (DeclsToRewriteTy::iterator 2824 I = DeclsToRewrite.begin(), E = DeclsToRewrite.end(); I != E; ++I) 2825 DeclTypesToEmit.push(const_cast<Decl*>(*I)); 2826 while (!DeclTypesToEmit.empty()) { 2827 DeclOrType DOT = DeclTypesToEmit.front(); 2828 DeclTypesToEmit.pop(); 2829 if (DOT.isType()) 2830 WriteType(DOT.getType()); 2831 else 2832 WriteDecl(Context, DOT.getDecl()); 2833 } 2834 Stream.ExitBlock(); 2835 2836 WritePreprocessor(PP); 2837 WriteSelectors(SemaRef); 2838 WriteReferencedSelectorsPool(SemaRef); 2839 WriteIdentifierTable(PP); 2840 WriteTypeDeclOffsets(); 2841 // FIXME: For chained PCH only write the new mappings (we currently 2842 // write all of them again). 2843 WritePragmaDiagnosticMappings(Context.getDiagnostics()); 2844 2845 /// Build a record containing first declarations from a chained PCH and the 2846 /// most recent declarations in this AST that they point to. 2847 RecordData FirstLatestDeclIDs; 2848 for (FirstLatestDeclMap::iterator 2849 I = FirstLatestDecls.begin(), E = FirstLatestDecls.end(); I != E; ++I) { 2850 assert(I->first->getPCHLevel() > I->second->getPCHLevel() && 2851 "Expected first & second to be in different PCHs"); 2852 AddDeclRef(I->first, FirstLatestDeclIDs); 2853 AddDeclRef(I->second, FirstLatestDeclIDs); 2854 } 2855 if (!FirstLatestDeclIDs.empty()) 2856 Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs); 2857 2858 // Write the record containing external, unnamed definitions. 2859 if (!ExternalDefinitions.empty()) 2860 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions); 2861 2862 // Write the record containing tentative definitions. 2863 if (!TentativeDefinitions.empty()) 2864 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 2865 2866 // Write the record containing unused file scoped decls. 2867 if (!UnusedFileScopedDecls.empty()) 2868 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 2869 2870 // Write the record containing weak undeclared identifiers. 2871 if (!WeakUndeclaredIdentifiers.empty()) 2872 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 2873 WeakUndeclaredIdentifiers); 2874 2875 // Write the record containing locally-scoped external definitions. 2876 if (!LocallyScopedExternalDecls.empty()) 2877 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS, 2878 LocallyScopedExternalDecls); 2879 2880 // Write the record containing ext_vector type names. 2881 if (!ExtVectorDecls.empty()) 2882 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 2883 2884 // Write the record containing VTable uses information. 2885 if (!VTableUses.empty()) 2886 Stream.EmitRecord(VTABLE_USES, VTableUses); 2887 2888 // Write the record containing dynamic classes declarations. 2889 if (!DynamicClasses.empty()) 2890 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses); 2891 2892 // Write the record containing pending implicit instantiations. 2893 if (!PendingInstantiations.empty()) 2894 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 2895 2896 // Write the record containing declaration references of Sema. 2897 if (!SemaDeclRefs.empty()) 2898 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 2899 2900 // Write the updates to DeclContexts. 2901 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator 2902 I = UpdatedDeclContexts.begin(), 2903 E = UpdatedDeclContexts.end(); 2904 I != E; ++I) 2905 WriteDeclContextVisibleUpdate(*I); 2906 2907 WriteDeclUpdatesBlocks(); 2908 2909 Record.clear(); 2910 Record.push_back(NumStatements); 2911 Record.push_back(NumMacros); 2912 Record.push_back(NumLexicalDeclContexts); 2913 Record.push_back(NumVisibleDeclContexts); 2914 WriteDeclReplacementsBlock(); 2915 Stream.EmitRecord(STATISTICS, Record); 2916 Stream.ExitBlock(); 2917} 2918 2919void ASTWriter::WriteDeclUpdatesBlocks() { 2920 if (DeclUpdates.empty()) 2921 return; 2922 2923 RecordData OffsetsRecord; 2924 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, 3); 2925 for (DeclUpdateMap::iterator 2926 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) { 2927 const Decl *D = I->first; 2928 UpdateRecord &URec = I->second; 2929 2930 if (DeclsToRewrite.count(D)) 2931 continue; // The decl will be written completely,no need to store updates. 2932 2933 uint64_t Offset = Stream.GetCurrentBitNo(); 2934 Stream.EmitRecord(DECL_UPDATES, URec); 2935 2936 OffsetsRecord.push_back(GetDeclRef(D)); 2937 OffsetsRecord.push_back(Offset); 2938 } 2939 Stream.ExitBlock(); 2940 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord); 2941} 2942 2943void ASTWriter::WriteDeclReplacementsBlock() { 2944 if (ReplacedDecls.empty()) 2945 return; 2946 2947 RecordData Record; 2948 for (llvm::SmallVector<std::pair<DeclID, uint64_t>, 16>::iterator 2949 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) { 2950 Record.push_back(I->first); 2951 Record.push_back(I->second); 2952 } 2953 Stream.EmitRecord(DECL_REPLACEMENTS, Record); 2954} 2955 2956void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) { 2957 Record.push_back(Loc.getRawEncoding()); 2958} 2959 2960void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) { 2961 AddSourceLocation(Range.getBegin(), Record); 2962 AddSourceLocation(Range.getEnd(), Record); 2963} 2964 2965void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) { 2966 Record.push_back(Value.getBitWidth()); 2967 const uint64_t *Words = Value.getRawData(); 2968 Record.append(Words, Words + Value.getNumWords()); 2969} 2970 2971void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) { 2972 Record.push_back(Value.isUnsigned()); 2973 AddAPInt(Value, Record); 2974} 2975 2976void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) { 2977 AddAPInt(Value.bitcastToAPInt(), Record); 2978} 2979 2980void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) { 2981 Record.push_back(getIdentifierRef(II)); 2982} 2983 2984IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) { 2985 if (II == 0) 2986 return 0; 2987 2988 IdentID &ID = IdentifierIDs[II]; 2989 if (ID == 0) 2990 ID = NextIdentID++; 2991 return ID; 2992} 2993 2994MacroID ASTWriter::getMacroDefinitionID(MacroDefinition *MD) { 2995 if (MD == 0) 2996 return 0; 2997 2998 MacroID &ID = MacroDefinitions[MD]; 2999 if (ID == 0) 3000 ID = NextMacroID++; 3001 return ID; 3002} 3003 3004void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) { 3005 Record.push_back(getSelectorRef(SelRef)); 3006} 3007 3008SelectorID ASTWriter::getSelectorRef(Selector Sel) { 3009 if (Sel.getAsOpaquePtr() == 0) { 3010 return 0; 3011 } 3012 3013 SelectorID &SID = SelectorIDs[Sel]; 3014 if (SID == 0 && Chain) { 3015 // This might trigger a ReadSelector callback, which will set the ID for 3016 // this selector. 3017 Chain->LoadSelector(Sel); 3018 } 3019 if (SID == 0) { 3020 SID = NextSelectorID++; 3021 } 3022 return SID; 3023} 3024 3025void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) { 3026 AddDeclRef(Temp->getDestructor(), Record); 3027} 3028 3029void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases, 3030 CXXBaseSpecifier const *BasesEnd, 3031 RecordDataImpl &Record) { 3032 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded"); 3033 CXXBaseSpecifiersToWrite.push_back( 3034 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID, 3035 Bases, BasesEnd)); 3036 Record.push_back(NextCXXBaseSpecifiersID++); 3037} 3038 3039void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind, 3040 const TemplateArgumentLocInfo &Arg, 3041 RecordDataImpl &Record) { 3042 switch (Kind) { 3043 case TemplateArgument::Expression: 3044 AddStmt(Arg.getAsExpr()); 3045 break; 3046 case TemplateArgument::Type: 3047 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record); 3048 break; 3049 case TemplateArgument::Template: 3050 AddSourceRange(Arg.getTemplateQualifierRange(), Record); 3051 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 3052 break; 3053 case TemplateArgument::TemplateExpansion: 3054 AddSourceRange(Arg.getTemplateQualifierRange(), Record); 3055 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 3056 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record); 3057 break; 3058 case TemplateArgument::Null: 3059 case TemplateArgument::Integral: 3060 case TemplateArgument::Declaration: 3061 case TemplateArgument::Pack: 3062 break; 3063 } 3064} 3065 3066void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg, 3067 RecordDataImpl &Record) { 3068 AddTemplateArgument(Arg.getArgument(), Record); 3069 3070 if (Arg.getArgument().getKind() == TemplateArgument::Expression) { 3071 bool InfoHasSameExpr 3072 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr(); 3073 Record.push_back(InfoHasSameExpr); 3074 if (InfoHasSameExpr) 3075 return; // Avoid storing the same expr twice. 3076 } 3077 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(), 3078 Record); 3079} 3080 3081void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordDataImpl &Record) { 3082 if (TInfo == 0) { 3083 AddTypeRef(QualType(), Record); 3084 return; 3085 } 3086 3087 AddTypeRef(TInfo->getType(), Record); 3088 TypeLocWriter TLW(*this, Record); 3089 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc()) 3090 TLW.Visit(TL); 3091} 3092 3093void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) { 3094 Record.push_back(GetOrCreateTypeID(T)); 3095} 3096 3097TypeID ASTWriter::GetOrCreateTypeID(QualType T) { 3098 return MakeTypeID(T, 3099 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this)); 3100} 3101 3102TypeID ASTWriter::getTypeID(QualType T) const { 3103 return MakeTypeID(T, 3104 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this)); 3105} 3106 3107TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) { 3108 if (T.isNull()) 3109 return TypeIdx(); 3110 assert(!T.getLocalFastQualifiers()); 3111 3112 TypeIdx &Idx = TypeIdxs[T]; 3113 if (Idx.getIndex() == 0) { 3114 // We haven't seen this type before. Assign it a new ID and put it 3115 // into the queue of types to emit. 3116 Idx = TypeIdx(NextTypeID++); 3117 DeclTypesToEmit.push(T); 3118 } 3119 return Idx; 3120} 3121 3122TypeIdx ASTWriter::getTypeIdx(QualType T) const { 3123 if (T.isNull()) 3124 return TypeIdx(); 3125 assert(!T.getLocalFastQualifiers()); 3126 3127 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 3128 assert(I != TypeIdxs.end() && "Type not emitted!"); 3129 return I->second; 3130} 3131 3132void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) { 3133 Record.push_back(GetDeclRef(D)); 3134} 3135 3136DeclID ASTWriter::GetDeclRef(const Decl *D) { 3137 if (D == 0) { 3138 return 0; 3139 } 3140 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer"); 3141 DeclID &ID = DeclIDs[D]; 3142 if (ID == 0) { 3143 // We haven't seen this declaration before. Give it a new ID and 3144 // enqueue it in the list of declarations to emit. 3145 ID = NextDeclID++; 3146 DeclTypesToEmit.push(const_cast<Decl *>(D)); 3147 } else if (ID < FirstDeclID && D->isChangedSinceDeserialization()) { 3148 // We don't add it to the replacement collection here, because we don't 3149 // have the offset yet. 3150 DeclTypesToEmit.push(const_cast<Decl *>(D)); 3151 // Reset the flag, so that we don't add this decl multiple times. 3152 const_cast<Decl *>(D)->setChangedSinceDeserialization(false); 3153 } 3154 3155 return ID; 3156} 3157 3158DeclID ASTWriter::getDeclID(const Decl *D) { 3159 if (D == 0) 3160 return 0; 3161 3162 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!"); 3163 return DeclIDs[D]; 3164} 3165 3166void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) { 3167 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc. 3168 Record.push_back(Name.getNameKind()); 3169 switch (Name.getNameKind()) { 3170 case DeclarationName::Identifier: 3171 AddIdentifierRef(Name.getAsIdentifierInfo(), Record); 3172 break; 3173 3174 case DeclarationName::ObjCZeroArgSelector: 3175 case DeclarationName::ObjCOneArgSelector: 3176 case DeclarationName::ObjCMultiArgSelector: 3177 AddSelectorRef(Name.getObjCSelector(), Record); 3178 break; 3179 3180 case DeclarationName::CXXConstructorName: 3181 case DeclarationName::CXXDestructorName: 3182 case DeclarationName::CXXConversionFunctionName: 3183 AddTypeRef(Name.getCXXNameType(), Record); 3184 break; 3185 3186 case DeclarationName::CXXOperatorName: 3187 Record.push_back(Name.getCXXOverloadedOperator()); 3188 break; 3189 3190 case DeclarationName::CXXLiteralOperatorName: 3191 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record); 3192 break; 3193 3194 case DeclarationName::CXXUsingDirective: 3195 // No extra data to emit 3196 break; 3197 } 3198} 3199 3200void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 3201 DeclarationName Name, RecordDataImpl &Record) { 3202 switch (Name.getNameKind()) { 3203 case DeclarationName::CXXConstructorName: 3204 case DeclarationName::CXXDestructorName: 3205 case DeclarationName::CXXConversionFunctionName: 3206 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record); 3207 break; 3208 3209 case DeclarationName::CXXOperatorName: 3210 AddSourceLocation( 3211 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc), 3212 Record); 3213 AddSourceLocation( 3214 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc), 3215 Record); 3216 break; 3217 3218 case DeclarationName::CXXLiteralOperatorName: 3219 AddSourceLocation( 3220 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc), 3221 Record); 3222 break; 3223 3224 case DeclarationName::Identifier: 3225 case DeclarationName::ObjCZeroArgSelector: 3226 case DeclarationName::ObjCOneArgSelector: 3227 case DeclarationName::ObjCMultiArgSelector: 3228 case DeclarationName::CXXUsingDirective: 3229 break; 3230 } 3231} 3232 3233void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 3234 RecordDataImpl &Record) { 3235 AddDeclarationName(NameInfo.getName(), Record); 3236 AddSourceLocation(NameInfo.getLoc(), Record); 3237 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record); 3238} 3239 3240void ASTWriter::AddQualifierInfo(const QualifierInfo &Info, 3241 RecordDataImpl &Record) { 3242 AddNestedNameSpecifier(Info.NNS, Record); 3243 AddSourceRange(Info.NNSRange, Record); 3244 Record.push_back(Info.NumTemplParamLists); 3245 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i) 3246 AddTemplateParameterList(Info.TemplParamLists[i], Record); 3247} 3248 3249void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS, 3250 RecordDataImpl &Record) { 3251 // Nested name specifiers usually aren't too long. I think that 8 would 3252 // typically accomodate the vast majority. 3253 llvm::SmallVector<NestedNameSpecifier *, 8> NestedNames; 3254 3255 // Push each of the NNS's onto a stack for serialization in reverse order. 3256 while (NNS) { 3257 NestedNames.push_back(NNS); 3258 NNS = NNS->getPrefix(); 3259 } 3260 3261 Record.push_back(NestedNames.size()); 3262 while(!NestedNames.empty()) { 3263 NNS = NestedNames.pop_back_val(); 3264 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind(); 3265 Record.push_back(Kind); 3266 switch (Kind) { 3267 case NestedNameSpecifier::Identifier: 3268 AddIdentifierRef(NNS->getAsIdentifier(), Record); 3269 break; 3270 3271 case NestedNameSpecifier::Namespace: 3272 AddDeclRef(NNS->getAsNamespace(), Record); 3273 break; 3274 3275 case NestedNameSpecifier::TypeSpec: 3276 case NestedNameSpecifier::TypeSpecWithTemplate: 3277 AddTypeRef(QualType(NNS->getAsType(), 0), Record); 3278 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 3279 break; 3280 3281 case NestedNameSpecifier::Global: 3282 // Don't need to write an associated value. 3283 break; 3284 } 3285 } 3286} 3287 3288void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) { 3289 TemplateName::NameKind Kind = Name.getKind(); 3290 Record.push_back(Kind); 3291 switch (Kind) { 3292 case TemplateName::Template: 3293 AddDeclRef(Name.getAsTemplateDecl(), Record); 3294 break; 3295 3296 case TemplateName::OverloadedTemplate: { 3297 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate(); 3298 Record.push_back(OvT->size()); 3299 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end(); 3300 I != E; ++I) 3301 AddDeclRef(*I, Record); 3302 break; 3303 } 3304 3305 case TemplateName::QualifiedTemplate: { 3306 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName(); 3307 AddNestedNameSpecifier(QualT->getQualifier(), Record); 3308 Record.push_back(QualT->hasTemplateKeyword()); 3309 AddDeclRef(QualT->getTemplateDecl(), Record); 3310 break; 3311 } 3312 3313 case TemplateName::DependentTemplate: { 3314 DependentTemplateName *DepT = Name.getAsDependentTemplateName(); 3315 AddNestedNameSpecifier(DepT->getQualifier(), Record); 3316 Record.push_back(DepT->isIdentifier()); 3317 if (DepT->isIdentifier()) 3318 AddIdentifierRef(DepT->getIdentifier(), Record); 3319 else 3320 Record.push_back(DepT->getOperator()); 3321 break; 3322 } 3323 3324 case TemplateName::SubstTemplateTemplateParmPack: { 3325 SubstTemplateTemplateParmPackStorage *SubstPack 3326 = Name.getAsSubstTemplateTemplateParmPack(); 3327 AddDeclRef(SubstPack->getParameterPack(), Record); 3328 AddTemplateArgument(SubstPack->getArgumentPack(), Record); 3329 break; 3330 } 3331 } 3332} 3333 3334void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg, 3335 RecordDataImpl &Record) { 3336 Record.push_back(Arg.getKind()); 3337 switch (Arg.getKind()) { 3338 case TemplateArgument::Null: 3339 break; 3340 case TemplateArgument::Type: 3341 AddTypeRef(Arg.getAsType(), Record); 3342 break; 3343 case TemplateArgument::Declaration: 3344 AddDeclRef(Arg.getAsDecl(), Record); 3345 break; 3346 case TemplateArgument::Integral: 3347 AddAPSInt(*Arg.getAsIntegral(), Record); 3348 AddTypeRef(Arg.getIntegralType(), Record); 3349 break; 3350 case TemplateArgument::Template: 3351 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 3352 break; 3353 case TemplateArgument::TemplateExpansion: 3354 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 3355 if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions()) 3356 Record.push_back(*NumExpansions + 1); 3357 else 3358 Record.push_back(0); 3359 break; 3360 case TemplateArgument::Expression: 3361 AddStmt(Arg.getAsExpr()); 3362 break; 3363 case TemplateArgument::Pack: 3364 Record.push_back(Arg.pack_size()); 3365 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end(); 3366 I != E; ++I) 3367 AddTemplateArgument(*I, Record); 3368 break; 3369 } 3370} 3371 3372void 3373ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams, 3374 RecordDataImpl &Record) { 3375 assert(TemplateParams && "No TemplateParams!"); 3376 AddSourceLocation(TemplateParams->getTemplateLoc(), Record); 3377 AddSourceLocation(TemplateParams->getLAngleLoc(), Record); 3378 AddSourceLocation(TemplateParams->getRAngleLoc(), Record); 3379 Record.push_back(TemplateParams->size()); 3380 for (TemplateParameterList::const_iterator 3381 P = TemplateParams->begin(), PEnd = TemplateParams->end(); 3382 P != PEnd; ++P) 3383 AddDeclRef(*P, Record); 3384} 3385 3386/// \brief Emit a template argument list. 3387void 3388ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs, 3389 RecordDataImpl &Record) { 3390 assert(TemplateArgs && "No TemplateArgs!"); 3391 Record.push_back(TemplateArgs->size()); 3392 for (int i=0, e = TemplateArgs->size(); i != e; ++i) 3393 AddTemplateArgument(TemplateArgs->get(i), Record); 3394} 3395 3396 3397void 3398ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) { 3399 Record.push_back(Set.size()); 3400 for (UnresolvedSetImpl::const_iterator 3401 I = Set.begin(), E = Set.end(); I != E; ++I) { 3402 AddDeclRef(I.getDecl(), Record); 3403 Record.push_back(I.getAccess()); 3404 } 3405} 3406 3407void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base, 3408 RecordDataImpl &Record) { 3409 Record.push_back(Base.isVirtual()); 3410 Record.push_back(Base.isBaseOfClass()); 3411 Record.push_back(Base.getAccessSpecifierAsWritten()); 3412 Record.push_back(Base.getInheritConstructors()); 3413 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record); 3414 AddSourceRange(Base.getSourceRange(), Record); 3415 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 3416 : SourceLocation(), 3417 Record); 3418} 3419 3420void ASTWriter::FlushCXXBaseSpecifiers() { 3421 RecordData Record; 3422 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) { 3423 Record.clear(); 3424 3425 // Record the offset of this base-specifier set. 3426 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - FirstCXXBaseSpecifiersID; 3427 if (Index == CXXBaseSpecifiersOffsets.size()) 3428 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo()); 3429 else { 3430 if (Index > CXXBaseSpecifiersOffsets.size()) 3431 CXXBaseSpecifiersOffsets.resize(Index + 1); 3432 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo(); 3433 } 3434 3435 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases, 3436 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd; 3437 Record.push_back(BEnd - B); 3438 for (; B != BEnd; ++B) 3439 AddCXXBaseSpecifier(*B, Record); 3440 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record); 3441 3442 // Flush any expressions that were written as part of the base specifiers. 3443 FlushStmts(); 3444 } 3445 3446 CXXBaseSpecifiersToWrite.clear(); 3447} 3448 3449void ASTWriter::AddCXXCtorInitializers( 3450 const CXXCtorInitializer * const *CtorInitializers, 3451 unsigned NumCtorInitializers, 3452 RecordDataImpl &Record) { 3453 Record.push_back(NumCtorInitializers); 3454 for (unsigned i=0; i != NumCtorInitializers; ++i) { 3455 const CXXCtorInitializer *Init = CtorInitializers[i]; 3456 3457 Record.push_back(Init->isBaseInitializer()); 3458 if (Init->isBaseInitializer()) { 3459 AddTypeSourceInfo(Init->getBaseClassInfo(), Record); 3460 Record.push_back(Init->isBaseVirtual()); 3461 } else { 3462 Record.push_back(Init->isIndirectMemberInitializer()); 3463 if (Init->isIndirectMemberInitializer()) 3464 AddDeclRef(Init->getIndirectMember(), Record); 3465 else 3466 AddDeclRef(Init->getMember(), Record); 3467 } 3468 3469 AddSourceLocation(Init->getMemberLocation(), Record); 3470 AddStmt(Init->getInit()); 3471 AddSourceLocation(Init->getLParenLoc(), Record); 3472 AddSourceLocation(Init->getRParenLoc(), Record); 3473 Record.push_back(Init->isWritten()); 3474 if (Init->isWritten()) { 3475 Record.push_back(Init->getSourceOrder()); 3476 } else { 3477 Record.push_back(Init->getNumArrayIndices()); 3478 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i) 3479 AddDeclRef(Init->getArrayIndex(i), Record); 3480 } 3481 } 3482} 3483 3484void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) { 3485 assert(D->DefinitionData); 3486 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData; 3487 Record.push_back(Data.UserDeclaredConstructor); 3488 Record.push_back(Data.UserDeclaredCopyConstructor); 3489 Record.push_back(Data.UserDeclaredCopyAssignment); 3490 Record.push_back(Data.UserDeclaredDestructor); 3491 Record.push_back(Data.Aggregate); 3492 Record.push_back(Data.PlainOldData); 3493 Record.push_back(Data.Empty); 3494 Record.push_back(Data.Polymorphic); 3495 Record.push_back(Data.Abstract); 3496 Record.push_back(Data.HasTrivialConstructor); 3497 Record.push_back(Data.HasTrivialCopyConstructor); 3498 Record.push_back(Data.HasTrivialCopyAssignment); 3499 Record.push_back(Data.HasTrivialDestructor); 3500 Record.push_back(Data.ComputedVisibleConversions); 3501 Record.push_back(Data.DeclaredDefaultConstructor); 3502 Record.push_back(Data.DeclaredCopyConstructor); 3503 Record.push_back(Data.DeclaredCopyAssignment); 3504 Record.push_back(Data.DeclaredDestructor); 3505 3506 Record.push_back(Data.NumBases); 3507 if (Data.NumBases > 0) 3508 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases, 3509 Record); 3510 3511 // FIXME: Make VBases lazily computed when needed to avoid storing them. 3512 Record.push_back(Data.NumVBases); 3513 if (Data.NumVBases > 0) 3514 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases, 3515 Record); 3516 3517 AddUnresolvedSet(Data.Conversions, Record); 3518 AddUnresolvedSet(Data.VisibleConversions, Record); 3519 // Data.Definition is the owning decl, no need to write it. 3520 AddDeclRef(Data.FirstFriend, Record); 3521} 3522 3523void ASTWriter::ReaderInitialized(ASTReader *Reader) { 3524 assert(Reader && "Cannot remove chain"); 3525 assert(!Chain && "Cannot replace chain"); 3526 assert(FirstDeclID == NextDeclID && 3527 FirstTypeID == NextTypeID && 3528 FirstIdentID == NextIdentID && 3529 FirstSelectorID == NextSelectorID && 3530 FirstMacroID == NextMacroID && 3531 FirstCXXBaseSpecifiersID == NextCXXBaseSpecifiersID && 3532 "Setting chain after writing has started."); 3533 Chain = Reader; 3534 3535 FirstDeclID += Chain->getTotalNumDecls(); 3536 FirstTypeID += Chain->getTotalNumTypes(); 3537 FirstIdentID += Chain->getTotalNumIdentifiers(); 3538 FirstSelectorID += Chain->getTotalNumSelectors(); 3539 FirstMacroID += Chain->getTotalNumMacroDefinitions(); 3540 FirstCXXBaseSpecifiersID += Chain->getTotalNumCXXBaseSpecifiers(); 3541 NextDeclID = FirstDeclID; 3542 NextTypeID = FirstTypeID; 3543 NextIdentID = FirstIdentID; 3544 NextSelectorID = FirstSelectorID; 3545 NextMacroID = FirstMacroID; 3546 NextCXXBaseSpecifiersID = FirstCXXBaseSpecifiersID; 3547} 3548 3549void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) { 3550 IdentifierIDs[II] = ID; 3551} 3552 3553void ASTWriter::TypeRead(TypeIdx Idx, QualType T) { 3554 // Always take the highest-numbered type index. This copes with an interesting 3555 // case for chained AST writing where we schedule writing the type and then, 3556 // later, deserialize the type from another AST. In this case, we want to 3557 // keep the higher-numbered entry so that we can properly write it out to 3558 // the AST file. 3559 TypeIdx &StoredIdx = TypeIdxs[T]; 3560 if (Idx.getIndex() >= StoredIdx.getIndex()) 3561 StoredIdx = Idx; 3562} 3563 3564void ASTWriter::DeclRead(DeclID ID, const Decl *D) { 3565 DeclIDs[D] = ID; 3566} 3567 3568void ASTWriter::SelectorRead(SelectorID ID, Selector S) { 3569 SelectorIDs[S] = ID; 3570} 3571 3572void ASTWriter::MacroDefinitionRead(serialization::MacroID ID, 3573 MacroDefinition *MD) { 3574 MacroDefinitions[MD] = ID; 3575} 3576 3577void ASTWriter::CompletedTagDefinition(const TagDecl *D) { 3578 assert(D->isDefinition()); 3579 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 3580 // We are interested when a PCH decl is modified. 3581 if (RD->getPCHLevel() > 0) { 3582 // A forward reference was mutated into a definition. Rewrite it. 3583 // FIXME: This happens during template instantiation, should we 3584 // have created a new definition decl instead ? 3585 RewriteDecl(RD); 3586 } 3587 3588 for (CXXRecordDecl::redecl_iterator 3589 I = RD->redecls_begin(), E = RD->redecls_end(); I != E; ++I) { 3590 CXXRecordDecl *Redecl = cast<CXXRecordDecl>(*I); 3591 if (Redecl == RD) 3592 continue; 3593 3594 // We are interested when a PCH decl is modified. 3595 if (Redecl->getPCHLevel() > 0) { 3596 UpdateRecord &Record = DeclUpdates[Redecl]; 3597 Record.push_back(UPD_CXX_SET_DEFINITIONDATA); 3598 assert(Redecl->DefinitionData); 3599 assert(Redecl->DefinitionData->Definition == D); 3600 AddDeclRef(D, Record); // the DefinitionDecl 3601 } 3602 } 3603 } 3604} 3605void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) { 3606 // TU and namespaces are handled elsewhere. 3607 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC)) 3608 return; 3609 3610 if (!(D->getPCHLevel() == 0 && cast<Decl>(DC)->getPCHLevel() > 0)) 3611 return; // Not a source decl added to a DeclContext from PCH. 3612 3613 AddUpdatedDeclContext(DC); 3614} 3615 3616void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { 3617 assert(D->isImplicit()); 3618 if (!(D->getPCHLevel() == 0 && RD->getPCHLevel() > 0)) 3619 return; // Not a source member added to a class from PCH. 3620 if (!isa<CXXMethodDecl>(D)) 3621 return; // We are interested in lazily declared implicit methods. 3622 3623 // A decl coming from PCH was modified. 3624 assert(RD->isDefinition()); 3625 UpdateRecord &Record = DeclUpdates[RD]; 3626 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER); 3627 AddDeclRef(D, Record); 3628} 3629 3630void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD, 3631 const ClassTemplateSpecializationDecl *D) { 3632 // The specializations set is kept in the canonical template. 3633 TD = TD->getCanonicalDecl(); 3634 if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0)) 3635 return; // Not a source specialization added to a template from PCH. 3636 3637 UpdateRecord &Record = DeclUpdates[TD]; 3638 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION); 3639 AddDeclRef(D, Record); 3640} 3641 3642ASTSerializationListener::~ASTSerializationListener() { } 3643