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