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