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