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