1 //===--- ASTWriter.cpp - AST File Writer ----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTWriter class, which writes AST files.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Serialization/ASTWriter.h"
15 #include "clang/Serialization/ASTSerializationListener.h"
16 #include "ASTCommon.h"
17 #include "clang/Sema/Sema.h"
18 #include "clang/Sema/IdentifierResolver.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclContextInternals.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/Type.h"
27 #include "clang/AST/TypeLocVisitor.h"
28 #include "clang/Serialization/ASTReader.h"
29 #include "clang/Lex/MacroInfo.h"
30 #include "clang/Lex/PreprocessingRecord.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/HeaderSearch.h"
33 #include "clang/Basic/FileManager.h"
34 #include "clang/Basic/FileSystemStatCache.h"
35 #include "clang/Basic/OnDiskHashTable.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/SourceManagerInternals.h"
38 #include "clang/Basic/TargetInfo.h"
39 #include "clang/Basic/Version.h"
40 #include "clang/Basic/VersionTuple.h"
41 #include "llvm/ADT/APFloat.h"
42 #include "llvm/ADT/APInt.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/Bitcode/BitstreamWriter.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
50 using namespace clang;
51 using namespace clang::serialization;
53 template <typename T, typename Allocator>
54 static llvm::StringRef data(const std::vector<T, Allocator> &v) {
55 if (v.empty()) return llvm::StringRef();
56 return llvm::StringRef(reinterpret_cast<const char*>(&v[0]),
57 sizeof(T) * v.size());
61 static llvm::StringRef data(const llvm::SmallVectorImpl<T> &v) {
62 return llvm::StringRef(reinterpret_cast<const char*>(v.data()),
63 sizeof(T) * v.size());
66 //===----------------------------------------------------------------------===//
68 //===----------------------------------------------------------------------===//
73 ASTWriter::RecordDataImpl &Record;
76 /// \brief Type code that corresponds to the record generated.
79 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
80 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
82 void VisitArrayType(const ArrayType *T);
83 void VisitFunctionType(const FunctionType *T);
84 void VisitTagType(const TagType *T);
86 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
87 #define ABSTRACT_TYPE(Class, Base)
88 #include "clang/AST/TypeNodes.def"
92 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
93 assert(false && "Built-in types are never serialized");
96 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
97 Writer.AddTypeRef(T->getElementType(), Record);
101 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
102 Writer.AddTypeRef(T->getPointeeType(), Record);
106 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
107 Writer.AddTypeRef(T->getPointeeType(), Record);
108 Code = TYPE_BLOCK_POINTER;
111 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
112 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
113 Record.push_back(T->isSpelledAsLValue());
114 Code = TYPE_LVALUE_REFERENCE;
117 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
118 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
119 Code = TYPE_RVALUE_REFERENCE;
122 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
123 Writer.AddTypeRef(T->getPointeeType(), Record);
124 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
125 Code = TYPE_MEMBER_POINTER;
128 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
129 Writer.AddTypeRef(T->getElementType(), Record);
130 Record.push_back(T->getSizeModifier()); // FIXME: stable values
131 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
134 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
136 Writer.AddAPInt(T->getSize(), Record);
137 Code = TYPE_CONSTANT_ARRAY;
140 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
142 Code = TYPE_INCOMPLETE_ARRAY;
145 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
147 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
148 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
149 Writer.AddStmt(T->getSizeExpr());
150 Code = TYPE_VARIABLE_ARRAY;
153 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
154 Writer.AddTypeRef(T->getElementType(), Record);
155 Record.push_back(T->getNumElements());
156 Record.push_back(T->getVectorKind());
160 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
162 Code = TYPE_EXT_VECTOR;
165 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
166 Writer.AddTypeRef(T->getResultType(), Record);
167 FunctionType::ExtInfo C = T->getExtInfo();
168 Record.push_back(C.getNoReturn());
169 Record.push_back(C.getHasRegParm());
170 Record.push_back(C.getRegParm());
171 // FIXME: need to stabilize encoding of calling convention...
172 Record.push_back(C.getCC());
175 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
176 VisitFunctionType(T);
177 Code = TYPE_FUNCTION_NO_PROTO;
180 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
181 VisitFunctionType(T);
182 Record.push_back(T->getNumArgs());
183 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
184 Writer.AddTypeRef(T->getArgType(I), Record);
185 Record.push_back(T->isVariadic());
186 Record.push_back(T->getTypeQuals());
187 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
188 Record.push_back(T->getExceptionSpecType());
189 if (T->getExceptionSpecType() == EST_Dynamic) {
190 Record.push_back(T->getNumExceptions());
191 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
192 Writer.AddTypeRef(T->getExceptionType(I), Record);
193 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
194 Writer.AddStmt(T->getNoexceptExpr());
196 Code = TYPE_FUNCTION_PROTO;
199 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
200 Writer.AddDeclRef(T->getDecl(), Record);
201 Code = TYPE_UNRESOLVED_USING;
204 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
205 Writer.AddDeclRef(T->getDecl(), Record);
206 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
207 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
211 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
212 Writer.AddStmt(T->getUnderlyingExpr());
213 Code = TYPE_TYPEOF_EXPR;
216 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
217 Writer.AddTypeRef(T->getUnderlyingType(), Record);
221 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
222 Writer.AddStmt(T->getUnderlyingExpr());
223 Code = TYPE_DECLTYPE;
226 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
227 Writer.AddTypeRef(T->getBaseType(), Record);
228 Writer.AddTypeRef(T->getUnderlyingType(), Record);
229 Record.push_back(T->getUTTKind());
230 Code = TYPE_UNARY_TRANSFORM;
233 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
234 Writer.AddTypeRef(T->getDeducedType(), Record);
238 void ASTTypeWriter::VisitTagType(const TagType *T) {
239 Record.push_back(T->isDependentType());
240 Writer.AddDeclRef(T->getDecl(), Record);
241 assert(!T->isBeingDefined() &&
242 "Cannot serialize in the middle of a type definition");
245 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
250 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
255 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
256 Writer.AddTypeRef(T->getModifiedType(), Record);
257 Writer.AddTypeRef(T->getEquivalentType(), Record);
258 Record.push_back(T->getAttrKind());
259 Code = TYPE_ATTRIBUTED;
263 ASTTypeWriter::VisitSubstTemplateTypeParmType(
264 const SubstTemplateTypeParmType *T) {
265 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
266 Writer.AddTypeRef(T->getReplacementType(), Record);
267 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
271 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
272 const SubstTemplateTypeParmPackType *T) {
273 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
274 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
275 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
279 ASTTypeWriter::VisitTemplateSpecializationType(
280 const TemplateSpecializationType *T) {
281 Record.push_back(T->isDependentType());
282 Writer.AddTemplateName(T->getTemplateName(), Record);
283 Record.push_back(T->getNumArgs());
284 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
285 ArgI != ArgE; ++ArgI)
286 Writer.AddTemplateArgument(*ArgI, Record);
287 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
288 T->isCanonicalUnqualified() ? QualType()
289 : T->getCanonicalTypeInternal(),
291 Code = TYPE_TEMPLATE_SPECIALIZATION;
295 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
297 Writer.AddStmt(T->getSizeExpr());
298 Writer.AddSourceRange(T->getBracketsRange(), Record);
299 Code = TYPE_DEPENDENT_SIZED_ARRAY;
303 ASTTypeWriter::VisitDependentSizedExtVectorType(
304 const DependentSizedExtVectorType *T) {
305 // FIXME: Serialize this type (C++ only)
306 assert(false && "Cannot serialize dependent sized extended vector types");
310 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
311 Record.push_back(T->getDepth());
312 Record.push_back(T->getIndex());
313 Record.push_back(T->isParameterPack());
314 Writer.AddDeclRef(T->getDecl(), Record);
315 Code = TYPE_TEMPLATE_TYPE_PARM;
319 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
320 Record.push_back(T->getKeyword());
321 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
322 Writer.AddIdentifierRef(T->getIdentifier(), Record);
323 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
324 : T->getCanonicalTypeInternal(),
326 Code = TYPE_DEPENDENT_NAME;
330 ASTTypeWriter::VisitDependentTemplateSpecializationType(
331 const DependentTemplateSpecializationType *T) {
332 Record.push_back(T->getKeyword());
333 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
334 Writer.AddIdentifierRef(T->getIdentifier(), Record);
335 Record.push_back(T->getNumArgs());
336 for (DependentTemplateSpecializationType::iterator
337 I = T->begin(), E = T->end(); I != E; ++I)
338 Writer.AddTemplateArgument(*I, Record);
339 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
342 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
343 Writer.AddTypeRef(T->getPattern(), Record);
344 if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions())
345 Record.push_back(*NumExpansions + 1);
348 Code = TYPE_PACK_EXPANSION;
351 void ASTTypeWriter::VisitParenType(const ParenType *T) {
352 Writer.AddTypeRef(T->getInnerType(), Record);
356 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
357 Record.push_back(T->getKeyword());
358 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
359 Writer.AddTypeRef(T->getNamedType(), Record);
360 Code = TYPE_ELABORATED;
363 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
364 Writer.AddDeclRef(T->getDecl(), Record);
365 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
366 Code = TYPE_INJECTED_CLASS_NAME;
369 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
370 Writer.AddDeclRef(T->getDecl(), Record);
371 Code = TYPE_OBJC_INTERFACE;
374 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
375 Writer.AddTypeRef(T->getBaseType(), Record);
376 Record.push_back(T->getNumProtocols());
377 for (ObjCObjectType::qual_iterator I = T->qual_begin(),
378 E = T->qual_end(); I != E; ++I)
379 Writer.AddDeclRef(*I, Record);
380 Code = TYPE_OBJC_OBJECT;
384 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
385 Writer.AddTypeRef(T->getPointeeType(), Record);
386 Code = TYPE_OBJC_OBJECT_POINTER;
391 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
393 ASTWriter::RecordDataImpl &Record;
396 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
397 : Writer(Writer), Record(Record) { }
399 #define ABSTRACT_TYPELOC(CLASS, PARENT)
400 #define TYPELOC(CLASS, PARENT) \
401 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
402 #include "clang/AST/TypeLocNodes.def"
404 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
405 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
410 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
413 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
414 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
415 if (TL.needsExtraLocalData()) {
416 Record.push_back(TL.getWrittenTypeSpec());
417 Record.push_back(TL.getWrittenSignSpec());
418 Record.push_back(TL.getWrittenWidthSpec());
419 Record.push_back(TL.hasModeAttr());
422 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
423 Writer.AddSourceLocation(TL.getNameLoc(), Record);
425 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
426 Writer.AddSourceLocation(TL.getStarLoc(), Record);
428 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
429 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
431 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
432 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
434 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
435 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
437 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
438 Writer.AddSourceLocation(TL.getStarLoc(), Record);
439 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
441 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
442 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
443 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
444 Record.push_back(TL.getSizeExpr() ? 1 : 0);
445 if (TL.getSizeExpr())
446 Writer.AddStmt(TL.getSizeExpr());
448 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
449 VisitArrayTypeLoc(TL);
451 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
452 VisitArrayTypeLoc(TL);
454 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
455 VisitArrayTypeLoc(TL);
457 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
458 DependentSizedArrayTypeLoc TL) {
459 VisitArrayTypeLoc(TL);
461 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
462 DependentSizedExtVectorTypeLoc TL) {
463 Writer.AddSourceLocation(TL.getNameLoc(), Record);
465 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
466 Writer.AddSourceLocation(TL.getNameLoc(), Record);
468 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
469 Writer.AddSourceLocation(TL.getNameLoc(), Record);
471 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
472 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
473 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
474 Record.push_back(TL.getTrailingReturn());
475 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
476 Writer.AddDeclRef(TL.getArg(i), Record);
478 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
479 VisitFunctionTypeLoc(TL);
481 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
482 VisitFunctionTypeLoc(TL);
484 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
485 Writer.AddSourceLocation(TL.getNameLoc(), Record);
487 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
488 Writer.AddSourceLocation(TL.getNameLoc(), Record);
490 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
491 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
492 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
493 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
495 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
496 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
497 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
498 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
499 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
501 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
502 Writer.AddSourceLocation(TL.getNameLoc(), Record);
504 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
505 Writer.AddSourceLocation(TL.getKWLoc(), Record);
506 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
507 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
508 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
510 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
511 Writer.AddSourceLocation(TL.getNameLoc(), Record);
513 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
514 Writer.AddSourceLocation(TL.getNameLoc(), Record);
516 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
517 Writer.AddSourceLocation(TL.getNameLoc(), Record);
519 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
520 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
521 if (TL.hasAttrOperand()) {
522 SourceRange range = TL.getAttrOperandParensRange();
523 Writer.AddSourceLocation(range.getBegin(), Record);
524 Writer.AddSourceLocation(range.getEnd(), Record);
526 if (TL.hasAttrExprOperand()) {
527 Expr *operand = TL.getAttrExprOperand();
528 Record.push_back(operand ? 1 : 0);
529 if (operand) Writer.AddStmt(operand);
530 } else if (TL.hasAttrEnumOperand()) {
531 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
534 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
535 Writer.AddSourceLocation(TL.getNameLoc(), Record);
537 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
538 SubstTemplateTypeParmTypeLoc TL) {
539 Writer.AddSourceLocation(TL.getNameLoc(), Record);
541 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
542 SubstTemplateTypeParmPackTypeLoc TL) {
543 Writer.AddSourceLocation(TL.getNameLoc(), Record);
545 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
546 TemplateSpecializationTypeLoc TL) {
547 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
548 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
549 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
550 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
551 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
552 TL.getArgLoc(i).getLocInfo(), Record);
554 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
555 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
556 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
558 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
559 Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
560 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
562 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
563 Writer.AddSourceLocation(TL.getNameLoc(), Record);
565 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
566 Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
567 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
568 Writer.AddSourceLocation(TL.getNameLoc(), Record);
570 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
571 DependentTemplateSpecializationTypeLoc TL) {
572 Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
573 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
574 Writer.AddSourceLocation(TL.getNameLoc(), Record);
575 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
576 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
577 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
578 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
579 TL.getArgLoc(I).getLocInfo(), Record);
581 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
582 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
584 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
585 Writer.AddSourceLocation(TL.getNameLoc(), Record);
587 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
588 Record.push_back(TL.hasBaseTypeAsWritten());
589 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
590 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
591 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
592 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
594 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
595 Writer.AddSourceLocation(TL.getStarLoc(), Record);
598 //===----------------------------------------------------------------------===//
599 // ASTWriter Implementation
600 //===----------------------------------------------------------------------===//
602 static void EmitBlockID(unsigned ID, const char *Name,
603 llvm::BitstreamWriter &Stream,
604 ASTWriter::RecordDataImpl &Record) {
606 Record.push_back(ID);
607 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
609 // Emit the block name if present.
610 if (Name == 0 || Name[0] == 0) return;
613 Record.push_back(*Name++);
614 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
617 static void EmitRecordID(unsigned ID, const char *Name,
618 llvm::BitstreamWriter &Stream,
619 ASTWriter::RecordDataImpl &Record) {
621 Record.push_back(ID);
623 Record.push_back(*Name++);
624 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
627 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
628 ASTWriter::RecordDataImpl &Record) {
629 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
631 RECORD(STMT_NULL_PTR);
633 RECORD(STMT_COMPOUND);
635 RECORD(STMT_DEFAULT);
643 RECORD(STMT_INDIRECT_GOTO);
644 RECORD(STMT_CONTINUE);
649 RECORD(EXPR_PREDEFINED);
650 RECORD(EXPR_DECL_REF);
651 RECORD(EXPR_INTEGER_LITERAL);
652 RECORD(EXPR_FLOATING_LITERAL);
653 RECORD(EXPR_IMAGINARY_LITERAL);
654 RECORD(EXPR_STRING_LITERAL);
655 RECORD(EXPR_CHARACTER_LITERAL);
657 RECORD(EXPR_UNARY_OPERATOR);
658 RECORD(EXPR_SIZEOF_ALIGN_OF);
659 RECORD(EXPR_ARRAY_SUBSCRIPT);
662 RECORD(EXPR_BINARY_OPERATOR);
663 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
664 RECORD(EXPR_CONDITIONAL_OPERATOR);
665 RECORD(EXPR_IMPLICIT_CAST);
666 RECORD(EXPR_CSTYLE_CAST);
667 RECORD(EXPR_COMPOUND_LITERAL);
668 RECORD(EXPR_EXT_VECTOR_ELEMENT);
669 RECORD(EXPR_INIT_LIST);
670 RECORD(EXPR_DESIGNATED_INIT);
671 RECORD(EXPR_IMPLICIT_VALUE_INIT);
673 RECORD(EXPR_ADDR_LABEL);
676 RECORD(EXPR_GNU_NULL);
677 RECORD(EXPR_SHUFFLE_VECTOR);
679 RECORD(EXPR_BLOCK_DECL_REF);
680 RECORD(EXPR_GENERIC_SELECTION);
681 RECORD(EXPR_OBJC_STRING_LITERAL);
682 RECORD(EXPR_OBJC_ENCODE);
683 RECORD(EXPR_OBJC_SELECTOR_EXPR);
684 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
685 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
686 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
687 RECORD(EXPR_OBJC_KVC_REF_EXPR);
688 RECORD(EXPR_OBJC_MESSAGE_EXPR);
689 RECORD(STMT_OBJC_FOR_COLLECTION);
690 RECORD(STMT_OBJC_CATCH);
691 RECORD(STMT_OBJC_FINALLY);
692 RECORD(STMT_OBJC_AT_TRY);
693 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
694 RECORD(STMT_OBJC_AT_THROW);
695 RECORD(EXPR_CXX_OPERATOR_CALL);
696 RECORD(EXPR_CXX_CONSTRUCT);
697 RECORD(EXPR_CXX_STATIC_CAST);
698 RECORD(EXPR_CXX_DYNAMIC_CAST);
699 RECORD(EXPR_CXX_REINTERPRET_CAST);
700 RECORD(EXPR_CXX_CONST_CAST);
701 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
702 RECORD(EXPR_CXX_BOOL_LITERAL);
703 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
704 RECORD(EXPR_CXX_TYPEID_EXPR);
705 RECORD(EXPR_CXX_TYPEID_TYPE);
706 RECORD(EXPR_CXX_UUIDOF_EXPR);
707 RECORD(EXPR_CXX_UUIDOF_TYPE);
708 RECORD(EXPR_CXX_THIS);
709 RECORD(EXPR_CXX_THROW);
710 RECORD(EXPR_CXX_DEFAULT_ARG);
711 RECORD(EXPR_CXX_BIND_TEMPORARY);
712 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
713 RECORD(EXPR_CXX_NEW);
714 RECORD(EXPR_CXX_DELETE);
715 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
716 RECORD(EXPR_EXPR_WITH_CLEANUPS);
717 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
718 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
719 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
720 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
721 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
722 RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
723 RECORD(EXPR_CXX_NOEXCEPT);
724 RECORD(EXPR_OPAQUE_VALUE);
725 RECORD(EXPR_BINARY_TYPE_TRAIT);
726 RECORD(EXPR_PACK_EXPANSION);
727 RECORD(EXPR_SIZEOF_PACK);
728 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
729 RECORD(EXPR_CUDA_KERNEL_CALL);
733 void ASTWriter::WriteBlockInfoBlock() {
735 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
737 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
738 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
740 // AST Top-Level Block.
742 RECORD(ORIGINAL_FILE_NAME);
743 RECORD(ORIGINAL_FILE_ID);
746 RECORD(LANGUAGE_OPTIONS);
748 RECORD(IDENTIFIER_OFFSET);
749 RECORD(IDENTIFIER_TABLE);
750 RECORD(EXTERNAL_DEFINITIONS);
751 RECORD(SPECIAL_TYPES);
753 RECORD(TENTATIVE_DEFINITIONS);
754 RECORD(UNUSED_FILESCOPED_DECLS);
755 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
756 RECORD(SELECTOR_OFFSETS);
758 RECORD(PP_COUNTER_VALUE);
759 RECORD(SOURCE_LOCATION_OFFSETS);
760 RECORD(SOURCE_LOCATION_PRELOADS);
762 RECORD(EXT_VECTOR_DECLS);
763 RECORD(VERSION_CONTROL_BRANCH_REVISION);
764 RECORD(MACRO_DEFINITION_OFFSETS);
765 RECORD(CHAINED_METADATA);
766 RECORD(REFERENCED_SELECTOR_POOL);
767 RECORD(TU_UPDATE_LEXICAL);
768 RECORD(REDECLS_UPDATE_LATEST);
769 RECORD(SEMA_DECL_REFS);
770 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
771 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
772 RECORD(DECL_REPLACEMENTS);
773 RECORD(UPDATE_VISIBLE);
774 RECORD(DECL_UPDATE_OFFSETS);
775 RECORD(DECL_UPDATES);
776 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
777 RECORD(DIAG_PRAGMA_MAPPINGS);
778 RECORD(CUDA_SPECIAL_DECL_REFS);
779 RECORD(HEADER_SEARCH_TABLE);
780 RECORD(FP_PRAGMA_OPTIONS);
781 RECORD(OPENCL_EXTENSIONS);
782 RECORD(DELEGATING_CTORS);
784 // SourceManager Block.
785 BLOCK(SOURCE_MANAGER_BLOCK);
786 RECORD(SM_SLOC_FILE_ENTRY);
787 RECORD(SM_SLOC_BUFFER_ENTRY);
788 RECORD(SM_SLOC_BUFFER_BLOB);
789 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
790 RECORD(SM_LINE_TABLE);
792 // Preprocessor Block.
793 BLOCK(PREPROCESSOR_BLOCK);
794 RECORD(PP_MACRO_OBJECT_LIKE);
795 RECORD(PP_MACRO_FUNCTION_LIKE);
798 // Decls and Types block.
799 BLOCK(DECLTYPES_BLOCK);
800 RECORD(TYPE_EXT_QUAL);
801 RECORD(TYPE_COMPLEX);
802 RECORD(TYPE_POINTER);
803 RECORD(TYPE_BLOCK_POINTER);
804 RECORD(TYPE_LVALUE_REFERENCE);
805 RECORD(TYPE_RVALUE_REFERENCE);
806 RECORD(TYPE_MEMBER_POINTER);
807 RECORD(TYPE_CONSTANT_ARRAY);
808 RECORD(TYPE_INCOMPLETE_ARRAY);
809 RECORD(TYPE_VARIABLE_ARRAY);
811 RECORD(TYPE_EXT_VECTOR);
812 RECORD(TYPE_FUNCTION_PROTO);
813 RECORD(TYPE_FUNCTION_NO_PROTO);
814 RECORD(TYPE_TYPEDEF);
815 RECORD(TYPE_TYPEOF_EXPR);
819 RECORD(TYPE_OBJC_INTERFACE);
820 RECORD(TYPE_OBJC_OBJECT);
821 RECORD(TYPE_OBJC_OBJECT_POINTER);
822 RECORD(TYPE_DECLTYPE);
823 RECORD(TYPE_ELABORATED);
824 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
825 RECORD(TYPE_UNRESOLVED_USING);
826 RECORD(TYPE_INJECTED_CLASS_NAME);
827 RECORD(TYPE_OBJC_OBJECT);
828 RECORD(TYPE_TEMPLATE_TYPE_PARM);
829 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
830 RECORD(TYPE_DEPENDENT_NAME);
831 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
832 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
834 RECORD(TYPE_PACK_EXPANSION);
835 RECORD(TYPE_ATTRIBUTED);
836 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
837 RECORD(DECL_TRANSLATION_UNIT);
838 RECORD(DECL_TYPEDEF);
841 RECORD(DECL_ENUM_CONSTANT);
842 RECORD(DECL_FUNCTION);
843 RECORD(DECL_OBJC_METHOD);
844 RECORD(DECL_OBJC_INTERFACE);
845 RECORD(DECL_OBJC_PROTOCOL);
846 RECORD(DECL_OBJC_IVAR);
847 RECORD(DECL_OBJC_AT_DEFS_FIELD);
848 RECORD(DECL_OBJC_CLASS);
849 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
850 RECORD(DECL_OBJC_CATEGORY);
851 RECORD(DECL_OBJC_CATEGORY_IMPL);
852 RECORD(DECL_OBJC_IMPLEMENTATION);
853 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
854 RECORD(DECL_OBJC_PROPERTY);
855 RECORD(DECL_OBJC_PROPERTY_IMPL);
858 RECORD(DECL_IMPLICIT_PARAM);
859 RECORD(DECL_PARM_VAR);
860 RECORD(DECL_FILE_SCOPE_ASM);
862 RECORD(DECL_CONTEXT_LEXICAL);
863 RECORD(DECL_CONTEXT_VISIBLE);
864 RECORD(DECL_NAMESPACE);
865 RECORD(DECL_NAMESPACE_ALIAS);
867 RECORD(DECL_USING_SHADOW);
868 RECORD(DECL_USING_DIRECTIVE);
869 RECORD(DECL_UNRESOLVED_USING_VALUE);
870 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
871 RECORD(DECL_LINKAGE_SPEC);
872 RECORD(DECL_CXX_RECORD);
873 RECORD(DECL_CXX_METHOD);
874 RECORD(DECL_CXX_CONSTRUCTOR);
875 RECORD(DECL_CXX_DESTRUCTOR);
876 RECORD(DECL_CXX_CONVERSION);
877 RECORD(DECL_ACCESS_SPEC);
879 RECORD(DECL_FRIEND_TEMPLATE);
880 RECORD(DECL_CLASS_TEMPLATE);
881 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
882 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
883 RECORD(DECL_FUNCTION_TEMPLATE);
884 RECORD(DECL_TEMPLATE_TYPE_PARM);
885 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
886 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
887 RECORD(DECL_STATIC_ASSERT);
888 RECORD(DECL_CXX_BASE_SPECIFIERS);
889 RECORD(DECL_INDIRECTFIELD);
890 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
892 // Statements and Exprs can occur in the Decls and Types block.
893 AddStmtsExprs(Stream, Record);
895 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
896 RECORD(PPD_MACRO_INSTANTIATION);
897 RECORD(PPD_MACRO_DEFINITION);
898 RECORD(PPD_INCLUSION_DIRECTIVE);
905 /// \brief Adjusts the given filename to only write out the portion of the
906 /// filename that is not part of the system root directory.
908 /// \param Filename the file name to adjust.
910 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
911 /// the returned filename will be adjusted by this system root.
913 /// \returns either the original filename (if it needs no adjustment) or the
914 /// adjusted filename (which points into the @p Filename parameter).
916 adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
917 assert(Filename && "No file name to adjust?");
922 // Verify that the filename and the system root have the same prefix.
924 for (; Filename[Pos] && isysroot[Pos]; ++Pos)
925 if (Filename[Pos] != isysroot[Pos])
926 return Filename; // Prefixes don't match.
928 // We hit the end of the filename before we hit the end of the system root.
932 // If the file name has a '/' at the current position, skip over the '/'.
933 // We distinguish sysroot-based includes from absolute includes by the
934 // absence of '/' at the beginning of sysroot-based includes.
935 if (Filename[Pos] == '/')
938 return Filename + Pos;
941 /// \brief Write the AST metadata (e.g., i686-apple-darwin9).
942 void ASTWriter::WriteMetadata(ASTContext &Context, const char *isysroot,
943 const std::string &OutputFile) {
944 using namespace llvm;
947 const TargetInfo &Target = Context.Target;
948 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
949 MetaAbbrev->Add(BitCodeAbbrevOp(
950 Chain ? CHAINED_METADATA : METADATA));
951 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major
952 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor
953 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
954 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
955 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
956 // Target triple or chained PCH name
957 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
958 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
961 Record.push_back(Chain ? CHAINED_METADATA : METADATA);
962 Record.push_back(VERSION_MAJOR);
963 Record.push_back(VERSION_MINOR);
964 Record.push_back(CLANG_VERSION_MAJOR);
965 Record.push_back(CLANG_VERSION_MINOR);
966 Record.push_back(isysroot != 0);
967 // FIXME: This writes the absolute path for chained headers.
968 const std::string &BlobStr = Chain ? Chain->getFileName() : Target.getTriple().getTriple();
969 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, BlobStr);
971 // Original file name and file ID
972 SourceManager &SM = Context.getSourceManager();
973 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
974 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
975 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME));
976 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
977 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
979 llvm::SmallString<128> MainFilePath(MainFile->getName());
981 llvm::sys::fs::make_absolute(MainFilePath);
983 const char *MainFileNameStr = MainFilePath.c_str();
984 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
987 Record.push_back(ORIGINAL_FILE_NAME);
988 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
991 Record.push_back(SM.getMainFileID().getOpaqueValue());
992 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
995 // Original PCH directory
996 if (!OutputFile.empty() && OutputFile != "-") {
997 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
998 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
999 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1000 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1002 llvm::SmallString<128> OutputPath(OutputFile);
1004 llvm::sys::fs::make_absolute(OutputPath);
1005 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1008 Record.push_back(ORIGINAL_PCH_DIR);
1009 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1012 // Repository branch/version information.
1013 BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev();
1014 RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION));
1015 RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1016 unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev);
1018 Record.push_back(VERSION_CONTROL_BRANCH_REVISION);
1019 Stream.EmitRecordWithBlob(RepoAbbrevCode, Record,
1020 getClangFullRepositoryVersion());
1023 /// \brief Write the LangOptions structure.
1024 void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
1026 Record.push_back(LangOpts.Trigraphs);
1027 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
1028 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
1029 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
1030 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
1031 Record.push_back(LangOpts.GNUKeywords); // Allow GNU-extension keywords
1032 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
1033 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
1034 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
1035 Record.push_back(LangOpts.C99); // C99 Support
1036 Record.push_back(LangOpts.C1X); // C1X Support
1037 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
1038 // LangOpts.MSCVersion is ignored because all it does it set a macro, which is
1039 // already saved elsewhere.
1040 Record.push_back(LangOpts.CPlusPlus); // C++ Support
1041 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
1042 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
1044 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
1045 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
1046 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C
1047 // modern abi enabled.
1048 Record.push_back(LangOpts.ObjCNonFragileABI2); // Objective-C enhanced
1049 // modern abi enabled.
1050 Record.push_back(LangOpts.AppleKext); // Apple's kernel extensions ABI
1051 Record.push_back(LangOpts.ObjCDefaultSynthProperties); // Objective-C auto-synthesized
1052 // properties enabled.
1053 Record.push_back(LangOpts.ObjCInferRelatedResultType);
1054 Record.push_back(LangOpts.NoConstantCFStrings); // non cfstring generation enabled..
1056 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
1057 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
1058 Record.push_back(LangOpts.LaxVectorConversions);
1059 Record.push_back(LangOpts.AltiVec);
1060 Record.push_back(LangOpts.Exceptions); // Support exception handling.
1061 Record.push_back(LangOpts.ObjCExceptions);
1062 Record.push_back(LangOpts.CXXExceptions);
1063 Record.push_back(LangOpts.SjLjExceptions);
1065 Record.push_back(LangOpts.MSBitfields); // MS-compatible structure layout
1066 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
1067 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
1068 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
1070 // Whether static initializers are protected by locks.
1071 Record.push_back(LangOpts.ThreadsafeStatics);
1072 Record.push_back(LangOpts.POSIXThreads);
1073 Record.push_back(LangOpts.Blocks); // block extension to C
1074 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
1076 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
1077 // (modulo the platform support).
1079 Record.push_back(LangOpts.getSignedOverflowBehavior());
1080 Record.push_back(LangOpts.HeinousExtensions);
1082 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
1083 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
1085 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
1086 // opposed to __DYNAMIC__).
1087 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
1089 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
1090 // used (instead of C99 semantics).
1091 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
1092 Record.push_back(LangOpts.Deprecated); // Should __DEPRECATED be defined.
1093 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
1095 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
1097 Record.push_back(LangOpts.ShortWChar); // force wchar_t to be unsigned short
1098 Record.push_back(LangOpts.ShortEnums); // Should the enum type be equivalent
1099 // to the smallest integer type with
1101 Record.push_back(LangOpts.getGCMode());
1102 Record.push_back(LangOpts.getVisibilityMode());
1103 Record.push_back(LangOpts.getStackProtectorMode());
1104 Record.push_back(LangOpts.InstantiationDepth);
1105 Record.push_back(LangOpts.OpenCL);
1106 Record.push_back(LangOpts.CUDA);
1107 Record.push_back(LangOpts.CatchUndefined);
1108 Record.push_back(LangOpts.DefaultFPContract);
1109 Record.push_back(LangOpts.ElideConstructors);
1110 Record.push_back(LangOpts.SpellChecking);
1111 Record.push_back(LangOpts.MRTD);
1112 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1115 //===----------------------------------------------------------------------===//
1116 // stat cache Serialization
1117 //===----------------------------------------------------------------------===//
1120 // Trait used for the on-disk hash table of stat cache results.
1121 class ASTStatCacheTrait {
1123 typedef const char * key_type;
1124 typedef key_type key_type_ref;
1126 typedef struct stat data_type;
1127 typedef const data_type &data_type_ref;
1129 static unsigned ComputeHash(const char *path) {
1130 return llvm::HashString(path);
1133 std::pair<unsigned,unsigned>
1134 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
1135 data_type_ref Data) {
1136 unsigned StrLen = strlen(path);
1137 clang::io::Emit16(Out, StrLen);
1138 unsigned DataLen = 4 + 4 + 2 + 8 + 8;
1139 clang::io::Emit8(Out, DataLen);
1140 return std::make_pair(StrLen + 1, DataLen);
1143 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
1144 Out.write(path, KeyLen);
1147 void EmitData(llvm::raw_ostream &Out, key_type_ref,
1148 data_type_ref Data, unsigned DataLen) {
1149 using namespace clang::io;
1150 uint64_t Start = Out.tell(); (void)Start;
1152 Emit32(Out, (uint32_t) Data.st_ino);
1153 Emit32(Out, (uint32_t) Data.st_dev);
1154 Emit16(Out, (uint16_t) Data.st_mode);
1155 Emit64(Out, (uint64_t) Data.st_mtime);
1156 Emit64(Out, (uint64_t) Data.st_size);
1158 assert(Out.tell() - Start == DataLen && "Wrong data length");
1161 } // end anonymous namespace
1163 /// \brief Write the stat() system call cache to the AST file.
1164 void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
1165 // Build the on-disk hash table containing information about every
1167 OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator;
1168 unsigned NumStatEntries = 0;
1169 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
1170 StatEnd = StatCalls.end();
1171 Stat != StatEnd; ++Stat, ++NumStatEntries) {
1172 const char *Filename = Stat->first();
1173 Generator.insert(Filename, Stat->second);
1176 // Create the on-disk hash table in a buffer.
1177 llvm::SmallString<4096> StatCacheData;
1178 uint32_t BucketOffset;
1180 llvm::raw_svector_ostream Out(StatCacheData);
1181 // Make sure that no bucket is at offset 0
1182 clang::io::Emit32(Out, 0);
1183 BucketOffset = Generator.Emit(Out);
1186 // Create a blob abbreviation
1187 using namespace llvm;
1188 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1189 Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE));
1190 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1191 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1192 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1193 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
1195 // Write the stat cache
1197 Record.push_back(STAT_CACHE);
1198 Record.push_back(BucketOffset);
1199 Record.push_back(NumStatEntries);
1200 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
1203 //===----------------------------------------------------------------------===//
1204 // Source Manager Serialization
1205 //===----------------------------------------------------------------------===//
1207 /// \brief Create an abbreviation for the SLocEntry that refers to a
1209 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1210 using namespace llvm;
1211 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1212 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1213 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1214 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1215 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1216 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1217 // FileEntry fields.
1218 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1219 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1220 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1221 return Stream.EmitAbbrev(Abbrev);
1224 /// \brief Create an abbreviation for the SLocEntry that refers to a
1226 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1227 using namespace llvm;
1228 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1229 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1230 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1231 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1232 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1233 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1234 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1235 return Stream.EmitAbbrev(Abbrev);
1238 /// \brief Create an abbreviation for the SLocEntry that refers to a
1240 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1241 using namespace llvm;
1242 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1243 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1244 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1245 return Stream.EmitAbbrev(Abbrev);
1248 /// \brief Create an abbreviation for the SLocEntry that refers to an
1250 static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
1251 using namespace llvm;
1252 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1253 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_INSTANTIATION_ENTRY));
1254 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1255 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1256 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1257 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1258 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1259 return Stream.EmitAbbrev(Abbrev);
1263 // Trait used for the on-disk hash table of header search information.
1264 class HeaderFileInfoTrait {
1269 HeaderFileInfoTrait(ASTWriter &Writer, HeaderSearch &HS)
1270 : Writer(Writer), HS(HS) { }
1272 typedef const char *key_type;
1273 typedef key_type key_type_ref;
1275 typedef HeaderFileInfo data_type;
1276 typedef const data_type &data_type_ref;
1278 static unsigned ComputeHash(const char *path) {
1279 // The hash is based only on the filename portion of the key, so that the
1280 // reader can match based on filenames when symlinking or excess path
1281 // elements ("foo/../", "../") change the form of the name. However,
1282 // complete path is still the key.
1283 return llvm::HashString(llvm::sys::path::filename(path));
1286 std::pair<unsigned,unsigned>
1287 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
1288 data_type_ref Data) {
1289 unsigned StrLen = strlen(path);
1290 clang::io::Emit16(Out, StrLen);
1291 unsigned DataLen = 1 + 2 + 4;
1292 clang::io::Emit8(Out, DataLen);
1293 return std::make_pair(StrLen + 1, DataLen);
1296 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
1297 Out.write(path, KeyLen);
1300 void EmitData(llvm::raw_ostream &Out, key_type_ref,
1301 data_type_ref Data, unsigned DataLen) {
1302 using namespace clang::io;
1303 uint64_t Start = Out.tell(); (void)Start;
1305 unsigned char Flags = (Data.isImport << 4)
1306 | (Data.isPragmaOnce << 3)
1307 | (Data.DirInfo << 1)
1309 Emit8(Out, (uint8_t)Flags);
1310 Emit16(Out, (uint16_t) Data.NumIncludes);
1312 if (!Data.ControllingMacro)
1313 Emit32(Out, (uint32_t)Data.ControllingMacroID);
1315 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
1316 assert(Out.tell() - Start == DataLen && "Wrong data length");
1319 } // end anonymous namespace
1321 /// \brief Write the header search block for the list of files that
1323 /// \param HS The header search structure to save.
1325 /// \param Chain Whether we're creating a chained AST file.
1326 void ASTWriter::WriteHeaderSearch(HeaderSearch &HS, const char* isysroot) {
1327 llvm::SmallVector<const FileEntry *, 16> FilesByUID;
1328 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1330 if (FilesByUID.size() > HS.header_file_size())
1331 FilesByUID.resize(HS.header_file_size());
1333 HeaderFileInfoTrait GeneratorTrait(*this, HS);
1334 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1335 llvm::SmallVector<const char *, 4> SavedStrings;
1336 unsigned NumHeaderSearchEntries = 0;
1337 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1338 const FileEntry *File = FilesByUID[UID];
1342 const HeaderFileInfo &HFI = HS.header_file_begin()[UID];
1343 if (HFI.External && Chain)
1346 // Turn the file name into an absolute path, if it isn't already.
1347 const char *Filename = File->getName();
1348 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1350 // If we performed any translation on the file name at all, we need to
1351 // save this string, since the generator will refer to it later.
1352 if (Filename != File->getName()) {
1353 Filename = strdup(Filename);
1354 SavedStrings.push_back(Filename);
1357 Generator.insert(Filename, HFI, GeneratorTrait);
1358 ++NumHeaderSearchEntries;
1361 // Create the on-disk hash table in a buffer.
1362 llvm::SmallString<4096> TableData;
1363 uint32_t BucketOffset;
1365 llvm::raw_svector_ostream Out(TableData);
1366 // Make sure that no bucket is at offset 0
1367 clang::io::Emit32(Out, 0);
1368 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1371 // Create a blob abbreviation
1372 using namespace llvm;
1373 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1374 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1375 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1376 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1377 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1378 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1380 // Write the stat cache
1382 Record.push_back(HEADER_SEARCH_TABLE);
1383 Record.push_back(BucketOffset);
1384 Record.push_back(NumHeaderSearchEntries);
1385 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1387 // Free all of the strings we had to duplicate.
1388 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1389 free((void*)SavedStrings[I]);
1392 /// \brief Writes the block containing the serialized form of the
1395 /// TODO: We should probably use an on-disk hash table (stored in a
1396 /// blob), indexed based on the file name, so that we only create
1397 /// entries for files that we actually need. In the common case (no
1398 /// errors), we probably won't have to create file entries for any of
1399 /// the files in the AST.
1400 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1401 const Preprocessor &PP,
1402 const char *isysroot) {
1405 // Enter the source manager block.
1406 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1408 // Abbreviations for the various kinds of source-location entries.
1409 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1410 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1411 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1412 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
1414 // Write the line table.
1415 if (SourceMgr.hasLineTable()) {
1416 LineTableInfo &LineTable = SourceMgr.getLineTable();
1418 // Emit the file names
1419 Record.push_back(LineTable.getNumFilenames());
1420 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1421 // Emit the file name
1422 const char *Filename = LineTable.getFilename(I);
1423 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1424 unsigned FilenameLen = Filename? strlen(Filename) : 0;
1425 Record.push_back(FilenameLen);
1427 Record.insert(Record.end(), Filename, Filename + FilenameLen);
1430 // Emit the line entries
1431 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1434 Record.push_back(L->first);
1436 // Emit the line entries
1437 Record.push_back(L->second.size());
1438 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1439 LEEnd = L->second.end();
1440 LE != LEEnd; ++LE) {
1441 Record.push_back(LE->FileOffset);
1442 Record.push_back(LE->LineNo);
1443 Record.push_back(LE->FilenameID);
1444 Record.push_back((unsigned)LE->FileKind);
1445 Record.push_back(LE->IncludeOffset);
1448 Stream.EmitRecord(SM_LINE_TABLE, Record);
1451 // Write out the source location entry table. We skip the first
1452 // entry, which is always the same dummy entry.
1453 std::vector<uint32_t> SLocEntryOffsets;
1454 // Write out the offsets of only source location file entries.
1455 // We will go through them in ASTReader::validateFileEntries().
1456 std::vector<uint32_t> SLocFileEntryOffsets;
1457 RecordData PreloadSLocs;
1458 unsigned BaseSLocID = Chain ? Chain->getTotalNumSLocs() : 0;
1459 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1 - BaseSLocID);
1460 for (unsigned I = BaseSLocID + 1, N = SourceMgr.sloc_entry_size();
1462 // Get this source location entry.
1463 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getSLocEntry(I);
1465 // Record the offset of this source-location entry.
1466 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1468 // Figure out which record code to use.
1470 if (SLoc->isFile()) {
1471 if (SLoc->getFile().getContentCache()->OrigEntry) {
1472 Code = SM_SLOC_FILE_ENTRY;
1473 SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo());
1475 Code = SM_SLOC_BUFFER_ENTRY;
1477 Code = SM_SLOC_INSTANTIATION_ENTRY;
1479 Record.push_back(Code);
1481 Record.push_back(SLoc->getOffset());
1482 if (SLoc->isFile()) {
1483 const SrcMgr::FileInfo &File = SLoc->getFile();
1484 Record.push_back(File.getIncludeLoc().getRawEncoding());
1485 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1486 Record.push_back(File.hasLineDirectives());
1488 const SrcMgr::ContentCache *Content = File.getContentCache();
1489 if (Content->OrigEntry) {
1490 assert(Content->OrigEntry == Content->ContentsEntry &&
1491 "Writing to AST an overriden file is not supported");
1493 // The source location entry is a file. The blob associated
1494 // with this entry is the file name.
1496 // Emit size/modification time for this file.
1497 Record.push_back(Content->OrigEntry->getSize());
1498 Record.push_back(Content->OrigEntry->getModificationTime());
1500 // Turn the file name into an absolute path, if it isn't already.
1501 const char *Filename = Content->OrigEntry->getName();
1502 llvm::SmallString<128> FilePath(Filename);
1504 // Ask the file manager to fixup the relative path for us. This will
1505 // honor the working directory.
1506 SourceMgr.getFileManager().FixupRelativePath(FilePath);
1508 // FIXME: This call to make_absolute shouldn't be necessary, the
1509 // call to FixupRelativePath should always return an absolute path.
1510 llvm::sys::fs::make_absolute(FilePath);
1511 Filename = FilePath.c_str();
1513 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1514 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
1516 // The source location entry is a buffer. The blob associated
1517 // with this entry contains the contents of the buffer.
1519 // We add one to the size so that we capture the trailing NULL
1520 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1521 // the reader side).
1522 const llvm::MemoryBuffer *Buffer
1523 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1524 const char *Name = Buffer->getBufferIdentifier();
1525 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1526 llvm::StringRef(Name, strlen(Name) + 1));
1528 Record.push_back(SM_SLOC_BUFFER_BLOB);
1529 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1530 llvm::StringRef(Buffer->getBufferStart(),
1531 Buffer->getBufferSize() + 1));
1533 if (strcmp(Name, "<built-in>") == 0)
1534 PreloadSLocs.push_back(BaseSLocID + SLocEntryOffsets.size());
1537 // The source location entry is an instantiation.
1538 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
1539 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
1540 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
1541 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
1543 // Compute the token length for this macro expansion.
1544 unsigned NextOffset = SourceMgr.getNextOffset();
1546 NextOffset = SourceMgr.getSLocEntry(I + 1).getOffset();
1547 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1548 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
1554 if (SLocEntryOffsets.empty())
1557 // Write the source-location offsets table into the AST block. This
1558 // table is used for lazily loading source-location information.
1559 using namespace llvm;
1560 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1561 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1562 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1563 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
1564 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1565 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1568 Record.push_back(SOURCE_LOCATION_OFFSETS);
1569 Record.push_back(SLocEntryOffsets.size());
1570 unsigned BaseOffset = Chain ? Chain->getNextSLocOffset() : 0;
1571 Record.push_back(SourceMgr.getNextOffset() - BaseOffset);
1572 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
1574 Abbrev = new BitCodeAbbrev();
1575 Abbrev->Add(BitCodeAbbrevOp(FILE_SOURCE_LOCATION_OFFSETS));
1576 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1577 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1578 unsigned SLocFileOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1581 Record.push_back(FILE_SOURCE_LOCATION_OFFSETS);
1582 Record.push_back(SLocFileEntryOffsets.size());
1583 Stream.EmitRecordWithBlob(SLocFileOffsetsAbbrev, Record,
1584 data(SLocFileEntryOffsets));
1586 // Write the source location entry preloads array, telling the AST
1587 // reader which source locations entries it should load eagerly.
1588 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1591 //===----------------------------------------------------------------------===//
1592 // Preprocessor Serialization
1593 //===----------------------------------------------------------------------===//
1595 static int compareMacroDefinitions(const void *XPtr, const void *YPtr) {
1596 const std::pair<const IdentifierInfo *, MacroInfo *> &X =
1597 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr;
1598 const std::pair<const IdentifierInfo *, MacroInfo *> &Y =
1599 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr;
1600 return X.first->getName().compare(Y.first->getName());
1603 /// \brief Writes the block containing the serialized form of the
1606 void ASTWriter::WritePreprocessor(const Preprocessor &PP) {
1609 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1610 if (PP.getCounterValue() != 0) {
1611 Record.push_back(PP.getCounterValue());
1612 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1616 // Enter the preprocessor block.
1617 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1619 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1620 // FIXME: use diagnostics subsystem for localization etc.
1621 if (PP.SawDateOrTime())
1622 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1625 // Loop over all the macro definitions that are live at the end of the file,
1626 // emitting each to the PP section.
1627 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1629 // Construct the list of macro definitions that need to be serialized.
1630 llvm::SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2>
1632 llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen;
1633 for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0),
1634 E = PP.macro_end(Chain == 0);
1636 MacroDefinitionsSeen.insert(I->first);
1637 MacrosToEmit.push_back(std::make_pair(I->first, I->second));
1640 // Sort the set of macro definitions that need to be serialized by the
1641 // name of the macro, to provide a stable ordering.
1642 llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(),
1643 &compareMacroDefinitions);
1645 // Resolve any identifiers that defined macros at the time they were
1646 // deserialized, adding them to the list of macros to emit (if appropriate).
1647 for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) {
1648 IdentifierInfo *Name
1649 = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]);
1650 if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name))
1651 MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name)));
1654 for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) {
1655 const IdentifierInfo *Name = MacrosToEmit[I].first;
1656 MacroInfo *MI = MacrosToEmit[I].second;
1660 // Don't emit builtin macros like __LINE__ to the AST file unless they have
1661 // been redefined by the header (in which case they are not isBuiltinMacro).
1662 // Also skip macros from a AST file if we're chaining.
1664 // FIXME: There is a (probably minor) optimization we could do here, if
1665 // the macro comes from the original PCH but the identifier comes from a
1666 // chained PCH, by storing the offset into the original PCH rather than
1667 // writing the macro definition a second time.
1668 if (MI->isBuiltinMacro() ||
1669 (Chain && Name->isFromAST() && MI->isFromAST()))
1672 AddIdentifierRef(Name, Record);
1673 MacroOffsets[Name] = Stream.GetCurrentBitNo();
1674 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1675 Record.push_back(MI->isUsed());
1678 if (MI->isObjectLike()) {
1679 Code = PP_MACRO_OBJECT_LIKE;
1681 Code = PP_MACRO_FUNCTION_LIKE;
1683 Record.push_back(MI->isC99Varargs());
1684 Record.push_back(MI->isGNUVarargs());
1685 Record.push_back(MI->getNumArgs());
1686 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1688 AddIdentifierRef(*I, Record);
1691 // If we have a detailed preprocessing record, record the macro definition
1692 // ID that corresponds to this macro.
1694 Record.push_back(getMacroDefinitionID(PPRec->findMacroDefinition(MI)));
1696 Stream.EmitRecord(Code, Record);
1699 // Emit the tokens array.
1700 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1701 // Note that we know that the preprocessor does not have any annotation
1702 // tokens in it because they are created by the parser, and thus can't be
1703 // in a macro definition.
1704 const Token &Tok = MI->getReplacementToken(TokNo);
1706 Record.push_back(Tok.getLocation().getRawEncoding());
1707 Record.push_back(Tok.getLength());
1709 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1711 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
1712 // FIXME: Should translate token kind to a stable encoding.
1713 Record.push_back(Tok.getKind());
1714 // FIXME: Should translate token flags to a stable encoding.
1715 Record.push_back(Tok.getFlags());
1717 Stream.EmitRecord(PP_TOKEN, Record);
1725 WritePreprocessorDetail(*PPRec);
1728 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
1729 if (PPRec.begin(Chain) == PPRec.end(Chain))
1732 // Enter the preprocessor block.
1733 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
1735 // If the preprocessor has a preprocessing record, emit it.
1736 unsigned NumPreprocessingRecords = 0;
1737 using namespace llvm;
1739 // Set up the abbreviation for
1740 unsigned InclusionAbbrev = 0;
1742 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1743 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
1744 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1745 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // start location
1746 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // end location
1747 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
1748 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
1749 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
1750 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1751 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
1754 unsigned IndexBase = Chain ? PPRec.getNumPreallocatedEntities() : 0;
1756 for (PreprocessingRecord::iterator E = PPRec.begin(Chain),
1757 EEnd = PPRec.end(Chain);
1761 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
1762 // Record this macro definition's location.
1763 MacroID ID = getMacroDefinitionID(MD);
1765 // Don't write the macro definition if it is from another AST file.
1766 if (ID < FirstMacroID)
1769 // Notify the serialization listener that we're serializing this entity.
1770 if (SerializationListener)
1771 SerializationListener->SerializedPreprocessedEntity(*E,
1772 Stream.GetCurrentBitNo());
1774 unsigned Position = ID - FirstMacroID;
1775 if (Position != MacroDefinitionOffsets.size()) {
1776 if (Position > MacroDefinitionOffsets.size())
1777 MacroDefinitionOffsets.resize(Position + 1);
1779 MacroDefinitionOffsets[Position] = Stream.GetCurrentBitNo();
1781 MacroDefinitionOffsets.push_back(Stream.GetCurrentBitNo());
1783 Record.push_back(IndexBase + NumPreprocessingRecords++);
1784 Record.push_back(ID);
1785 AddSourceLocation(MD->getSourceRange().getBegin(), Record);
1786 AddSourceLocation(MD->getSourceRange().getEnd(), Record);
1787 AddIdentifierRef(MD->getName(), Record);
1788 AddSourceLocation(MD->getLocation(), Record);
1789 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
1793 // Notify the serialization listener that we're serializing this entity.
1794 if (SerializationListener)
1795 SerializationListener->SerializedPreprocessedEntity(*E,
1796 Stream.GetCurrentBitNo());
1798 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
1799 Record.push_back(IndexBase + NumPreprocessingRecords++);
1800 AddSourceLocation(MI->getSourceRange().getBegin(), Record);
1801 AddSourceLocation(MI->getSourceRange().getEnd(), Record);
1802 AddIdentifierRef(MI->getName(), Record);
1803 Record.push_back(getMacroDefinitionID(MI->getDefinition()));
1804 Stream.EmitRecord(PPD_MACRO_INSTANTIATION, Record);
1808 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
1809 Record.push_back(PPD_INCLUSION_DIRECTIVE);
1810 Record.push_back(IndexBase + NumPreprocessingRecords++);
1811 AddSourceLocation(ID->getSourceRange().getBegin(), Record);
1812 AddSourceLocation(ID->getSourceRange().getEnd(), Record);
1813 Record.push_back(ID->getFileName().size());
1814 Record.push_back(ID->wasInQuotes());
1815 Record.push_back(static_cast<unsigned>(ID->getKind()));
1816 llvm::SmallString<64> Buffer;
1817 Buffer += ID->getFileName();
1818 Buffer += ID->getFile()->getName();
1819 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
1823 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
1827 // Write the offsets table for the preprocessing record.
1828 if (NumPreprocessingRecords > 0) {
1829 // Write the offsets table for identifier IDs.
1830 using namespace llvm;
1831 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1832 Abbrev->Add(BitCodeAbbrevOp(MACRO_DEFINITION_OFFSETS));
1833 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of records
1834 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macro defs
1835 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1836 unsigned MacroDefOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1839 Record.push_back(MACRO_DEFINITION_OFFSETS);
1840 Record.push_back(NumPreprocessingRecords);
1841 Record.push_back(MacroDefinitionOffsets.size());
1842 Stream.EmitRecordWithBlob(MacroDefOffsetAbbrev, Record,
1843 data(MacroDefinitionOffsets));
1847 void ASTWriter::WritePragmaDiagnosticMappings(const Diagnostic &Diag) {
1849 for (Diagnostic::DiagStatePointsTy::const_iterator
1850 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
1852 const Diagnostic::DiagStatePoint &point = *I;
1853 if (point.Loc.isInvalid())
1856 Record.push_back(point.Loc.getRawEncoding());
1857 for (Diagnostic::DiagState::iterator
1858 I = point.State->begin(), E = point.State->end(); I != E; ++I) {
1859 unsigned diag = I->first, map = I->second;
1860 if (map & 0x10) { // mapping from a diagnostic pragma.
1861 Record.push_back(diag);
1862 Record.push_back(map & 0x7);
1865 Record.push_back(-1); // mark the end of the diag/map pairs for this
1869 if (!Record.empty())
1870 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
1873 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
1874 if (CXXBaseSpecifiersOffsets.empty())
1879 // Create a blob abbreviation for the C++ base specifiers offsets.
1880 using namespace llvm;
1882 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1883 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
1884 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
1885 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1886 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1888 // Write the selector offsets table.
1890 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
1891 Record.push_back(CXXBaseSpecifiersOffsets.size());
1892 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
1893 data(CXXBaseSpecifiersOffsets));
1896 //===----------------------------------------------------------------------===//
1897 // Type Serialization
1898 //===----------------------------------------------------------------------===//
1900 /// \brief Write the representation of a type to the AST stream.
1901 void ASTWriter::WriteType(QualType T) {
1902 TypeIdx &Idx = TypeIdxs[T];
1903 if (Idx.getIndex() == 0) // we haven't seen this type before.
1904 Idx = TypeIdx(NextTypeID++);
1906 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
1908 // Record the offset for this type.
1909 unsigned Index = Idx.getIndex() - FirstTypeID;
1910 if (TypeOffsets.size() == Index)
1911 TypeOffsets.push_back(Stream.GetCurrentBitNo());
1912 else if (TypeOffsets.size() < Index) {
1913 TypeOffsets.resize(Index + 1);
1914 TypeOffsets[Index] = Stream.GetCurrentBitNo();
1919 // Emit the type's representation.
1920 ASTTypeWriter W(*this, Record);
1922 if (T.hasLocalNonFastQualifiers()) {
1923 Qualifiers Qs = T.getLocalQualifiers();
1924 AddTypeRef(T.getLocalUnqualifiedType(), Record);
1925 Record.push_back(Qs.getAsOpaqueValue());
1926 W.Code = TYPE_EXT_QUAL;
1928 switch (T->getTypeClass()) {
1929 // For all of the concrete, non-dependent types, call the
1930 // appropriate visitor function.
1931 #define TYPE(Class, Base) \
1932 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1933 #define ABSTRACT_TYPE(Class, Base)
1934 #include "clang/AST/TypeNodes.def"
1938 // Emit the serialized record.
1939 Stream.EmitRecord(W.Code, Record);
1941 // Flush any expressions that were written as part of this type.
1945 //===----------------------------------------------------------------------===//
1946 // Declaration Serialization
1947 //===----------------------------------------------------------------------===//
1949 /// \brief Write the block containing all of the declaration IDs
1950 /// lexically declared within the given DeclContext.
1952 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1953 /// bistream, or 0 if no block was written.
1954 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1956 if (DC->decls_empty())
1959 uint64_t Offset = Stream.GetCurrentBitNo();
1961 Record.push_back(DECL_CONTEXT_LEXICAL);
1962 llvm::SmallVector<KindDeclIDPair, 64> Decls;
1963 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1965 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
1967 ++NumLexicalDeclContexts;
1968 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
1972 void ASTWriter::WriteTypeDeclOffsets() {
1973 using namespace llvm;
1976 // Write the type offsets array
1977 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1978 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
1979 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1980 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1981 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1983 Record.push_back(TYPE_OFFSET);
1984 Record.push_back(TypeOffsets.size());
1985 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
1987 // Write the declaration offsets array
1988 Abbrev = new BitCodeAbbrev();
1989 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
1990 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1991 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1992 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1994 Record.push_back(DECL_OFFSET);
1995 Record.push_back(DeclOffsets.size());
1996 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
1999 //===----------------------------------------------------------------------===//
2000 // Global Method Pool and Selector Serialization
2001 //===----------------------------------------------------------------------===//
2004 // Trait used for the on-disk hash table used in the method pool.
2005 class ASTMethodPoolTrait {
2009 typedef Selector key_type;
2010 typedef key_type key_type_ref;
2014 ObjCMethodList Instance, Factory;
2016 typedef const data_type& data_type_ref;
2018 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2020 static unsigned ComputeHash(Selector Sel) {
2021 return serialization::ComputeHash(Sel);
2024 std::pair<unsigned,unsigned>
2025 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
2026 data_type_ref Methods) {
2027 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2028 clang::io::Emit16(Out, KeyLen);
2029 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2030 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2031 Method = Method->Next)
2034 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2035 Method = Method->Next)
2038 clang::io::Emit16(Out, DataLen);
2039 return std::make_pair(KeyLen, DataLen);
2042 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
2043 uint64_t Start = Out.tell();
2044 assert((Start >> 32) == 0 && "Selector key offset too large");
2045 Writer.SetSelectorOffset(Sel, Start);
2046 unsigned N = Sel.getNumArgs();
2047 clang::io::Emit16(Out, N);
2050 for (unsigned I = 0; I != N; ++I)
2051 clang::io::Emit32(Out,
2052 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2055 void EmitData(llvm::raw_ostream& Out, key_type_ref,
2056 data_type_ref Methods, unsigned DataLen) {
2057 uint64_t Start = Out.tell(); (void)Start;
2058 clang::io::Emit32(Out, Methods.ID);
2059 unsigned NumInstanceMethods = 0;
2060 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2061 Method = Method->Next)
2063 ++NumInstanceMethods;
2065 unsigned NumFactoryMethods = 0;
2066 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2067 Method = Method->Next)
2069 ++NumFactoryMethods;
2071 clang::io::Emit16(Out, NumInstanceMethods);
2072 clang::io::Emit16(Out, NumFactoryMethods);
2073 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2074 Method = Method->Next)
2076 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2077 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2078 Method = Method->Next)
2080 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2082 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2085 } // end anonymous namespace
2087 /// \brief Write ObjC data: selectors and the method pool.
2089 /// The method pool contains both instance and factory methods, stored
2090 /// in an on-disk hash table indexed by the selector. The hash table also
2091 /// contains an empty entry for every other selector known to Sema.
2092 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2093 using namespace llvm;
2095 // Do we have to do anything at all?
2096 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2098 unsigned NumTableEntries = 0;
2099 // Create and write out the blob that contains selectors and the method pool.
2101 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2102 ASTMethodPoolTrait Trait(*this);
2104 // Create the on-disk hash table representation. We walk through every
2105 // selector we've seen and look it up in the method pool.
2106 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2107 for (llvm::DenseMap<Selector, SelectorID>::iterator
2108 I = SelectorIDs.begin(), E = SelectorIDs.end();
2110 Selector S = I->first;
2111 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2112 ASTMethodPoolTrait::data_type Data = {
2117 if (F != SemaRef.MethodPool.end()) {
2118 Data.Instance = F->second.first;
2119 Data.Factory = F->second.second;
2121 // Only write this selector if it's not in an existing AST or something
2123 if (Chain && I->second < FirstSelectorID) {
2124 // Selector already exists. Did it change?
2125 bool changed = false;
2126 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
2128 if (M->Method->getPCHLevel() == 0)
2131 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
2133 if (M->Method->getPCHLevel() == 0)
2138 } else if (Data.Instance.Method || Data.Factory.Method) {
2139 // A new method pool entry.
2142 Generator.insert(S, Data, Trait);
2145 // Create the on-disk hash table in a buffer.
2146 llvm::SmallString<4096> MethodPool;
2147 uint32_t BucketOffset;
2149 ASTMethodPoolTrait Trait(*this);
2150 llvm::raw_svector_ostream Out(MethodPool);
2151 // Make sure that no bucket is at offset 0
2152 clang::io::Emit32(Out, 0);
2153 BucketOffset = Generator.Emit(Out, Trait);
2156 // Create a blob abbreviation
2157 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2158 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
2159 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2160 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2161 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2162 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
2164 // Write the method pool
2166 Record.push_back(METHOD_POOL);
2167 Record.push_back(BucketOffset);
2168 Record.push_back(NumTableEntries);
2169 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
2171 // Create a blob abbreviation for the selector table offsets.
2172 Abbrev = new BitCodeAbbrev();
2173 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
2174 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2175 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2176 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2178 // Write the selector offsets table.
2180 Record.push_back(SELECTOR_OFFSETS);
2181 Record.push_back(SelectorOffsets.size());
2182 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
2183 data(SelectorOffsets));
2187 /// \brief Write the selectors referenced in @selector expression into AST file.
2188 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
2189 using namespace llvm;
2190 if (SemaRef.ReferencedSelectors.empty())
2195 // Note: this writes out all references even for a dependent AST. But it is
2196 // very tricky to fix, and given that @selector shouldn't really appear in
2197 // headers, probably not worth it. It's not a correctness issue.
2198 for (DenseMap<Selector, SourceLocation>::iterator S =
2199 SemaRef.ReferencedSelectors.begin(),
2200 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
2201 Selector Sel = (*S).first;
2202 SourceLocation Loc = (*S).second;
2203 AddSelectorRef(Sel, Record);
2204 AddSourceLocation(Loc, Record);
2206 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
2209 //===----------------------------------------------------------------------===//
2210 // Identifier Table Serialization
2211 //===----------------------------------------------------------------------===//
2214 class ASTIdentifierTableTrait {
2218 /// \brief Determines whether this is an "interesting" identifier
2219 /// that needs a full IdentifierInfo structure written into the hash
2221 static bool isInterestingIdentifier(const IdentifierInfo *II) {
2222 return II->isPoisoned() ||
2223 II->isExtensionToken() ||
2224 II->hasMacroDefinition() ||
2225 II->getObjCOrBuiltinID() ||
2226 II->getFETokenInfo<void>();
2230 typedef const IdentifierInfo* key_type;
2231 typedef key_type key_type_ref;
2233 typedef IdentID data_type;
2234 typedef data_type data_type_ref;
2236 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP)
2237 : Writer(Writer), PP(PP) { }
2239 static unsigned ComputeHash(const IdentifierInfo* II) {
2240 return llvm::HashString(II->getName());
2243 std::pair<unsigned,unsigned>
2244 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
2246 unsigned KeyLen = II->getLength() + 1;
2247 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
2248 if (isInterestingIdentifier(II)) {
2249 DataLen += 2; // 2 bytes for builtin ID, flags
2250 if (II->hasMacroDefinition() &&
2251 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
2253 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
2254 DEnd = IdentifierResolver::end();
2256 DataLen += sizeof(DeclID);
2258 clang::io::Emit16(Out, DataLen);
2259 // We emit the key length after the data length so that every
2260 // string is preceded by a 16-bit length. This matches the PTH
2261 // format for storing identifiers.
2262 clang::io::Emit16(Out, KeyLen);
2263 return std::make_pair(KeyLen, DataLen);
2266 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
2268 // Record the location of the key data. This is used when generating
2269 // the mapping from persistent IDs to strings.
2270 Writer.SetIdentifierOffset(II, Out.tell());
2271 Out.write(II->getNameStart(), KeyLen);
2274 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
2275 IdentID ID, unsigned) {
2276 if (!isInterestingIdentifier(II)) {
2277 clang::io::Emit32(Out, ID << 1);
2281 clang::io::Emit32(Out, (ID << 1) | 0x01);
2283 bool hasMacroDefinition =
2284 II->hasMacroDefinition() &&
2285 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
2286 Bits = (uint32_t)II->getObjCOrBuiltinID();
2287 Bits = (Bits << 1) | unsigned(hasMacroDefinition);
2288 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
2289 Bits = (Bits << 1) | unsigned(II->isPoisoned());
2290 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
2291 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
2292 clang::io::Emit16(Out, Bits);
2294 if (hasMacroDefinition)
2295 clang::io::Emit32(Out, Writer.getMacroOffset(II));
2297 // Emit the declaration IDs in reverse order, because the
2298 // IdentifierResolver provides the declarations as they would be
2299 // visible (e.g., the function "stat" would come before the struct
2300 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
2301 // adds declarations to the end of the list (so we need to see the
2302 // struct "status" before the function "status").
2303 // Only emit declarations that aren't from a chained PCH, though.
2304 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
2305 IdentifierResolver::end());
2306 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
2307 DEnd = Decls.rend();
2309 clang::io::Emit32(Out, Writer.getDeclID(*D));
2312 } // end anonymous namespace
2314 /// \brief Write the identifier table into the AST file.
2316 /// The identifier table consists of a blob containing string data
2317 /// (the actual identifiers themselves) and a separate "offsets" index
2318 /// that maps identifier IDs to locations within the blob.
2319 void ASTWriter::WriteIdentifierTable(Preprocessor &PP) {
2320 using namespace llvm;
2322 // Create and write out the blob that contains the identifier
2325 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
2326 ASTIdentifierTableTrait Trait(*this, PP);
2328 // Look for any identifiers that were named while processing the
2329 // headers, but are otherwise not needed. We add these to the hash
2330 // table to enable checking of the predefines buffer in the case
2331 // where the user adds new macro definitions when building the AST
2333 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
2334 IDEnd = PP.getIdentifierTable().end();
2336 getIdentifierRef(ID->second);
2338 // Create the on-disk hash table representation. We only store offsets
2339 // for identifiers that appear here for the first time.
2340 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
2341 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
2342 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
2343 ID != IDEnd; ++ID) {
2344 assert(ID->first && "NULL identifier in identifier table");
2345 if (!Chain || !ID->first->isFromAST())
2346 Generator.insert(ID->first, ID->second, Trait);
2349 // Create the on-disk hash table in a buffer.
2350 llvm::SmallString<4096> IdentifierTable;
2351 uint32_t BucketOffset;
2353 ASTIdentifierTableTrait Trait(*this, PP);
2354 llvm::raw_svector_ostream Out(IdentifierTable);
2355 // Make sure that no bucket is at offset 0
2356 clang::io::Emit32(Out, 0);
2357 BucketOffset = Generator.Emit(Out, Trait);
2360 // Create a blob abbreviation
2361 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2362 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
2363 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2364 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2365 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
2367 // Write the identifier table
2369 Record.push_back(IDENTIFIER_TABLE);
2370 Record.push_back(BucketOffset);
2371 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
2374 // Write the offsets table for identifier IDs.
2375 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2376 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
2377 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
2378 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2379 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2382 Record.push_back(IDENTIFIER_OFFSET);
2383 Record.push_back(IdentifierOffsets.size());
2384 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
2385 data(IdentifierOffsets));
2388 //===----------------------------------------------------------------------===//
2389 // DeclContext's Name Lookup Table Serialization
2390 //===----------------------------------------------------------------------===//
2393 // Trait used for the on-disk hash table used in the method pool.
2394 class ASTDeclContextNameLookupTrait {
2398 typedef DeclarationName key_type;
2399 typedef key_type key_type_ref;
2401 typedef DeclContext::lookup_result data_type;
2402 typedef const data_type& data_type_ref;
2404 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
2406 unsigned ComputeHash(DeclarationName Name) {
2407 llvm::FoldingSetNodeID ID;
2408 ID.AddInteger(Name.getNameKind());
2410 switch (Name.getNameKind()) {
2411 case DeclarationName::Identifier:
2412 ID.AddString(Name.getAsIdentifierInfo()->getName());
2414 case DeclarationName::ObjCZeroArgSelector:
2415 case DeclarationName::ObjCOneArgSelector:
2416 case DeclarationName::ObjCMultiArgSelector:
2417 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
2419 case DeclarationName::CXXConstructorName:
2420 case DeclarationName::CXXDestructorName:
2421 case DeclarationName::CXXConversionFunctionName:
2422 ID.AddInteger(Writer.GetOrCreateTypeID(Name.getCXXNameType()));
2424 case DeclarationName::CXXOperatorName:
2425 ID.AddInteger(Name.getCXXOverloadedOperator());
2427 case DeclarationName::CXXLiteralOperatorName:
2428 ID.AddString(Name.getCXXLiteralIdentifier()->getName());
2429 case DeclarationName::CXXUsingDirective:
2433 return ID.ComputeHash();
2436 std::pair<unsigned,unsigned>
2437 EmitKeyDataLength(llvm::raw_ostream& Out, DeclarationName Name,
2438 data_type_ref Lookup) {
2439 unsigned KeyLen = 1;
2440 switch (Name.getNameKind()) {
2441 case DeclarationName::Identifier:
2442 case DeclarationName::ObjCZeroArgSelector:
2443 case DeclarationName::ObjCOneArgSelector:
2444 case DeclarationName::ObjCMultiArgSelector:
2445 case DeclarationName::CXXConstructorName:
2446 case DeclarationName::CXXDestructorName:
2447 case DeclarationName::CXXConversionFunctionName:
2448 case DeclarationName::CXXLiteralOperatorName:
2451 case DeclarationName::CXXOperatorName:
2454 case DeclarationName::CXXUsingDirective:
2457 clang::io::Emit16(Out, KeyLen);
2459 // 2 bytes for num of decls and 4 for each DeclID.
2460 unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first);
2461 clang::io::Emit16(Out, DataLen);
2463 return std::make_pair(KeyLen, DataLen);
2466 void EmitKey(llvm::raw_ostream& Out, DeclarationName Name, unsigned) {
2467 using namespace clang::io;
2469 assert(Name.getNameKind() < 0x100 && "Invalid name kind ?");
2470 Emit8(Out, Name.getNameKind());
2471 switch (Name.getNameKind()) {
2472 case DeclarationName::Identifier:
2473 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
2475 case DeclarationName::ObjCZeroArgSelector:
2476 case DeclarationName::ObjCOneArgSelector:
2477 case DeclarationName::ObjCMultiArgSelector:
2478 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
2480 case DeclarationName::CXXConstructorName:
2481 case DeclarationName::CXXDestructorName:
2482 case DeclarationName::CXXConversionFunctionName:
2483 Emit32(Out, Writer.getTypeID(Name.getCXXNameType()));
2485 case DeclarationName::CXXOperatorName:
2486 assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?");
2487 Emit8(Out, Name.getCXXOverloadedOperator());
2489 case DeclarationName::CXXLiteralOperatorName:
2490 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
2492 case DeclarationName::CXXUsingDirective:
2497 void EmitData(llvm::raw_ostream& Out, key_type_ref,
2498 data_type Lookup, unsigned DataLen) {
2499 uint64_t Start = Out.tell(); (void)Start;
2500 clang::io::Emit16(Out, Lookup.second - Lookup.first);
2501 for (; Lookup.first != Lookup.second; ++Lookup.first)
2502 clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first));
2504 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2507 } // end anonymous namespace
2509 /// \brief Write the block containing all of the declaration IDs
2510 /// visible from the given DeclContext.
2512 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
2513 /// bitstream, or 0 if no block was written.
2514 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
2516 if (DC->getPrimaryContext() != DC)
2519 // Since there is no name lookup into functions or methods, don't bother to
2520 // build a visible-declarations table for these entities.
2521 if (DC->isFunctionOrMethod())
2524 // If not in C++, we perform name lookup for the translation unit via the
2525 // IdentifierInfo chains, don't bother to build a visible-declarations table.
2526 // FIXME: In C++ we need the visible declarations in order to "see" the
2527 // friend declarations, is there a way to do this without writing the table ?
2528 if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus)
2531 // Force the DeclContext to build a its name-lookup table.
2532 if (DC->hasExternalVisibleStorage())
2533 DC->MaterializeVisibleDeclsFromExternalStorage();
2535 DC->lookup(DeclarationName());
2537 // Serialize the contents of the mapping used for lookup. Note that,
2538 // although we have two very different code paths, the serialized
2539 // representation is the same for both cases: a declaration name,
2540 // followed by a size, followed by references to the visible
2541 // declarations that have that name.
2542 uint64_t Offset = Stream.GetCurrentBitNo();
2543 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2544 if (!Map || Map->empty())
2547 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2548 ASTDeclContextNameLookupTrait Trait(*this);
2550 // Create the on-disk hash table representation.
2551 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2553 DeclarationName Name = D->first;
2554 DeclContext::lookup_result Result = D->second.getLookupResult();
2555 Generator.insert(Name, Result, Trait);
2558 // Create the on-disk hash table in a buffer.
2559 llvm::SmallString<4096> LookupTable;
2560 uint32_t BucketOffset;
2562 llvm::raw_svector_ostream Out(LookupTable);
2563 // Make sure that no bucket is at offset 0
2564 clang::io::Emit32(Out, 0);
2565 BucketOffset = Generator.Emit(Out, Trait);
2568 // Write the lookup table
2570 Record.push_back(DECL_CONTEXT_VISIBLE);
2571 Record.push_back(BucketOffset);
2572 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
2575 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
2576 ++NumVisibleDeclContexts;
2580 /// \brief Write an UPDATE_VISIBLE block for the given context.
2582 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
2583 /// DeclContext in a dependent AST file. As such, they only exist for the TU
2584 /// (in C++) and for namespaces.
2585 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
2586 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2587 if (!Map || Map->empty())
2590 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2591 ASTDeclContextNameLookupTrait Trait(*this);
2593 // Create the hash table.
2594 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2596 DeclarationName Name = D->first;
2597 DeclContext::lookup_result Result = D->second.getLookupResult();
2598 // For any name that appears in this table, the results are complete, i.e.
2599 // they overwrite results from previous PCHs. Merging is always a mess.
2600 Generator.insert(Name, Result, Trait);
2603 // Create the on-disk hash table in a buffer.
2604 llvm::SmallString<4096> LookupTable;
2605 uint32_t BucketOffset;
2607 llvm::raw_svector_ostream Out(LookupTable);
2608 // Make sure that no bucket is at offset 0
2609 clang::io::Emit32(Out, 0);
2610 BucketOffset = Generator.Emit(Out, Trait);
2613 // Write the lookup table
2615 Record.push_back(UPDATE_VISIBLE);
2616 Record.push_back(getDeclID(cast<Decl>(DC)));
2617 Record.push_back(BucketOffset);
2618 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
2621 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
2622 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
2624 Record.push_back(Opts.fp_contract);
2625 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
2628 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
2629 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
2630 if (!SemaRef.Context.getLangOptions().OpenCL)
2633 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
2635 #define OPENCLEXT(nm) Record.push_back(Opts.nm);
2636 #include "clang/Basic/OpenCLExtensions.def"
2637 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
2640 //===----------------------------------------------------------------------===//
2641 // General Serialization Routines
2642 //===----------------------------------------------------------------------===//
2644 /// \brief Write a record containing the given attributes.
2645 void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) {
2646 Record.push_back(Attrs.size());
2647 for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){
2648 const Attr * A = *i;
2649 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
2650 AddSourceLocation(A->getLocation(), Record);
2652 #include "clang/Serialization/AttrPCHWrite.inc"
2657 void ASTWriter::AddString(llvm::StringRef Str, RecordDataImpl &Record) {
2658 Record.push_back(Str.size());
2659 Record.insert(Record.end(), Str.begin(), Str.end());
2662 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
2663 RecordDataImpl &Record) {
2664 Record.push_back(Version.getMajor());
2665 if (llvm::Optional<unsigned> Minor = Version.getMinor())
2666 Record.push_back(*Minor + 1);
2668 Record.push_back(0);
2669 if (llvm::Optional<unsigned> Subminor = Version.getSubminor())
2670 Record.push_back(*Subminor + 1);
2672 Record.push_back(0);
2675 /// \brief Note that the identifier II occurs at the given offset
2676 /// within the identifier table.
2677 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
2678 IdentID ID = IdentifierIDs[II];
2679 // Only store offsets new to this AST file. Other identifier names are looked
2680 // up earlier in the chain and thus don't need an offset.
2681 if (ID >= FirstIdentID)
2682 IdentifierOffsets[ID - FirstIdentID] = Offset;
2685 /// \brief Note that the selector Sel occurs at the given offset
2686 /// within the method pool/selector table.
2687 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
2688 unsigned ID = SelectorIDs[Sel];
2689 assert(ID && "Unknown selector");
2690 // Don't record offsets for selectors that are also available in a different
2692 if (ID < FirstSelectorID)
2694 SelectorOffsets[ID - FirstSelectorID] = Offset;
2697 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
2698 : Stream(Stream), Chain(0), SerializationListener(0),
2699 FirstDeclID(1), NextDeclID(FirstDeclID),
2700 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
2701 FirstIdentID(1), NextIdentID(FirstIdentID), FirstSelectorID(1),
2702 NextSelectorID(FirstSelectorID), FirstMacroID(1), NextMacroID(FirstMacroID),
2703 CollectedStmts(&StmtsToEmit),
2704 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
2705 NumVisibleDeclContexts(0),
2706 FirstCXXBaseSpecifiersID(1), NextCXXBaseSpecifiersID(1),
2707 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0),
2708 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0),
2709 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0),
2710 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0),
2711 DeclTypedefAbbrev(0),
2712 DeclVarAbbrev(0), DeclFieldAbbrev(0),
2713 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0)
2717 void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2718 const std::string &OutputFile,
2719 const char *isysroot) {
2720 // Emit the file header.
2721 Stream.Emit((unsigned)'C', 8);
2722 Stream.Emit((unsigned)'P', 8);
2723 Stream.Emit((unsigned)'C', 8);
2724 Stream.Emit((unsigned)'H', 8);
2726 WriteBlockInfoBlock();
2729 WriteASTChain(SemaRef, StatCalls, isysroot);
2731 WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile);
2734 void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2735 const char *isysroot,
2736 const std::string &OutputFile) {
2737 using namespace llvm;
2739 ASTContext &Context = SemaRef.Context;
2740 Preprocessor &PP = SemaRef.PP;
2742 // The translation unit is the first declaration we'll emit.
2743 DeclIDs[Context.getTranslationUnitDecl()] = 1;
2745 DeclTypesToEmit.push(Context.getTranslationUnitDecl());
2747 // Make sure that we emit IdentifierInfos (and any attached
2748 // declarations) for builtins.
2750 IdentifierTable &Table = PP.getIdentifierTable();
2751 llvm::SmallVector<const char *, 32> BuiltinNames;
2752 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
2753 Context.getLangOptions().NoBuiltin);
2754 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
2755 getIdentifierRef(&Table.get(BuiltinNames[I]));
2758 // Build a record containing all of the tentative definitions in this file, in
2759 // TentativeDefinitions order. Generally, this record will be empty for
2761 RecordData TentativeDefinitions;
2762 for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
2763 AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
2766 // Build a record containing all of the file scoped decls in this file.
2767 RecordData UnusedFileScopedDecls;
2768 for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i)
2769 AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
2771 RecordData DelegatingCtorDecls;
2772 for (unsigned i=0, e = SemaRef.DelegatingCtorDecls.size(); i != e; ++i)
2773 AddDeclRef(SemaRef.DelegatingCtorDecls[i], DelegatingCtorDecls);
2775 RecordData WeakUndeclaredIdentifiers;
2776 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
2777 WeakUndeclaredIdentifiers.push_back(
2778 SemaRef.WeakUndeclaredIdentifiers.size());
2779 for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
2780 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
2781 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
2782 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
2783 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
2784 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
2785 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
2789 // Build a record containing all of the locally-scoped external
2790 // declarations in this header file. Generally, this record will be
2792 RecordData LocallyScopedExternalDecls;
2793 // FIXME: This is filling in the AST file in densemap order which is
2795 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
2796 TD = SemaRef.LocallyScopedExternalDecls.begin(),
2797 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
2799 AddDeclRef(TD->second, LocallyScopedExternalDecls);
2801 // Build a record containing all of the ext_vector declarations.
2802 RecordData ExtVectorDecls;
2803 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
2804 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
2806 // Build a record containing all of the VTable uses information.
2807 RecordData VTableUses;
2808 if (!SemaRef.VTableUses.empty()) {
2809 VTableUses.push_back(SemaRef.VTableUses.size());
2810 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
2811 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
2812 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
2813 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
2817 // Build a record containing all of dynamic classes declarations.
2818 RecordData DynamicClasses;
2819 for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
2820 AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
2822 // Build a record containing all of pending implicit instantiations.
2823 RecordData PendingInstantiations;
2824 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
2825 I = SemaRef.PendingInstantiations.begin(),
2826 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
2827 AddDeclRef(I->first, PendingInstantiations);
2828 AddSourceLocation(I->second, PendingInstantiations);
2830 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
2831 "There are local ones at end of translation unit!");
2833 // Build a record containing some declaration references.
2834 RecordData SemaDeclRefs;
2835 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
2836 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
2837 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
2840 RecordData CUDASpecialDeclRefs;
2841 if (Context.getcudaConfigureCallDecl()) {
2842 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
2845 // Write the remaining AST contents.
2847 Stream.EnterSubblock(AST_BLOCK_ID, 5);
2848 WriteMetadata(Context, isysroot, OutputFile);
2849 WriteLanguageOptions(Context.getLangOptions());
2850 if (StatCalls && !isysroot)
2851 WriteStatCache(*StatCalls);
2852 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2853 // Write the record of special types.
2856 AddTypeRef(Context.getBuiltinVaListType(), Record);
2857 AddTypeRef(Context.getObjCIdType(), Record);
2858 AddTypeRef(Context.getObjCSelType(), Record);
2859 AddTypeRef(Context.getObjCProtoType(), Record);
2860 AddTypeRef(Context.getObjCClassType(), Record);
2861 AddTypeRef(Context.getRawCFConstantStringType(), Record);
2862 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
2863 AddTypeRef(Context.getFILEType(), Record);
2864 AddTypeRef(Context.getjmp_bufType(), Record);
2865 AddTypeRef(Context.getsigjmp_bufType(), Record);
2866 AddTypeRef(Context.ObjCIdRedefinitionType, Record);
2867 AddTypeRef(Context.ObjCClassRedefinitionType, Record);
2868 AddTypeRef(Context.getRawBlockdescriptorType(), Record);
2869 AddTypeRef(Context.getRawBlockdescriptorExtendedType(), Record);
2870 AddTypeRef(Context.ObjCSelRedefinitionType, Record);
2871 AddTypeRef(Context.getRawNSConstantStringType(), Record);
2872 Record.push_back(Context.isInt128Installed());
2873 AddTypeRef(Context.AutoDeductTy, Record);
2874 AddTypeRef(Context.AutoRRefDeductTy, Record);
2875 Stream.EmitRecord(SPECIAL_TYPES, Record);
2877 // Keep writing types and declarations until all types and
2878 // declarations have been written.
2879 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
2880 WriteDeclsBlockAbbrevs();
2881 while (!DeclTypesToEmit.empty()) {
2882 DeclOrType DOT = DeclTypesToEmit.front();
2883 DeclTypesToEmit.pop();
2885 WriteType(DOT.getType());
2887 WriteDecl(Context, DOT.getDecl());
2891 WritePreprocessor(PP);
2892 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
2893 WriteSelectors(SemaRef);
2894 WriteReferencedSelectorsPool(SemaRef);
2895 WriteIdentifierTable(PP);
2896 WriteFPPragmaOptions(SemaRef.getFPOptions());
2897 WriteOpenCLExtensions(SemaRef);
2899 WriteTypeDeclOffsets();
2900 WritePragmaDiagnosticMappings(Context.getDiagnostics());
2902 WriteCXXBaseSpecifiersOffsets();
2904 // Write the record containing external, unnamed definitions.
2905 if (!ExternalDefinitions.empty())
2906 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
2908 // Write the record containing tentative definitions.
2909 if (!TentativeDefinitions.empty())
2910 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
2912 // Write the record containing unused file scoped decls.
2913 if (!UnusedFileScopedDecls.empty())
2914 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
2916 // Write the record containing weak undeclared identifiers.
2917 if (!WeakUndeclaredIdentifiers.empty())
2918 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
2919 WeakUndeclaredIdentifiers);
2921 // Write the record containing locally-scoped external definitions.
2922 if (!LocallyScopedExternalDecls.empty())
2923 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
2924 LocallyScopedExternalDecls);
2926 // Write the record containing ext_vector type names.
2927 if (!ExtVectorDecls.empty())
2928 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
2930 // Write the record containing VTable uses information.
2931 if (!VTableUses.empty())
2932 Stream.EmitRecord(VTABLE_USES, VTableUses);
2934 // Write the record containing dynamic classes declarations.
2935 if (!DynamicClasses.empty())
2936 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
2938 // Write the record containing pending implicit instantiations.
2939 if (!PendingInstantiations.empty())
2940 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
2942 // Write the record containing declaration references of Sema.
2943 if (!SemaDeclRefs.empty())
2944 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
2946 // Write the record containing CUDA-specific declaration references.
2947 if (!CUDASpecialDeclRefs.empty())
2948 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
2950 // Write the delegating constructors.
2951 if (!DelegatingCtorDecls.empty())
2952 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
2954 // Some simple statistics
2956 Record.push_back(NumStatements);
2957 Record.push_back(NumMacros);
2958 Record.push_back(NumLexicalDeclContexts);
2959 Record.push_back(NumVisibleDeclContexts);
2960 Stream.EmitRecord(STATISTICS, Record);
2964 void ASTWriter::WriteASTChain(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2965 const char *isysroot) {
2966 using namespace llvm;
2968 ASTContext &Context = SemaRef.Context;
2969 Preprocessor &PP = SemaRef.PP;
2972 Stream.EnterSubblock(AST_BLOCK_ID, 5);
2973 WriteMetadata(Context, isysroot, "");
2974 if (StatCalls && !isysroot)
2975 WriteStatCache(*StatCalls);
2976 // FIXME: Source manager block should only write new stuff, which could be
2977 // done by tracking the largest ID in the chain
2978 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2980 // The special types are in the chained PCH.
2982 // We don't start with the translation unit, but with its decls that
2983 // don't come from the chained PCH.
2984 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
2985 llvm::SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
2986 for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
2987 E = TU->noload_decls_end();
2989 if ((*I)->getPCHLevel() == 0)
2990 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
2991 else if ((*I)->isChangedSinceDeserialization())
2992 (void)GetDeclRef(*I); // Make sure it's written, but don't record it.
2994 // We also need to write a lexical updates block for the TU.
2995 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
2996 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
2997 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
2998 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
3000 Record.push_back(TU_UPDATE_LEXICAL);
3001 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
3002 data(NewGlobalDecls));
3003 // And a visible updates block for the DeclContexts.
3004 Abv = new llvm::BitCodeAbbrev();
3005 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
3006 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3007 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
3008 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3009 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
3010 WriteDeclContextVisibleUpdate(TU);
3012 // Build a record containing all of the new tentative definitions in this
3013 // file, in TentativeDefinitions order.
3014 RecordData TentativeDefinitions;
3015 for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
3016 if (SemaRef.TentativeDefinitions[i]->getPCHLevel() == 0)
3017 AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
3020 // Build a record containing all of the file scoped decls in this file.
3021 RecordData UnusedFileScopedDecls;
3022 for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i) {
3023 if (SemaRef.UnusedFileScopedDecls[i]->getPCHLevel() == 0)
3024 AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
3027 // Build a record containing all of the delegating constructor decls in this
3029 RecordData DelegatingCtorDecls;
3030 for (unsigned i=0, e = SemaRef.DelegatingCtorDecls.size(); i != e; ++i) {
3031 if (SemaRef.DelegatingCtorDecls[i]->getPCHLevel() == 0)
3032 AddDeclRef(SemaRef.DelegatingCtorDecls[i], DelegatingCtorDecls);
3035 // We write the entire table, overwriting the tables from the chain.
3036 RecordData WeakUndeclaredIdentifiers;
3037 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
3038 WeakUndeclaredIdentifiers.push_back(
3039 SemaRef.WeakUndeclaredIdentifiers.size());
3040 for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
3041 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
3042 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
3043 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
3044 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
3045 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
3046 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
3050 // Build a record containing all of the locally-scoped external
3051 // declarations in this header file. Generally, this record will be
3053 RecordData LocallyScopedExternalDecls;
3054 // FIXME: This is filling in the AST file in densemap order which is
3056 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3057 TD = SemaRef.LocallyScopedExternalDecls.begin(),
3058 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
3059 TD != TDEnd; ++TD) {
3060 if (TD->second->getPCHLevel() == 0)
3061 AddDeclRef(TD->second, LocallyScopedExternalDecls);
3064 // Build a record containing all of the ext_vector declarations.
3065 RecordData ExtVectorDecls;
3066 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I) {
3067 if (SemaRef.ExtVectorDecls[I]->getPCHLevel() == 0)
3068 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
3071 // Build a record containing all of the VTable uses information.
3072 // We write everything here, because it's too hard to determine whether
3073 // a use is new to this part.
3074 RecordData VTableUses;
3075 if (!SemaRef.VTableUses.empty()) {
3076 VTableUses.push_back(SemaRef.VTableUses.size());
3077 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
3078 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
3079 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
3080 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
3084 // Build a record containing all of dynamic classes declarations.
3085 RecordData DynamicClasses;
3086 for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
3087 if (SemaRef.DynamicClasses[I]->getPCHLevel() == 0)
3088 AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
3090 // Build a record containing all of pending implicit instantiations.
3091 RecordData PendingInstantiations;
3092 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
3093 I = SemaRef.PendingInstantiations.begin(),
3094 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
3095 AddDeclRef(I->first, PendingInstantiations);
3096 AddSourceLocation(I->second, PendingInstantiations);
3098 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
3099 "There are local ones at end of translation unit!");
3101 // Build a record containing some declaration references.
3102 // It's not worth the effort to avoid duplication here.
3103 RecordData SemaDeclRefs;
3104 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
3105 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
3106 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
3109 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
3110 WriteDeclsBlockAbbrevs();
3111 for (DeclsToRewriteTy::iterator
3112 I = DeclsToRewrite.begin(), E = DeclsToRewrite.end(); I != E; ++I)
3113 DeclTypesToEmit.push(const_cast<Decl*>(*I));
3114 while (!DeclTypesToEmit.empty()) {
3115 DeclOrType DOT = DeclTypesToEmit.front();
3116 DeclTypesToEmit.pop();
3118 WriteType(DOT.getType());
3120 WriteDecl(Context, DOT.getDecl());
3124 WritePreprocessor(PP);
3125 WriteSelectors(SemaRef);
3126 WriteReferencedSelectorsPool(SemaRef);
3127 WriteIdentifierTable(PP);
3128 WriteFPPragmaOptions(SemaRef.getFPOptions());
3129 WriteOpenCLExtensions(SemaRef);
3131 WriteTypeDeclOffsets();
3132 // FIXME: For chained PCH only write the new mappings (we currently
3133 // write all of them again).
3134 WritePragmaDiagnosticMappings(Context.getDiagnostics());
3136 WriteCXXBaseSpecifiersOffsets();
3138 /// Build a record containing first declarations from a chained PCH and the
3139 /// most recent declarations in this AST that they point to.
3140 RecordData FirstLatestDeclIDs;
3141 for (FirstLatestDeclMap::iterator
3142 I = FirstLatestDecls.begin(), E = FirstLatestDecls.end(); I != E; ++I) {
3143 assert(I->first->getPCHLevel() > I->second->getPCHLevel() &&
3144 "Expected first & second to be in different PCHs");
3145 AddDeclRef(I->first, FirstLatestDeclIDs);
3146 AddDeclRef(I->second, FirstLatestDeclIDs);
3148 if (!FirstLatestDeclIDs.empty())
3149 Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs);
3151 // Write the record containing external, unnamed definitions.
3152 if (!ExternalDefinitions.empty())
3153 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
3155 // Write the record containing tentative definitions.
3156 if (!TentativeDefinitions.empty())
3157 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
3159 // Write the record containing unused file scoped decls.
3160 if (!UnusedFileScopedDecls.empty())
3161 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
3163 // Write the record containing weak undeclared identifiers.
3164 if (!WeakUndeclaredIdentifiers.empty())
3165 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
3166 WeakUndeclaredIdentifiers);
3168 // Write the record containing locally-scoped external definitions.
3169 if (!LocallyScopedExternalDecls.empty())
3170 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
3171 LocallyScopedExternalDecls);
3173 // Write the record containing ext_vector type names.
3174 if (!ExtVectorDecls.empty())
3175 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
3177 // Write the record containing VTable uses information.
3178 if (!VTableUses.empty())
3179 Stream.EmitRecord(VTABLE_USES, VTableUses);
3181 // Write the record containing dynamic classes declarations.
3182 if (!DynamicClasses.empty())
3183 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
3185 // Write the record containing pending implicit instantiations.
3186 if (!PendingInstantiations.empty())
3187 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
3189 // Write the record containing declaration references of Sema.
3190 if (!SemaDeclRefs.empty())
3191 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
3193 // Write the delegating constructors.
3194 if (!DelegatingCtorDecls.empty())
3195 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
3197 // Write the updates to DeclContexts.
3198 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
3199 I = UpdatedDeclContexts.begin(),
3200 E = UpdatedDeclContexts.end();
3202 WriteDeclContextVisibleUpdate(*I);
3204 WriteDeclUpdatesBlocks();
3207 Record.push_back(NumStatements);
3208 Record.push_back(NumMacros);
3209 Record.push_back(NumLexicalDeclContexts);
3210 Record.push_back(NumVisibleDeclContexts);
3211 WriteDeclReplacementsBlock();
3212 Stream.EmitRecord(STATISTICS, Record);
3216 void ASTWriter::WriteDeclUpdatesBlocks() {
3217 if (DeclUpdates.empty())
3220 RecordData OffsetsRecord;
3221 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
3222 for (DeclUpdateMap::iterator
3223 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
3224 const Decl *D = I->first;
3225 UpdateRecord &URec = I->second;
3227 if (DeclsToRewrite.count(D))
3228 continue; // The decl will be written completely,no need to store updates.
3230 uint64_t Offset = Stream.GetCurrentBitNo();
3231 Stream.EmitRecord(DECL_UPDATES, URec);
3233 OffsetsRecord.push_back(GetDeclRef(D));
3234 OffsetsRecord.push_back(Offset);
3237 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
3240 void ASTWriter::WriteDeclReplacementsBlock() {
3241 if (ReplacedDecls.empty())
3245 for (llvm::SmallVector<std::pair<DeclID, uint64_t>, 16>::iterator
3246 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
3247 Record.push_back(I->first);
3248 Record.push_back(I->second);
3250 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
3253 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
3254 Record.push_back(Loc.getRawEncoding());
3257 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
3258 AddSourceLocation(Range.getBegin(), Record);
3259 AddSourceLocation(Range.getEnd(), Record);
3262 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
3263 Record.push_back(Value.getBitWidth());
3264 const uint64_t *Words = Value.getRawData();
3265 Record.append(Words, Words + Value.getNumWords());
3268 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
3269 Record.push_back(Value.isUnsigned());
3270 AddAPInt(Value, Record);
3273 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
3274 AddAPInt(Value.bitcastToAPInt(), Record);
3277 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
3278 Record.push_back(getIdentifierRef(II));
3281 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
3285 IdentID &ID = IdentifierIDs[II];
3291 MacroID ASTWriter::getMacroDefinitionID(MacroDefinition *MD) {
3295 MacroID &ID = MacroDefinitions[MD];
3301 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
3302 Record.push_back(getSelectorRef(SelRef));
3305 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
3306 if (Sel.getAsOpaquePtr() == 0) {
3310 SelectorID &SID = SelectorIDs[Sel];
3311 if (SID == 0 && Chain) {
3312 // This might trigger a ReadSelector callback, which will set the ID for
3314 Chain->LoadSelector(Sel);
3317 SID = NextSelectorID++;
3322 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
3323 AddDeclRef(Temp->getDestructor(), Record);
3326 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
3327 CXXBaseSpecifier const *BasesEnd,
3328 RecordDataImpl &Record) {
3329 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
3330 CXXBaseSpecifiersToWrite.push_back(
3331 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
3333 Record.push_back(NextCXXBaseSpecifiersID++);
3336 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
3337 const TemplateArgumentLocInfo &Arg,
3338 RecordDataImpl &Record) {
3340 case TemplateArgument::Expression:
3341 AddStmt(Arg.getAsExpr());
3343 case TemplateArgument::Type:
3344 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
3346 case TemplateArgument::Template:
3347 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3348 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3350 case TemplateArgument::TemplateExpansion:
3351 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3352 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3353 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
3355 case TemplateArgument::Null:
3356 case TemplateArgument::Integral:
3357 case TemplateArgument::Declaration:
3358 case TemplateArgument::Pack:
3363 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
3364 RecordDataImpl &Record) {
3365 AddTemplateArgument(Arg.getArgument(), Record);
3367 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
3368 bool InfoHasSameExpr
3369 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
3370 Record.push_back(InfoHasSameExpr);
3371 if (InfoHasSameExpr)
3372 return; // Avoid storing the same expr twice.
3374 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
3378 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
3379 RecordDataImpl &Record) {
3381 AddTypeRef(QualType(), Record);
3385 AddTypeLoc(TInfo->getTypeLoc(), Record);
3388 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
3389 AddTypeRef(TL.getType(), Record);
3391 TypeLocWriter TLW(*this, Record);
3392 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
3396 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
3397 Record.push_back(GetOrCreateTypeID(T));
3400 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
3401 return MakeTypeID(T,
3402 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
3405 TypeID ASTWriter::getTypeID(QualType T) const {
3406 return MakeTypeID(T,
3407 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
3410 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
3413 assert(!T.getLocalFastQualifiers());
3415 TypeIdx &Idx = TypeIdxs[T];
3416 if (Idx.getIndex() == 0) {
3417 // We haven't seen this type before. Assign it a new ID and put it
3418 // into the queue of types to emit.
3419 Idx = TypeIdx(NextTypeID++);
3420 DeclTypesToEmit.push(T);
3425 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
3428 assert(!T.getLocalFastQualifiers());
3430 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
3431 assert(I != TypeIdxs.end() && "Type not emitted!");
3435 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
3436 Record.push_back(GetDeclRef(D));
3439 DeclID ASTWriter::GetDeclRef(const Decl *D) {
3443 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
3444 DeclID &ID = DeclIDs[D];
3446 // We haven't seen this declaration before. Give it a new ID and
3447 // enqueue it in the list of declarations to emit.
3449 DeclTypesToEmit.push(const_cast<Decl *>(D));
3450 } else if (ID < FirstDeclID && D->isChangedSinceDeserialization()) {
3451 // We don't add it to the replacement collection here, because we don't
3452 // have the offset yet.
3453 DeclTypesToEmit.push(const_cast<Decl *>(D));
3454 // Reset the flag, so that we don't add this decl multiple times.
3455 const_cast<Decl *>(D)->setChangedSinceDeserialization(false);
3461 DeclID ASTWriter::getDeclID(const Decl *D) {
3465 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
3469 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
3470 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
3471 Record.push_back(Name.getNameKind());
3472 switch (Name.getNameKind()) {
3473 case DeclarationName::Identifier:
3474 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
3477 case DeclarationName::ObjCZeroArgSelector:
3478 case DeclarationName::ObjCOneArgSelector:
3479 case DeclarationName::ObjCMultiArgSelector:
3480 AddSelectorRef(Name.getObjCSelector(), Record);
3483 case DeclarationName::CXXConstructorName:
3484 case DeclarationName::CXXDestructorName:
3485 case DeclarationName::CXXConversionFunctionName:
3486 AddTypeRef(Name.getCXXNameType(), Record);
3489 case DeclarationName::CXXOperatorName:
3490 Record.push_back(Name.getCXXOverloadedOperator());
3493 case DeclarationName::CXXLiteralOperatorName:
3494 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
3497 case DeclarationName::CXXUsingDirective:
3498 // No extra data to emit
3503 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
3504 DeclarationName Name, RecordDataImpl &Record) {
3505 switch (Name.getNameKind()) {
3506 case DeclarationName::CXXConstructorName:
3507 case DeclarationName::CXXDestructorName:
3508 case DeclarationName::CXXConversionFunctionName:
3509 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
3512 case DeclarationName::CXXOperatorName:
3514 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
3517 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
3521 case DeclarationName::CXXLiteralOperatorName:
3523 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
3527 case DeclarationName::Identifier:
3528 case DeclarationName::ObjCZeroArgSelector:
3529 case DeclarationName::ObjCOneArgSelector:
3530 case DeclarationName::ObjCMultiArgSelector:
3531 case DeclarationName::CXXUsingDirective:
3536 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3537 RecordDataImpl &Record) {
3538 AddDeclarationName(NameInfo.getName(), Record);
3539 AddSourceLocation(NameInfo.getLoc(), Record);
3540 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
3543 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
3544 RecordDataImpl &Record) {
3545 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
3546 Record.push_back(Info.NumTemplParamLists);
3547 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
3548 AddTemplateParameterList(Info.TemplParamLists[i], Record);
3551 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
3552 RecordDataImpl &Record) {
3553 // Nested name specifiers usually aren't too long. I think that 8 would
3554 // typically accommodate the vast majority.
3555 llvm::SmallVector<NestedNameSpecifier *, 8> NestedNames;
3557 // Push each of the NNS's onto a stack for serialization in reverse order.
3559 NestedNames.push_back(NNS);
3560 NNS = NNS->getPrefix();
3563 Record.push_back(NestedNames.size());
3564 while(!NestedNames.empty()) {
3565 NNS = NestedNames.pop_back_val();
3566 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
3567 Record.push_back(Kind);
3569 case NestedNameSpecifier::Identifier:
3570 AddIdentifierRef(NNS->getAsIdentifier(), Record);
3573 case NestedNameSpecifier::Namespace:
3574 AddDeclRef(NNS->getAsNamespace(), Record);
3577 case NestedNameSpecifier::NamespaceAlias:
3578 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
3581 case NestedNameSpecifier::TypeSpec:
3582 case NestedNameSpecifier::TypeSpecWithTemplate:
3583 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
3584 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3587 case NestedNameSpecifier::Global:
3588 // Don't need to write an associated value.
3594 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
3595 RecordDataImpl &Record) {
3596 // Nested name specifiers usually aren't too long. I think that 8 would
3597 // typically accommodate the vast majority.
3598 llvm::SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
3600 // Push each of the nested-name-specifiers's onto a stack for
3601 // serialization in reverse order.
3603 NestedNames.push_back(NNS);
3604 NNS = NNS.getPrefix();
3607 Record.push_back(NestedNames.size());
3608 while(!NestedNames.empty()) {
3609 NNS = NestedNames.pop_back_val();
3610 NestedNameSpecifier::SpecifierKind Kind
3611 = NNS.getNestedNameSpecifier()->getKind();
3612 Record.push_back(Kind);
3614 case NestedNameSpecifier::Identifier:
3615 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
3616 AddSourceRange(NNS.getLocalSourceRange(), Record);
3619 case NestedNameSpecifier::Namespace:
3620 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
3621 AddSourceRange(NNS.getLocalSourceRange(), Record);
3624 case NestedNameSpecifier::NamespaceAlias:
3625 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
3626 AddSourceRange(NNS.getLocalSourceRange(), Record);
3629 case NestedNameSpecifier::TypeSpec:
3630 case NestedNameSpecifier::TypeSpecWithTemplate:
3631 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3632 AddTypeLoc(NNS.getTypeLoc(), Record);
3633 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
3636 case NestedNameSpecifier::Global:
3637 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
3643 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
3644 TemplateName::NameKind Kind = Name.getKind();
3645 Record.push_back(Kind);
3647 case TemplateName::Template:
3648 AddDeclRef(Name.getAsTemplateDecl(), Record);
3651 case TemplateName::OverloadedTemplate: {
3652 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
3653 Record.push_back(OvT->size());
3654 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
3656 AddDeclRef(*I, Record);
3660 case TemplateName::QualifiedTemplate: {
3661 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
3662 AddNestedNameSpecifier(QualT->getQualifier(), Record);
3663 Record.push_back(QualT->hasTemplateKeyword());
3664 AddDeclRef(QualT->getTemplateDecl(), Record);
3668 case TemplateName::DependentTemplate: {
3669 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
3670 AddNestedNameSpecifier(DepT->getQualifier(), Record);
3671 Record.push_back(DepT->isIdentifier());
3672 if (DepT->isIdentifier())
3673 AddIdentifierRef(DepT->getIdentifier(), Record);
3675 Record.push_back(DepT->getOperator());
3679 case TemplateName::SubstTemplateTemplateParmPack: {
3680 SubstTemplateTemplateParmPackStorage *SubstPack
3681 = Name.getAsSubstTemplateTemplateParmPack();
3682 AddDeclRef(SubstPack->getParameterPack(), Record);
3683 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
3689 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
3690 RecordDataImpl &Record) {
3691 Record.push_back(Arg.getKind());
3692 switch (Arg.getKind()) {
3693 case TemplateArgument::Null:
3695 case TemplateArgument::Type:
3696 AddTypeRef(Arg.getAsType(), Record);
3698 case TemplateArgument::Declaration:
3699 AddDeclRef(Arg.getAsDecl(), Record);
3701 case TemplateArgument::Integral:
3702 AddAPSInt(*Arg.getAsIntegral(), Record);
3703 AddTypeRef(Arg.getIntegralType(), Record);
3705 case TemplateArgument::Template:
3706 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3708 case TemplateArgument::TemplateExpansion:
3709 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3710 if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
3711 Record.push_back(*NumExpansions + 1);
3713 Record.push_back(0);
3715 case TemplateArgument::Expression:
3716 AddStmt(Arg.getAsExpr());
3718 case TemplateArgument::Pack:
3719 Record.push_back(Arg.pack_size());
3720 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
3722 AddTemplateArgument(*I, Record);
3728 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
3729 RecordDataImpl &Record) {
3730 assert(TemplateParams && "No TemplateParams!");
3731 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
3732 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
3733 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
3734 Record.push_back(TemplateParams->size());
3735 for (TemplateParameterList::const_iterator
3736 P = TemplateParams->begin(), PEnd = TemplateParams->end();
3738 AddDeclRef(*P, Record);
3741 /// \brief Emit a template argument list.
3743 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
3744 RecordDataImpl &Record) {
3745 assert(TemplateArgs && "No TemplateArgs!");
3746 Record.push_back(TemplateArgs->size());
3747 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
3748 AddTemplateArgument(TemplateArgs->get(i), Record);
3753 ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) {
3754 Record.push_back(Set.size());
3755 for (UnresolvedSetImpl::const_iterator
3756 I = Set.begin(), E = Set.end(); I != E; ++I) {
3757 AddDeclRef(I.getDecl(), Record);
3758 Record.push_back(I.getAccess());
3762 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
3763 RecordDataImpl &Record) {
3764 Record.push_back(Base.isVirtual());
3765 Record.push_back(Base.isBaseOfClass());
3766 Record.push_back(Base.getAccessSpecifierAsWritten());
3767 Record.push_back(Base.getInheritConstructors());
3768 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
3769 AddSourceRange(Base.getSourceRange(), Record);
3770 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
3775 void ASTWriter::FlushCXXBaseSpecifiers() {
3777 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
3780 // Record the offset of this base-specifier set.
3781 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - FirstCXXBaseSpecifiersID;
3782 if (Index == CXXBaseSpecifiersOffsets.size())
3783 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
3785 if (Index > CXXBaseSpecifiersOffsets.size())
3786 CXXBaseSpecifiersOffsets.resize(Index + 1);
3787 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
3790 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
3791 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
3792 Record.push_back(BEnd - B);
3793 for (; B != BEnd; ++B)
3794 AddCXXBaseSpecifier(*B, Record);
3795 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
3797 // Flush any expressions that were written as part of the base specifiers.
3801 CXXBaseSpecifiersToWrite.clear();
3804 void ASTWriter::AddCXXCtorInitializers(
3805 const CXXCtorInitializer * const *CtorInitializers,
3806 unsigned NumCtorInitializers,
3807 RecordDataImpl &Record) {
3808 Record.push_back(NumCtorInitializers);
3809 for (unsigned i=0; i != NumCtorInitializers; ++i) {
3810 const CXXCtorInitializer *Init = CtorInitializers[i];
3812 if (Init->isBaseInitializer()) {
3813 Record.push_back(CTOR_INITIALIZER_BASE);
3814 AddTypeSourceInfo(Init->getBaseClassInfo(), Record);
3815 Record.push_back(Init->isBaseVirtual());
3816 } else if (Init->isDelegatingInitializer()) {
3817 Record.push_back(CTOR_INITIALIZER_DELEGATING);
3818 AddDeclRef(Init->getTargetConstructor(), Record);
3819 } else if (Init->isMemberInitializer()){
3820 Record.push_back(CTOR_INITIALIZER_MEMBER);
3821 AddDeclRef(Init->getMember(), Record);
3823 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
3824 AddDeclRef(Init->getIndirectMember(), Record);
3827 AddSourceLocation(Init->getMemberLocation(), Record);
3828 AddStmt(Init->getInit());
3829 AddSourceLocation(Init->getLParenLoc(), Record);
3830 AddSourceLocation(Init->getRParenLoc(), Record);
3831 Record.push_back(Init->isWritten());
3832 if (Init->isWritten()) {
3833 Record.push_back(Init->getSourceOrder());
3835 Record.push_back(Init->getNumArrayIndices());
3836 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
3837 AddDeclRef(Init->getArrayIndex(i), Record);
3842 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
3843 assert(D->DefinitionData);
3844 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
3845 Record.push_back(Data.UserDeclaredConstructor);
3846 Record.push_back(Data.UserDeclaredCopyConstructor);
3847 Record.push_back(Data.UserDeclaredCopyAssignment);
3848 Record.push_back(Data.UserDeclaredDestructor);
3849 Record.push_back(Data.Aggregate);
3850 Record.push_back(Data.PlainOldData);
3851 Record.push_back(Data.Empty);
3852 Record.push_back(Data.Polymorphic);
3853 Record.push_back(Data.Abstract);
3854 Record.push_back(Data.IsStandardLayout);
3855 Record.push_back(Data.HasNoNonEmptyBases);
3856 Record.push_back(Data.HasPrivateFields);
3857 Record.push_back(Data.HasProtectedFields);
3858 Record.push_back(Data.HasPublicFields);
3859 Record.push_back(Data.HasMutableFields);
3860 Record.push_back(Data.HasTrivialDefaultConstructor);
3861 Record.push_back(Data.HasConstExprNonCopyMoveConstructor);
3862 Record.push_back(Data.HasTrivialCopyConstructor);
3863 Record.push_back(Data.HasTrivialMoveConstructor);
3864 Record.push_back(Data.HasTrivialCopyAssignment);
3865 Record.push_back(Data.HasTrivialMoveAssignment);
3866 Record.push_back(Data.HasTrivialDestructor);
3867 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
3868 Record.push_back(Data.ComputedVisibleConversions);
3869 Record.push_back(Data.UserProvidedDefaultConstructor);
3870 Record.push_back(Data.DeclaredDefaultConstructor);
3871 Record.push_back(Data.DeclaredCopyConstructor);
3872 Record.push_back(Data.DeclaredCopyAssignment);
3873 Record.push_back(Data.DeclaredDestructor);
3875 Record.push_back(Data.NumBases);
3876 if (Data.NumBases > 0)
3877 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
3880 // FIXME: Make VBases lazily computed when needed to avoid storing them.
3881 Record.push_back(Data.NumVBases);
3882 if (Data.NumVBases > 0)
3883 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
3886 AddUnresolvedSet(Data.Conversions, Record);
3887 AddUnresolvedSet(Data.VisibleConversions, Record);
3888 // Data.Definition is the owning decl, no need to write it.
3889 AddDeclRef(Data.FirstFriend, Record);
3892 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
3893 assert(Reader && "Cannot remove chain");
3894 assert(!Chain && "Cannot replace chain");
3895 assert(FirstDeclID == NextDeclID &&
3896 FirstTypeID == NextTypeID &&
3897 FirstIdentID == NextIdentID &&
3898 FirstSelectorID == NextSelectorID &&
3899 FirstMacroID == NextMacroID &&
3900 FirstCXXBaseSpecifiersID == NextCXXBaseSpecifiersID &&
3901 "Setting chain after writing has started.");
3904 FirstDeclID += Chain->getTotalNumDecls();
3905 FirstTypeID += Chain->getTotalNumTypes();
3906 FirstIdentID += Chain->getTotalNumIdentifiers();
3907 FirstSelectorID += Chain->getTotalNumSelectors();
3908 FirstMacroID += Chain->getTotalNumMacroDefinitions();
3909 FirstCXXBaseSpecifiersID += Chain->getTotalNumCXXBaseSpecifiers();
3910 NextDeclID = FirstDeclID;
3911 NextTypeID = FirstTypeID;
3912 NextIdentID = FirstIdentID;
3913 NextSelectorID = FirstSelectorID;
3914 NextMacroID = FirstMacroID;
3915 NextCXXBaseSpecifiersID = FirstCXXBaseSpecifiersID;
3918 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
3919 IdentifierIDs[II] = ID;
3920 if (II->hasMacroDefinition())
3921 DeserializedMacroNames.push_back(II);
3924 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
3925 // Always take the highest-numbered type index. This copes with an interesting
3926 // case for chained AST writing where we schedule writing the type and then,
3927 // later, deserialize the type from another AST. In this case, we want to
3928 // keep the higher-numbered entry so that we can properly write it out to
3930 TypeIdx &StoredIdx = TypeIdxs[T];
3931 if (Idx.getIndex() >= StoredIdx.getIndex())
3935 void ASTWriter::DeclRead(DeclID ID, const Decl *D) {
3939 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
3940 SelectorIDs[S] = ID;
3943 void ASTWriter::MacroDefinitionRead(serialization::MacroID ID,
3944 MacroDefinition *MD) {
3945 MacroDefinitions[MD] = ID;
3948 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
3949 assert(D->isDefinition());
3950 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
3951 // We are interested when a PCH decl is modified.
3952 if (RD->getPCHLevel() > 0) {
3953 // A forward reference was mutated into a definition. Rewrite it.
3954 // FIXME: This happens during template instantiation, should we
3955 // have created a new definition decl instead ?
3959 for (CXXRecordDecl::redecl_iterator
3960 I = RD->redecls_begin(), E = RD->redecls_end(); I != E; ++I) {
3961 CXXRecordDecl *Redecl = cast<CXXRecordDecl>(*I);
3965 // We are interested when a PCH decl is modified.
3966 if (Redecl->getPCHLevel() > 0) {
3967 UpdateRecord &Record = DeclUpdates[Redecl];
3968 Record.push_back(UPD_CXX_SET_DEFINITIONDATA);
3969 assert(Redecl->DefinitionData);
3970 assert(Redecl->DefinitionData->Definition == D);
3971 AddDeclRef(D, Record); // the DefinitionDecl
3976 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
3977 // TU and namespaces are handled elsewhere.
3978 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
3981 if (!(D->getPCHLevel() == 0 && cast<Decl>(DC)->getPCHLevel() > 0))
3982 return; // Not a source decl added to a DeclContext from PCH.
3984 AddUpdatedDeclContext(DC);
3987 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
3988 assert(D->isImplicit());
3989 if (!(D->getPCHLevel() == 0 && RD->getPCHLevel() > 0))
3990 return; // Not a source member added to a class from PCH.
3991 if (!isa<CXXMethodDecl>(D))
3992 return; // We are interested in lazily declared implicit methods.
3994 // A decl coming from PCH was modified.
3995 assert(RD->isDefinition());
3996 UpdateRecord &Record = DeclUpdates[RD];
3997 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
3998 AddDeclRef(D, Record);
4001 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
4002 const ClassTemplateSpecializationDecl *D) {
4003 // The specializations set is kept in the canonical template.
4004 TD = TD->getCanonicalDecl();
4005 if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0))
4006 return; // Not a source specialization added to a template from PCH.
4008 UpdateRecord &Record = DeclUpdates[TD];
4009 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
4010 AddDeclRef(D, Record);
4013 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
4014 const FunctionDecl *D) {
4015 // The specializations set is kept in the canonical template.
4016 TD = TD->getCanonicalDecl();
4017 if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0))
4018 return; // Not a source specialization added to a template from PCH.
4020 UpdateRecord &Record = DeclUpdates[TD];
4021 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
4022 AddDeclRef(D, Record);
4025 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
4026 if (D->getPCHLevel() == 0)
4027 return; // Declaration not imported from PCH.
4029 // Implicit decl from a PCH was defined.
4030 // FIXME: Should implicit definition be a separate FunctionDecl?
4034 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
4035 if (D->getPCHLevel() == 0)
4038 // Since the actual instantiation is delayed, this really means that we need
4039 // to update the instantiation location.
4040 UpdateRecord &Record = DeclUpdates[D];
4041 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER);
4043 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record);
4046 ASTSerializationListener::~ASTSerializationListener() { }