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