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 "llvm/ADT/APFloat.h"
41 #include "llvm/ADT/APInt.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/Bitcode/BitstreamWriter.h"
44 #include "llvm/Support/FileSystem.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/Path.h"
49 using namespace clang;
50 using namespace clang::serialization;
52 template <typename T, typename Allocator>
53 T *data(std::vector<T, Allocator> &v) {
54 return v.empty() ? 0 : &v.front();
56 template <typename T, typename Allocator>
57 const T *data(const std::vector<T, Allocator> &v) {
58 return v.empty() ? 0 : &v.front();
61 //===----------------------------------------------------------------------===//
63 //===----------------------------------------------------------------------===//
68 ASTWriter::RecordDataImpl &Record;
71 /// \brief Type code that corresponds to the record generated.
74 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
75 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
77 void VisitArrayType(const ArrayType *T);
78 void VisitFunctionType(const FunctionType *T);
79 void VisitTagType(const TagType *T);
81 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
82 #define ABSTRACT_TYPE(Class, Base)
83 #include "clang/AST/TypeNodes.def"
87 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
88 assert(false && "Built-in types are never serialized");
91 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
92 Writer.AddTypeRef(T->getElementType(), Record);
96 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
97 Writer.AddTypeRef(T->getPointeeType(), Record);
101 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
102 Writer.AddTypeRef(T->getPointeeType(), Record);
103 Code = TYPE_BLOCK_POINTER;
106 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
107 Writer.AddTypeRef(T->getPointeeType(), Record);
108 Code = TYPE_LVALUE_REFERENCE;
111 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
112 Writer.AddTypeRef(T->getPointeeType(), Record);
113 Code = TYPE_RVALUE_REFERENCE;
116 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
117 Writer.AddTypeRef(T->getPointeeType(), Record);
118 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
119 Code = TYPE_MEMBER_POINTER;
122 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
123 Writer.AddTypeRef(T->getElementType(), Record);
124 Record.push_back(T->getSizeModifier()); // FIXME: stable values
125 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
128 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
130 Writer.AddAPInt(T->getSize(), Record);
131 Code = TYPE_CONSTANT_ARRAY;
134 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
136 Code = TYPE_INCOMPLETE_ARRAY;
139 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
141 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
142 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
143 Writer.AddStmt(T->getSizeExpr());
144 Code = TYPE_VARIABLE_ARRAY;
147 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
148 Writer.AddTypeRef(T->getElementType(), Record);
149 Record.push_back(T->getNumElements());
150 Record.push_back(T->getVectorKind());
154 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
156 Code = TYPE_EXT_VECTOR;
159 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
160 Writer.AddTypeRef(T->getResultType(), Record);
161 FunctionType::ExtInfo C = T->getExtInfo();
162 Record.push_back(C.getNoReturn());
163 Record.push_back(C.getRegParm());
164 // FIXME: need to stabilize encoding of calling convention...
165 Record.push_back(C.getCC());
168 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
169 VisitFunctionType(T);
170 Code = TYPE_FUNCTION_NO_PROTO;
173 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
174 VisitFunctionType(T);
175 Record.push_back(T->getNumArgs());
176 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
177 Writer.AddTypeRef(T->getArgType(I), Record);
178 Record.push_back(T->isVariadic());
179 Record.push_back(T->getTypeQuals());
180 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
181 Record.push_back(T->hasExceptionSpec());
182 Record.push_back(T->hasAnyExceptionSpec());
183 Record.push_back(T->getNumExceptions());
184 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
185 Writer.AddTypeRef(T->getExceptionType(I), Record);
186 Code = TYPE_FUNCTION_PROTO;
189 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
190 Writer.AddDeclRef(T->getDecl(), Record);
191 Code = TYPE_UNRESOLVED_USING;
194 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
195 Writer.AddDeclRef(T->getDecl(), Record);
196 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
197 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
201 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
202 Writer.AddStmt(T->getUnderlyingExpr());
203 Code = TYPE_TYPEOF_EXPR;
206 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
207 Writer.AddTypeRef(T->getUnderlyingType(), Record);
211 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
212 Writer.AddStmt(T->getUnderlyingExpr());
213 Code = TYPE_DECLTYPE;
216 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
217 Writer.AddTypeRef(T->getDeducedType(), Record);
221 void ASTTypeWriter::VisitTagType(const TagType *T) {
222 Record.push_back(T->isDependentType());
223 Writer.AddDeclRef(T->getDecl(), Record);
224 assert(!T->isBeingDefined() &&
225 "Cannot serialize in the middle of a type definition");
228 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
233 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
238 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
239 Writer.AddTypeRef(T->getModifiedType(), Record);
240 Writer.AddTypeRef(T->getEquivalentType(), Record);
241 Record.push_back(T->getAttrKind());
242 Code = TYPE_ATTRIBUTED;
246 ASTTypeWriter::VisitSubstTemplateTypeParmType(
247 const SubstTemplateTypeParmType *T) {
248 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
249 Writer.AddTypeRef(T->getReplacementType(), Record);
250 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
254 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
255 const SubstTemplateTypeParmPackType *T) {
256 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
257 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
258 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
262 ASTTypeWriter::VisitTemplateSpecializationType(
263 const TemplateSpecializationType *T) {
264 Record.push_back(T->isDependentType());
265 Writer.AddTemplateName(T->getTemplateName(), Record);
266 Record.push_back(T->getNumArgs());
267 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
268 ArgI != ArgE; ++ArgI)
269 Writer.AddTemplateArgument(*ArgI, Record);
270 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
271 : T->getCanonicalTypeInternal(),
273 Code = TYPE_TEMPLATE_SPECIALIZATION;
277 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
279 Writer.AddStmt(T->getSizeExpr());
280 Writer.AddSourceRange(T->getBracketsRange(), Record);
281 Code = TYPE_DEPENDENT_SIZED_ARRAY;
285 ASTTypeWriter::VisitDependentSizedExtVectorType(
286 const DependentSizedExtVectorType *T) {
287 // FIXME: Serialize this type (C++ only)
288 assert(false && "Cannot serialize dependent sized extended vector types");
292 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
293 Record.push_back(T->getDepth());
294 Record.push_back(T->getIndex());
295 Record.push_back(T->isParameterPack());
296 Writer.AddIdentifierRef(T->getName(), Record);
297 Code = TYPE_TEMPLATE_TYPE_PARM;
301 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
302 Record.push_back(T->getKeyword());
303 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
304 Writer.AddIdentifierRef(T->getIdentifier(), Record);
305 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
306 : T->getCanonicalTypeInternal(),
308 Code = TYPE_DEPENDENT_NAME;
312 ASTTypeWriter::VisitDependentTemplateSpecializationType(
313 const DependentTemplateSpecializationType *T) {
314 Record.push_back(T->getKeyword());
315 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
316 Writer.AddIdentifierRef(T->getIdentifier(), Record);
317 Record.push_back(T->getNumArgs());
318 for (DependentTemplateSpecializationType::iterator
319 I = T->begin(), E = T->end(); I != E; ++I)
320 Writer.AddTemplateArgument(*I, Record);
321 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
324 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
325 Writer.AddTypeRef(T->getPattern(), Record);
326 if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions())
327 Record.push_back(*NumExpansions + 1);
330 Code = TYPE_PACK_EXPANSION;
333 void ASTTypeWriter::VisitParenType(const ParenType *T) {
334 Writer.AddTypeRef(T->getInnerType(), Record);
338 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
339 Record.push_back(T->getKeyword());
340 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
341 Writer.AddTypeRef(T->getNamedType(), Record);
342 Code = TYPE_ELABORATED;
345 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
346 Writer.AddDeclRef(T->getDecl(), Record);
347 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
348 Code = TYPE_INJECTED_CLASS_NAME;
351 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
352 Writer.AddDeclRef(T->getDecl(), Record);
353 Code = TYPE_OBJC_INTERFACE;
356 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
357 Writer.AddTypeRef(T->getBaseType(), Record);
358 Record.push_back(T->getNumProtocols());
359 for (ObjCObjectType::qual_iterator I = T->qual_begin(),
360 E = T->qual_end(); I != E; ++I)
361 Writer.AddDeclRef(*I, Record);
362 Code = TYPE_OBJC_OBJECT;
366 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
367 Writer.AddTypeRef(T->getPointeeType(), Record);
368 Code = TYPE_OBJC_OBJECT_POINTER;
373 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
375 ASTWriter::RecordDataImpl &Record;
378 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
379 : Writer(Writer), Record(Record) { }
381 #define ABSTRACT_TYPELOC(CLASS, PARENT)
382 #define TYPELOC(CLASS, PARENT) \
383 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
384 #include "clang/AST/TypeLocNodes.def"
386 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
387 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
392 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
395 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
396 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
397 if (TL.needsExtraLocalData()) {
398 Record.push_back(TL.getWrittenTypeSpec());
399 Record.push_back(TL.getWrittenSignSpec());
400 Record.push_back(TL.getWrittenWidthSpec());
401 Record.push_back(TL.hasModeAttr());
404 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
405 Writer.AddSourceLocation(TL.getNameLoc(), Record);
407 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
408 Writer.AddSourceLocation(TL.getStarLoc(), Record);
410 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
411 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
413 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
414 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
416 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
417 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
419 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
420 Writer.AddSourceLocation(TL.getStarLoc(), Record);
422 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
423 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
424 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
425 Record.push_back(TL.getSizeExpr() ? 1 : 0);
426 if (TL.getSizeExpr())
427 Writer.AddStmt(TL.getSizeExpr());
429 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
430 VisitArrayTypeLoc(TL);
432 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
433 VisitArrayTypeLoc(TL);
435 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
436 VisitArrayTypeLoc(TL);
438 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
439 DependentSizedArrayTypeLoc TL) {
440 VisitArrayTypeLoc(TL);
442 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
443 DependentSizedExtVectorTypeLoc TL) {
444 Writer.AddSourceLocation(TL.getNameLoc(), Record);
446 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
447 Writer.AddSourceLocation(TL.getNameLoc(), Record);
449 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
450 Writer.AddSourceLocation(TL.getNameLoc(), Record);
452 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
453 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
454 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
455 Record.push_back(TL.getTrailingReturn());
456 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
457 Writer.AddDeclRef(TL.getArg(i), Record);
459 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
460 VisitFunctionTypeLoc(TL);
462 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
463 VisitFunctionTypeLoc(TL);
465 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
466 Writer.AddSourceLocation(TL.getNameLoc(), Record);
468 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
469 Writer.AddSourceLocation(TL.getNameLoc(), Record);
471 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
472 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
473 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
474 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
476 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
477 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
478 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
479 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
480 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
482 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
483 Writer.AddSourceLocation(TL.getNameLoc(), Record);
485 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
486 Writer.AddSourceLocation(TL.getNameLoc(), Record);
488 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
489 Writer.AddSourceLocation(TL.getNameLoc(), Record);
491 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
492 Writer.AddSourceLocation(TL.getNameLoc(), Record);
494 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
495 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
496 if (TL.hasAttrOperand()) {
497 SourceRange range = TL.getAttrOperandParensRange();
498 Writer.AddSourceLocation(range.getBegin(), Record);
499 Writer.AddSourceLocation(range.getEnd(), Record);
501 if (TL.hasAttrExprOperand()) {
502 Expr *operand = TL.getAttrExprOperand();
503 Record.push_back(operand ? 1 : 0);
504 if (operand) Writer.AddStmt(operand);
505 } else if (TL.hasAttrEnumOperand()) {
506 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
509 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
510 Writer.AddSourceLocation(TL.getNameLoc(), Record);
512 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
513 SubstTemplateTypeParmTypeLoc TL) {
514 Writer.AddSourceLocation(TL.getNameLoc(), Record);
516 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
517 SubstTemplateTypeParmPackTypeLoc TL) {
518 Writer.AddSourceLocation(TL.getNameLoc(), Record);
520 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
521 TemplateSpecializationTypeLoc TL) {
522 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
523 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
524 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
525 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
526 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
527 TL.getArgLoc(i).getLocInfo(), Record);
529 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
530 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
531 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
533 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
534 Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
535 Writer.AddSourceRange(TL.getQualifierRange(), Record);
537 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
538 Writer.AddSourceLocation(TL.getNameLoc(), Record);
540 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
541 Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
542 Writer.AddSourceRange(TL.getQualifierRange(), Record);
543 Writer.AddSourceLocation(TL.getNameLoc(), Record);
545 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
546 DependentTemplateSpecializationTypeLoc TL) {
547 Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
548 Writer.AddSourceRange(TL.getQualifierRange(), Record);
549 Writer.AddSourceLocation(TL.getNameLoc(), Record);
550 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
551 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
552 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
553 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
554 TL.getArgLoc(I).getLocInfo(), Record);
556 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
557 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
559 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
560 Writer.AddSourceLocation(TL.getNameLoc(), Record);
562 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
563 Record.push_back(TL.hasBaseTypeAsWritten());
564 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
565 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
566 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
567 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
569 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
570 Writer.AddSourceLocation(TL.getStarLoc(), Record);
573 //===----------------------------------------------------------------------===//
574 // ASTWriter Implementation
575 //===----------------------------------------------------------------------===//
577 static void EmitBlockID(unsigned ID, const char *Name,
578 llvm::BitstreamWriter &Stream,
579 ASTWriter::RecordDataImpl &Record) {
581 Record.push_back(ID);
582 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
584 // Emit the block name if present.
585 if (Name == 0 || Name[0] == 0) return;
588 Record.push_back(*Name++);
589 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
592 static void EmitRecordID(unsigned ID, const char *Name,
593 llvm::BitstreamWriter &Stream,
594 ASTWriter::RecordDataImpl &Record) {
596 Record.push_back(ID);
598 Record.push_back(*Name++);
599 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
602 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
603 ASTWriter::RecordDataImpl &Record) {
604 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
606 RECORD(STMT_NULL_PTR);
608 RECORD(STMT_COMPOUND);
610 RECORD(STMT_DEFAULT);
618 RECORD(STMT_INDIRECT_GOTO);
619 RECORD(STMT_CONTINUE);
624 RECORD(EXPR_PREDEFINED);
625 RECORD(EXPR_DECL_REF);
626 RECORD(EXPR_INTEGER_LITERAL);
627 RECORD(EXPR_FLOATING_LITERAL);
628 RECORD(EXPR_IMAGINARY_LITERAL);
629 RECORD(EXPR_STRING_LITERAL);
630 RECORD(EXPR_CHARACTER_LITERAL);
632 RECORD(EXPR_UNARY_OPERATOR);
633 RECORD(EXPR_SIZEOF_ALIGN_OF);
634 RECORD(EXPR_ARRAY_SUBSCRIPT);
637 RECORD(EXPR_BINARY_OPERATOR);
638 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
639 RECORD(EXPR_CONDITIONAL_OPERATOR);
640 RECORD(EXPR_IMPLICIT_CAST);
641 RECORD(EXPR_CSTYLE_CAST);
642 RECORD(EXPR_COMPOUND_LITERAL);
643 RECORD(EXPR_EXT_VECTOR_ELEMENT);
644 RECORD(EXPR_INIT_LIST);
645 RECORD(EXPR_DESIGNATED_INIT);
646 RECORD(EXPR_IMPLICIT_VALUE_INIT);
648 RECORD(EXPR_ADDR_LABEL);
651 RECORD(EXPR_GNU_NULL);
652 RECORD(EXPR_SHUFFLE_VECTOR);
654 RECORD(EXPR_BLOCK_DECL_REF);
655 RECORD(EXPR_OBJC_STRING_LITERAL);
656 RECORD(EXPR_OBJC_ENCODE);
657 RECORD(EXPR_OBJC_SELECTOR_EXPR);
658 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
659 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
660 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
661 RECORD(EXPR_OBJC_KVC_REF_EXPR);
662 RECORD(EXPR_OBJC_MESSAGE_EXPR);
663 RECORD(STMT_OBJC_FOR_COLLECTION);
664 RECORD(STMT_OBJC_CATCH);
665 RECORD(STMT_OBJC_FINALLY);
666 RECORD(STMT_OBJC_AT_TRY);
667 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
668 RECORD(STMT_OBJC_AT_THROW);
669 RECORD(EXPR_CXX_OPERATOR_CALL);
670 RECORD(EXPR_CXX_CONSTRUCT);
671 RECORD(EXPR_CXX_STATIC_CAST);
672 RECORD(EXPR_CXX_DYNAMIC_CAST);
673 RECORD(EXPR_CXX_REINTERPRET_CAST);
674 RECORD(EXPR_CXX_CONST_CAST);
675 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
676 RECORD(EXPR_CXX_BOOL_LITERAL);
677 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
678 RECORD(EXPR_CXX_TYPEID_EXPR);
679 RECORD(EXPR_CXX_TYPEID_TYPE);
680 RECORD(EXPR_CXX_UUIDOF_EXPR);
681 RECORD(EXPR_CXX_UUIDOF_TYPE);
682 RECORD(EXPR_CXX_THIS);
683 RECORD(EXPR_CXX_THROW);
684 RECORD(EXPR_CXX_DEFAULT_ARG);
685 RECORD(EXPR_CXX_BIND_TEMPORARY);
686 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
687 RECORD(EXPR_CXX_NEW);
688 RECORD(EXPR_CXX_DELETE);
689 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
690 RECORD(EXPR_EXPR_WITH_CLEANUPS);
691 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
692 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
693 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
694 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
695 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
696 RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
697 RECORD(EXPR_CXX_NOEXCEPT);
698 RECORD(EXPR_OPAQUE_VALUE);
699 RECORD(EXPR_BINARY_TYPE_TRAIT);
700 RECORD(EXPR_PACK_EXPANSION);
701 RECORD(EXPR_SIZEOF_PACK);
702 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
703 RECORD(EXPR_CUDA_KERNEL_CALL);
707 void ASTWriter::WriteBlockInfoBlock() {
709 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
711 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
712 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
714 // AST Top-Level Block.
716 RECORD(ORIGINAL_FILE_NAME);
719 RECORD(LANGUAGE_OPTIONS);
721 RECORD(IDENTIFIER_OFFSET);
722 RECORD(IDENTIFIER_TABLE);
723 RECORD(EXTERNAL_DEFINITIONS);
724 RECORD(SPECIAL_TYPES);
726 RECORD(TENTATIVE_DEFINITIONS);
727 RECORD(UNUSED_FILESCOPED_DECLS);
728 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
729 RECORD(SELECTOR_OFFSETS);
731 RECORD(PP_COUNTER_VALUE);
732 RECORD(SOURCE_LOCATION_OFFSETS);
733 RECORD(SOURCE_LOCATION_PRELOADS);
735 RECORD(EXT_VECTOR_DECLS);
736 RECORD(VERSION_CONTROL_BRANCH_REVISION);
737 RECORD(MACRO_DEFINITION_OFFSETS);
738 RECORD(CHAINED_METADATA);
739 RECORD(REFERENCED_SELECTOR_POOL);
740 RECORD(TU_UPDATE_LEXICAL);
741 RECORD(REDECLS_UPDATE_LATEST);
742 RECORD(SEMA_DECL_REFS);
743 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
744 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
745 RECORD(DECL_REPLACEMENTS);
746 RECORD(UPDATE_VISIBLE);
747 RECORD(DECL_UPDATE_OFFSETS);
748 RECORD(DECL_UPDATES);
749 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
750 RECORD(DIAG_PRAGMA_MAPPINGS);
751 RECORD(CUDA_SPECIAL_DECL_REFS);
752 RECORD(HEADER_SEARCH_TABLE);
753 RECORD(FP_PRAGMA_OPTIONS);
754 RECORD(OPENCL_EXTENSIONS);
756 // SourceManager Block.
757 BLOCK(SOURCE_MANAGER_BLOCK);
758 RECORD(SM_SLOC_FILE_ENTRY);
759 RECORD(SM_SLOC_BUFFER_ENTRY);
760 RECORD(SM_SLOC_BUFFER_BLOB);
761 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
762 RECORD(SM_LINE_TABLE);
764 // Preprocessor Block.
765 BLOCK(PREPROCESSOR_BLOCK);
766 RECORD(PP_MACRO_OBJECT_LIKE);
767 RECORD(PP_MACRO_FUNCTION_LIKE);
770 // Decls and Types block.
771 BLOCK(DECLTYPES_BLOCK);
772 RECORD(TYPE_EXT_QUAL);
773 RECORD(TYPE_COMPLEX);
774 RECORD(TYPE_POINTER);
775 RECORD(TYPE_BLOCK_POINTER);
776 RECORD(TYPE_LVALUE_REFERENCE);
777 RECORD(TYPE_RVALUE_REFERENCE);
778 RECORD(TYPE_MEMBER_POINTER);
779 RECORD(TYPE_CONSTANT_ARRAY);
780 RECORD(TYPE_INCOMPLETE_ARRAY);
781 RECORD(TYPE_VARIABLE_ARRAY);
783 RECORD(TYPE_EXT_VECTOR);
784 RECORD(TYPE_FUNCTION_PROTO);
785 RECORD(TYPE_FUNCTION_NO_PROTO);
786 RECORD(TYPE_TYPEDEF);
787 RECORD(TYPE_TYPEOF_EXPR);
791 RECORD(TYPE_OBJC_INTERFACE);
792 RECORD(TYPE_OBJC_OBJECT);
793 RECORD(TYPE_OBJC_OBJECT_POINTER);
794 RECORD(TYPE_DECLTYPE);
795 RECORD(TYPE_ELABORATED);
796 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
797 RECORD(TYPE_UNRESOLVED_USING);
798 RECORD(TYPE_INJECTED_CLASS_NAME);
799 RECORD(TYPE_OBJC_OBJECT);
800 RECORD(TYPE_TEMPLATE_TYPE_PARM);
801 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
802 RECORD(TYPE_DEPENDENT_NAME);
803 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
804 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
806 RECORD(TYPE_PACK_EXPANSION);
807 RECORD(TYPE_ATTRIBUTED);
808 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
809 RECORD(DECL_TRANSLATION_UNIT);
810 RECORD(DECL_TYPEDEF);
813 RECORD(DECL_ENUM_CONSTANT);
814 RECORD(DECL_FUNCTION);
815 RECORD(DECL_OBJC_METHOD);
816 RECORD(DECL_OBJC_INTERFACE);
817 RECORD(DECL_OBJC_PROTOCOL);
818 RECORD(DECL_OBJC_IVAR);
819 RECORD(DECL_OBJC_AT_DEFS_FIELD);
820 RECORD(DECL_OBJC_CLASS);
821 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
822 RECORD(DECL_OBJC_CATEGORY);
823 RECORD(DECL_OBJC_CATEGORY_IMPL);
824 RECORD(DECL_OBJC_IMPLEMENTATION);
825 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
826 RECORD(DECL_OBJC_PROPERTY);
827 RECORD(DECL_OBJC_PROPERTY_IMPL);
830 RECORD(DECL_IMPLICIT_PARAM);
831 RECORD(DECL_PARM_VAR);
832 RECORD(DECL_FILE_SCOPE_ASM);
834 RECORD(DECL_CONTEXT_LEXICAL);
835 RECORD(DECL_CONTEXT_VISIBLE);
836 RECORD(DECL_NAMESPACE);
837 RECORD(DECL_NAMESPACE_ALIAS);
839 RECORD(DECL_USING_SHADOW);
840 RECORD(DECL_USING_DIRECTIVE);
841 RECORD(DECL_UNRESOLVED_USING_VALUE);
842 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
843 RECORD(DECL_LINKAGE_SPEC);
844 RECORD(DECL_CXX_RECORD);
845 RECORD(DECL_CXX_METHOD);
846 RECORD(DECL_CXX_CONSTRUCTOR);
847 RECORD(DECL_CXX_DESTRUCTOR);
848 RECORD(DECL_CXX_CONVERSION);
849 RECORD(DECL_ACCESS_SPEC);
851 RECORD(DECL_FRIEND_TEMPLATE);
852 RECORD(DECL_CLASS_TEMPLATE);
853 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
854 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
855 RECORD(DECL_FUNCTION_TEMPLATE);
856 RECORD(DECL_TEMPLATE_TYPE_PARM);
857 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
858 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
859 RECORD(DECL_STATIC_ASSERT);
860 RECORD(DECL_CXX_BASE_SPECIFIERS);
861 RECORD(DECL_INDIRECTFIELD);
862 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
864 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
865 RECORD(PPD_MACRO_INSTANTIATION);
866 RECORD(PPD_MACRO_DEFINITION);
867 RECORD(PPD_INCLUSION_DIRECTIVE);
869 // Statements and Exprs can occur in the Decls and Types block.
870 AddStmtsExprs(Stream, Record);
876 /// \brief Adjusts the given filename to only write out the portion of the
877 /// filename that is not part of the system root directory.
879 /// \param Filename the file name to adjust.
881 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
882 /// the returned filename will be adjusted by this system root.
884 /// \returns either the original filename (if it needs no adjustment) or the
885 /// adjusted filename (which points into the @p Filename parameter).
887 adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
888 assert(Filename && "No file name to adjust?");
893 // Verify that the filename and the system root have the same prefix.
895 for (; Filename[Pos] && isysroot[Pos]; ++Pos)
896 if (Filename[Pos] != isysroot[Pos])
897 return Filename; // Prefixes don't match.
899 // We hit the end of the filename before we hit the end of the system root.
903 // If the file name has a '/' at the current position, skip over the '/'.
904 // We distinguish sysroot-based includes from absolute includes by the
905 // absence of '/' at the beginning of sysroot-based includes.
906 if (Filename[Pos] == '/')
909 return Filename + Pos;
912 /// \brief Write the AST metadata (e.g., i686-apple-darwin9).
913 void ASTWriter::WriteMetadata(ASTContext &Context, const char *isysroot,
914 const std::string &OutputFile) {
915 using namespace llvm;
918 const TargetInfo &Target = Context.Target;
919 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
920 MetaAbbrev->Add(BitCodeAbbrevOp(
921 Chain ? CHAINED_METADATA : METADATA));
922 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major
923 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor
924 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
925 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
926 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
927 // Target triple or chained PCH name
928 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
929 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
932 Record.push_back(Chain ? CHAINED_METADATA : METADATA);
933 Record.push_back(VERSION_MAJOR);
934 Record.push_back(VERSION_MINOR);
935 Record.push_back(CLANG_VERSION_MAJOR);
936 Record.push_back(CLANG_VERSION_MINOR);
937 Record.push_back(isysroot != 0);
938 // FIXME: This writes the absolute path for chained headers.
939 const std::string &BlobStr = Chain ? Chain->getFileName() : Target.getTriple().getTriple();
940 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, BlobStr);
942 // Original file name
943 SourceManager &SM = Context.getSourceManager();
944 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
945 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
946 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME));
947 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
948 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
950 llvm::SmallString<128> MainFilePath(MainFile->getName());
952 llvm::sys::fs::make_absolute(MainFilePath);
954 const char *MainFileNameStr = MainFilePath.c_str();
955 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
958 Record.push_back(ORIGINAL_FILE_NAME);
959 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
962 // Original PCH directory
963 if (!OutputFile.empty() && OutputFile != "-") {
964 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
965 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
966 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
967 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
969 llvm::SmallString<128> OutputPath(OutputFile);
971 llvm::sys::fs::make_absolute(OutputPath);
972 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
975 Record.push_back(ORIGINAL_PCH_DIR);
976 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
979 // Repository branch/version information.
980 BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev();
981 RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION));
982 RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
983 unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev);
985 Record.push_back(VERSION_CONTROL_BRANCH_REVISION);
986 Stream.EmitRecordWithBlob(RepoAbbrevCode, Record,
987 getClangFullRepositoryVersion());
990 /// \brief Write the LangOptions structure.
991 void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
993 Record.push_back(LangOpts.Trigraphs);
994 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
995 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
996 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
997 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
998 Record.push_back(LangOpts.GNUKeywords); // Allow GNU-extension keywords
999 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
1000 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
1001 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
1002 Record.push_back(LangOpts.C99); // C99 Support
1003 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
1004 // LangOpts.MSCVersion is ignored because all it does it set a macro, which is
1005 // already saved elsewhere.
1006 Record.push_back(LangOpts.CPlusPlus); // C++ Support
1007 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
1008 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
1010 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
1011 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
1012 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C
1013 // modern abi enabled.
1014 Record.push_back(LangOpts.ObjCNonFragileABI2); // Objective-C enhanced
1015 // modern abi enabled.
1016 Record.push_back(LangOpts.AppleKext); // Apple's kernel extensions ABI
1017 Record.push_back(LangOpts.ObjCDefaultSynthProperties); // Objective-C auto-synthesized
1018 // properties enabled.
1019 Record.push_back(LangOpts.NoConstantCFStrings); // non cfstring generation enabled..
1021 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
1022 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
1023 Record.push_back(LangOpts.LaxVectorConversions);
1024 Record.push_back(LangOpts.AltiVec);
1025 Record.push_back(LangOpts.Exceptions); // Support exception handling.
1026 Record.push_back(LangOpts.ObjCExceptions);
1027 Record.push_back(LangOpts.CXXExceptions);
1028 Record.push_back(LangOpts.SjLjExceptions);
1030 Record.push_back(LangOpts.MSBitfields); // MS-compatible structure layout
1031 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
1032 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
1033 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
1035 // Whether static initializers are protected by locks.
1036 Record.push_back(LangOpts.ThreadsafeStatics);
1037 Record.push_back(LangOpts.POSIXThreads);
1038 Record.push_back(LangOpts.Blocks); // block extension to C
1039 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
1041 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
1042 // (modulo the platform support).
1044 Record.push_back(LangOpts.getSignedOverflowBehavior());
1045 Record.push_back(LangOpts.HeinousExtensions);
1047 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
1048 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
1050 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
1051 // opposed to __DYNAMIC__).
1052 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
1054 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
1055 // used (instead of C99 semantics).
1056 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
1057 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
1059 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
1061 Record.push_back(LangOpts.ShortWChar); // force wchar_t to be unsigned short
1062 Record.push_back(LangOpts.ShortEnums); // Should the enum type be equivalent
1063 // to the smallest integer type with
1065 Record.push_back(LangOpts.getGCMode());
1066 Record.push_back(LangOpts.getVisibilityMode());
1067 Record.push_back(LangOpts.getStackProtectorMode());
1068 Record.push_back(LangOpts.InstantiationDepth);
1069 Record.push_back(LangOpts.OpenCL);
1070 Record.push_back(LangOpts.CUDA);
1071 Record.push_back(LangOpts.CatchUndefined);
1072 Record.push_back(LangOpts.DefaultFPContract);
1073 Record.push_back(LangOpts.ElideConstructors);
1074 Record.push_back(LangOpts.SpellChecking);
1075 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1078 //===----------------------------------------------------------------------===//
1079 // stat cache Serialization
1080 //===----------------------------------------------------------------------===//
1083 // Trait used for the on-disk hash table of stat cache results.
1084 class ASTStatCacheTrait {
1086 typedef const char * key_type;
1087 typedef key_type key_type_ref;
1089 typedef struct stat data_type;
1090 typedef const data_type &data_type_ref;
1092 static unsigned ComputeHash(const char *path) {
1093 return llvm::HashString(path);
1096 std::pair<unsigned,unsigned>
1097 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
1098 data_type_ref Data) {
1099 unsigned StrLen = strlen(path);
1100 clang::io::Emit16(Out, StrLen);
1101 unsigned DataLen = 4 + 4 + 2 + 8 + 8;
1102 clang::io::Emit8(Out, DataLen);
1103 return std::make_pair(StrLen + 1, DataLen);
1106 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
1107 Out.write(path, KeyLen);
1110 void EmitData(llvm::raw_ostream &Out, key_type_ref,
1111 data_type_ref Data, unsigned DataLen) {
1112 using namespace clang::io;
1113 uint64_t Start = Out.tell(); (void)Start;
1115 Emit32(Out, (uint32_t) Data.st_ino);
1116 Emit32(Out, (uint32_t) Data.st_dev);
1117 Emit16(Out, (uint16_t) Data.st_mode);
1118 Emit64(Out, (uint64_t) Data.st_mtime);
1119 Emit64(Out, (uint64_t) Data.st_size);
1121 assert(Out.tell() - Start == DataLen && "Wrong data length");
1124 } // end anonymous namespace
1126 /// \brief Write the stat() system call cache to the AST file.
1127 void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
1128 // Build the on-disk hash table containing information about every
1130 OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator;
1131 unsigned NumStatEntries = 0;
1132 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
1133 StatEnd = StatCalls.end();
1134 Stat != StatEnd; ++Stat, ++NumStatEntries) {
1135 const char *Filename = Stat->first();
1136 Generator.insert(Filename, Stat->second);
1139 // Create the on-disk hash table in a buffer.
1140 llvm::SmallString<4096> StatCacheData;
1141 uint32_t BucketOffset;
1143 llvm::raw_svector_ostream Out(StatCacheData);
1144 // Make sure that no bucket is at offset 0
1145 clang::io::Emit32(Out, 0);
1146 BucketOffset = Generator.Emit(Out);
1149 // Create a blob abbreviation
1150 using namespace llvm;
1151 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1152 Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE));
1153 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1154 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1155 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1156 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
1158 // Write the stat cache
1160 Record.push_back(STAT_CACHE);
1161 Record.push_back(BucketOffset);
1162 Record.push_back(NumStatEntries);
1163 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
1166 //===----------------------------------------------------------------------===//
1167 // Source Manager Serialization
1168 //===----------------------------------------------------------------------===//
1170 /// \brief Create an abbreviation for the SLocEntry that refers to a
1172 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1173 using namespace llvm;
1174 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1175 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1176 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1177 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1178 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1179 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1180 // FileEntry fields.
1181 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1182 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1183 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1184 return Stream.EmitAbbrev(Abbrev);
1187 /// \brief Create an abbreviation for the SLocEntry that refers to a
1189 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1190 using namespace llvm;
1191 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1192 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1193 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1194 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1195 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1196 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1197 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1198 return Stream.EmitAbbrev(Abbrev);
1201 /// \brief Create an abbreviation for the SLocEntry that refers to a
1203 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1204 using namespace llvm;
1205 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1206 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1207 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1208 return Stream.EmitAbbrev(Abbrev);
1211 /// \brief Create an abbreviation for the SLocEntry that refers to an
1213 static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
1214 using namespace llvm;
1215 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1216 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_INSTANTIATION_ENTRY));
1217 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1218 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1219 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1220 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1221 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1222 return Stream.EmitAbbrev(Abbrev);
1226 // Trait used for the on-disk hash table of header search information.
1227 class HeaderFileInfoTrait {
1232 HeaderFileInfoTrait(ASTWriter &Writer, HeaderSearch &HS)
1233 : Writer(Writer), HS(HS) { }
1235 typedef const char *key_type;
1236 typedef key_type key_type_ref;
1238 typedef HeaderFileInfo data_type;
1239 typedef const data_type &data_type_ref;
1241 static unsigned ComputeHash(const char *path) {
1242 // The hash is based only on the filename portion of the key, so that the
1243 // reader can match based on filenames when symlinking or excess path
1244 // elements ("foo/../", "../") change the form of the name. However,
1245 // complete path is still the key.
1246 return llvm::HashString(llvm::sys::path::filename(path));
1249 std::pair<unsigned,unsigned>
1250 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
1251 data_type_ref Data) {
1252 unsigned StrLen = strlen(path);
1253 clang::io::Emit16(Out, StrLen);
1254 unsigned DataLen = 1 + 2 + 4;
1255 clang::io::Emit8(Out, DataLen);
1256 return std::make_pair(StrLen + 1, DataLen);
1259 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
1260 Out.write(path, KeyLen);
1263 void EmitData(llvm::raw_ostream &Out, key_type_ref,
1264 data_type_ref Data, unsigned DataLen) {
1265 using namespace clang::io;
1266 uint64_t Start = Out.tell(); (void)Start;
1268 unsigned char Flags = (Data.isImport << 3)
1269 | (Data.DirInfo << 1)
1271 Emit8(Out, (uint8_t)Flags);
1272 Emit16(Out, (uint16_t) Data.NumIncludes);
1274 if (!Data.ControllingMacro)
1275 Emit32(Out, (uint32_t)Data.ControllingMacroID);
1277 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
1278 assert(Out.tell() - Start == DataLen && "Wrong data length");
1281 } // end anonymous namespace
1283 /// \brief Write the header search block for the list of files that
1285 /// \param HS The header search structure to save.
1287 /// \param Chain Whether we're creating a chained AST file.
1288 void ASTWriter::WriteHeaderSearch(HeaderSearch &HS, const char* isysroot) {
1289 llvm::SmallVector<const FileEntry *, 16> FilesByUID;
1290 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1292 if (FilesByUID.size() > HS.header_file_size())
1293 FilesByUID.resize(HS.header_file_size());
1295 HeaderFileInfoTrait GeneratorTrait(*this, HS);
1296 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1297 llvm::SmallVector<const char *, 4> SavedStrings;
1298 unsigned NumHeaderSearchEntries = 0;
1299 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1300 const FileEntry *File = FilesByUID[UID];
1304 const HeaderFileInfo &HFI = HS.header_file_begin()[UID];
1305 if (HFI.External && Chain)
1308 // Turn the file name into an absolute path, if it isn't already.
1309 const char *Filename = File->getName();
1310 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1312 // If we performed any translation on the file name at all, we need to
1313 // save this string, since the generator will refer to it later.
1314 if (Filename != File->getName()) {
1315 Filename = strdup(Filename);
1316 SavedStrings.push_back(Filename);
1319 Generator.insert(Filename, HFI, GeneratorTrait);
1320 ++NumHeaderSearchEntries;
1323 // Create the on-disk hash table in a buffer.
1324 llvm::SmallString<4096> TableData;
1325 uint32_t BucketOffset;
1327 llvm::raw_svector_ostream Out(TableData);
1328 // Make sure that no bucket is at offset 0
1329 clang::io::Emit32(Out, 0);
1330 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1333 // Create a blob abbreviation
1334 using namespace llvm;
1335 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1336 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1337 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1338 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1339 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1340 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1342 // Write the stat cache
1344 Record.push_back(HEADER_SEARCH_TABLE);
1345 Record.push_back(BucketOffset);
1346 Record.push_back(NumHeaderSearchEntries);
1347 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1349 // Free all of the strings we had to duplicate.
1350 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1351 free((void*)SavedStrings[I]);
1354 /// \brief Writes the block containing the serialized form of the
1357 /// TODO: We should probably use an on-disk hash table (stored in a
1358 /// blob), indexed based on the file name, so that we only create
1359 /// entries for files that we actually need. In the common case (no
1360 /// errors), we probably won't have to create file entries for any of
1361 /// the files in the AST.
1362 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1363 const Preprocessor &PP,
1364 const char *isysroot) {
1367 // Enter the source manager block.
1368 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1370 // Abbreviations for the various kinds of source-location entries.
1371 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1372 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1373 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1374 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
1376 // Write the line table.
1377 if (SourceMgr.hasLineTable()) {
1378 LineTableInfo &LineTable = SourceMgr.getLineTable();
1380 // Emit the file names
1381 Record.push_back(LineTable.getNumFilenames());
1382 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1383 // Emit the file name
1384 const char *Filename = LineTable.getFilename(I);
1385 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1386 unsigned FilenameLen = Filename? strlen(Filename) : 0;
1387 Record.push_back(FilenameLen);
1389 Record.insert(Record.end(), Filename, Filename + FilenameLen);
1392 // Emit the line entries
1393 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1396 Record.push_back(L->first);
1398 // Emit the line entries
1399 Record.push_back(L->second.size());
1400 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1401 LEEnd = L->second.end();
1402 LE != LEEnd; ++LE) {
1403 Record.push_back(LE->FileOffset);
1404 Record.push_back(LE->LineNo);
1405 Record.push_back(LE->FilenameID);
1406 Record.push_back((unsigned)LE->FileKind);
1407 Record.push_back(LE->IncludeOffset);
1410 Stream.EmitRecord(SM_LINE_TABLE, Record);
1413 // Write out the source location entry table. We skip the first
1414 // entry, which is always the same dummy entry.
1415 std::vector<uint32_t> SLocEntryOffsets;
1416 RecordData PreloadSLocs;
1417 unsigned BaseSLocID = Chain ? Chain->getTotalNumSLocs() : 0;
1418 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1 - BaseSLocID);
1419 for (unsigned I = BaseSLocID + 1, N = SourceMgr.sloc_entry_size();
1421 // Get this source location entry.
1422 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getSLocEntry(I);
1424 // Record the offset of this source-location entry.
1425 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1427 // Figure out which record code to use.
1429 if (SLoc->isFile()) {
1430 if (SLoc->getFile().getContentCache()->Entry)
1431 Code = SM_SLOC_FILE_ENTRY;
1433 Code = SM_SLOC_BUFFER_ENTRY;
1435 Code = SM_SLOC_INSTANTIATION_ENTRY;
1437 Record.push_back(Code);
1439 Record.push_back(SLoc->getOffset());
1440 if (SLoc->isFile()) {
1441 const SrcMgr::FileInfo &File = SLoc->getFile();
1442 Record.push_back(File.getIncludeLoc().getRawEncoding());
1443 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1444 Record.push_back(File.hasLineDirectives());
1446 const SrcMgr::ContentCache *Content = File.getContentCache();
1447 if (Content->Entry) {
1448 // The source location entry is a file. The blob associated
1449 // with this entry is the file name.
1451 // Emit size/modification time for this file.
1452 Record.push_back(Content->Entry->getSize());
1453 Record.push_back(Content->Entry->getModificationTime());
1455 // Turn the file name into an absolute path, if it isn't already.
1456 const char *Filename = Content->Entry->getName();
1457 llvm::SmallString<128> FilePath(Filename);
1458 llvm::sys::fs::make_absolute(FilePath);
1459 Filename = FilePath.c_str();
1461 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1462 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
1464 // The source location entry is a buffer. The blob associated
1465 // with this entry contains the contents of the buffer.
1467 // We add one to the size so that we capture the trailing NULL
1468 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1469 // the reader side).
1470 const llvm::MemoryBuffer *Buffer
1471 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1472 const char *Name = Buffer->getBufferIdentifier();
1473 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1474 llvm::StringRef(Name, strlen(Name) + 1));
1476 Record.push_back(SM_SLOC_BUFFER_BLOB);
1477 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1478 llvm::StringRef(Buffer->getBufferStart(),
1479 Buffer->getBufferSize() + 1));
1481 if (strcmp(Name, "<built-in>") == 0)
1482 PreloadSLocs.push_back(BaseSLocID + SLocEntryOffsets.size());
1485 // The source location entry is an instantiation.
1486 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
1487 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
1488 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
1489 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
1491 // Compute the token length for this macro expansion.
1492 unsigned NextOffset = SourceMgr.getNextOffset();
1494 NextOffset = SourceMgr.getSLocEntry(I + 1).getOffset();
1495 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1496 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
1502 if (SLocEntryOffsets.empty())
1505 // Write the source-location offsets table into the AST block. This
1506 // table is used for lazily loading source-location information.
1507 using namespace llvm;
1508 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1509 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1510 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1511 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
1512 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1513 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1516 Record.push_back(SOURCE_LOCATION_OFFSETS);
1517 Record.push_back(SLocEntryOffsets.size());
1518 unsigned BaseOffset = Chain ? Chain->getNextSLocOffset() : 0;
1519 Record.push_back(SourceMgr.getNextOffset() - BaseOffset);
1520 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
1521 (const char *)data(SLocEntryOffsets),
1522 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
1524 // Write the source location entry preloads array, telling the AST
1525 // reader which source locations entries it should load eagerly.
1526 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1529 //===----------------------------------------------------------------------===//
1530 // Preprocessor Serialization
1531 //===----------------------------------------------------------------------===//
1533 static int compareMacroDefinitions(const void *XPtr, const void *YPtr) {
1534 const std::pair<const IdentifierInfo *, MacroInfo *> &X =
1535 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr;
1536 const std::pair<const IdentifierInfo *, MacroInfo *> &Y =
1537 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr;
1538 return X.first->getName().compare(Y.first->getName());
1541 /// \brief Writes the block containing the serialized form of the
1544 void ASTWriter::WritePreprocessor(const Preprocessor &PP) {
1547 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1548 if (PP.getCounterValue() != 0) {
1549 Record.push_back(PP.getCounterValue());
1550 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1554 // Enter the preprocessor block.
1555 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1557 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1558 // FIXME: use diagnostics subsystem for localization etc.
1559 if (PP.SawDateOrTime())
1560 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1563 // Loop over all the macro definitions that are live at the end of the file,
1564 // emitting each to the PP section.
1565 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1567 // Construct the list of macro definitions that need to be serialized.
1568 llvm::SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2>
1570 llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen;
1571 for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0),
1572 E = PP.macro_end(Chain == 0);
1574 MacroDefinitionsSeen.insert(I->first);
1575 MacrosToEmit.push_back(std::make_pair(I->first, I->second));
1578 // Sort the set of macro definitions that need to be serialized by the
1579 // name of the macro, to provide a stable ordering.
1580 llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(),
1581 &compareMacroDefinitions);
1583 // Resolve any identifiers that defined macros at the time they were
1584 // deserialized, adding them to the list of macros to emit (if appropriate).
1585 for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) {
1586 IdentifierInfo *Name
1587 = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]);
1588 if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name))
1589 MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name)));
1592 for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) {
1593 const IdentifierInfo *Name = MacrosToEmit[I].first;
1594 MacroInfo *MI = MacrosToEmit[I].second;
1598 // Don't emit builtin macros like __LINE__ to the AST file unless they have
1599 // been redefined by the header (in which case they are not isBuiltinMacro).
1600 // Also skip macros from a AST file if we're chaining.
1602 // FIXME: There is a (probably minor) optimization we could do here, if
1603 // the macro comes from the original PCH but the identifier comes from a
1604 // chained PCH, by storing the offset into the original PCH rather than
1605 // writing the macro definition a second time.
1606 if (MI->isBuiltinMacro() ||
1607 (Chain && Name->isFromAST() && MI->isFromAST()))
1610 AddIdentifierRef(Name, Record);
1611 MacroOffsets[Name] = Stream.GetCurrentBitNo();
1612 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1613 Record.push_back(MI->isUsed());
1616 if (MI->isObjectLike()) {
1617 Code = PP_MACRO_OBJECT_LIKE;
1619 Code = PP_MACRO_FUNCTION_LIKE;
1621 Record.push_back(MI->isC99Varargs());
1622 Record.push_back(MI->isGNUVarargs());
1623 Record.push_back(MI->getNumArgs());
1624 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1626 AddIdentifierRef(*I, Record);
1629 // If we have a detailed preprocessing record, record the macro definition
1630 // ID that corresponds to this macro.
1632 Record.push_back(getMacroDefinitionID(PPRec->findMacroDefinition(MI)));
1634 Stream.EmitRecord(Code, Record);
1637 // Emit the tokens array.
1638 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1639 // Note that we know that the preprocessor does not have any annotation
1640 // tokens in it because they are created by the parser, and thus can't be
1641 // in a macro definition.
1642 const Token &Tok = MI->getReplacementToken(TokNo);
1644 Record.push_back(Tok.getLocation().getRawEncoding());
1645 Record.push_back(Tok.getLength());
1647 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1649 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
1650 // FIXME: Should translate token kind to a stable encoding.
1651 Record.push_back(Tok.getKind());
1652 // FIXME: Should translate token flags to a stable encoding.
1653 Record.push_back(Tok.getFlags());
1655 Stream.EmitRecord(PP_TOKEN, Record);
1663 WritePreprocessorDetail(*PPRec);
1666 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
1667 if (PPRec.begin(Chain) == PPRec.end(Chain))
1670 // Enter the preprocessor block.
1671 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
1673 // If the preprocessor has a preprocessing record, emit it.
1674 unsigned NumPreprocessingRecords = 0;
1675 using namespace llvm;
1677 // Set up the abbreviation for
1678 unsigned InclusionAbbrev = 0;
1680 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1681 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
1682 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1683 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // start location
1684 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // end location
1685 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
1686 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
1687 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
1688 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1689 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
1692 unsigned IndexBase = Chain ? PPRec.getNumPreallocatedEntities() : 0;
1694 for (PreprocessingRecord::iterator E = PPRec.begin(Chain),
1695 EEnd = PPRec.end(Chain);
1699 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
1700 // Record this macro definition's location.
1701 MacroID ID = getMacroDefinitionID(MD);
1703 // Don't write the macro definition if it is from another AST file.
1704 if (ID < FirstMacroID)
1707 // Notify the serialization listener that we're serializing this entity.
1708 if (SerializationListener)
1709 SerializationListener->SerializedPreprocessedEntity(*E,
1710 Stream.GetCurrentBitNo());
1712 unsigned Position = ID - FirstMacroID;
1713 if (Position != MacroDefinitionOffsets.size()) {
1714 if (Position > MacroDefinitionOffsets.size())
1715 MacroDefinitionOffsets.resize(Position + 1);
1717 MacroDefinitionOffsets[Position] = Stream.GetCurrentBitNo();
1719 MacroDefinitionOffsets.push_back(Stream.GetCurrentBitNo());
1721 Record.push_back(IndexBase + NumPreprocessingRecords++);
1722 Record.push_back(ID);
1723 AddSourceLocation(MD->getSourceRange().getBegin(), Record);
1724 AddSourceLocation(MD->getSourceRange().getEnd(), Record);
1725 AddIdentifierRef(MD->getName(), Record);
1726 AddSourceLocation(MD->getLocation(), Record);
1727 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
1731 // Notify the serialization listener that we're serializing this entity.
1732 if (SerializationListener)
1733 SerializationListener->SerializedPreprocessedEntity(*E,
1734 Stream.GetCurrentBitNo());
1736 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
1737 Record.push_back(IndexBase + NumPreprocessingRecords++);
1738 AddSourceLocation(MI->getSourceRange().getBegin(), Record);
1739 AddSourceLocation(MI->getSourceRange().getEnd(), Record);
1740 AddIdentifierRef(MI->getName(), Record);
1741 Record.push_back(getMacroDefinitionID(MI->getDefinition()));
1742 Stream.EmitRecord(PPD_MACRO_INSTANTIATION, Record);
1746 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
1747 Record.push_back(PPD_INCLUSION_DIRECTIVE);
1748 Record.push_back(IndexBase + NumPreprocessingRecords++);
1749 AddSourceLocation(ID->getSourceRange().getBegin(), Record);
1750 AddSourceLocation(ID->getSourceRange().getEnd(), Record);
1751 Record.push_back(ID->getFileName().size());
1752 Record.push_back(ID->wasInQuotes());
1753 Record.push_back(static_cast<unsigned>(ID->getKind()));
1754 llvm::SmallString<64> Buffer;
1755 Buffer += ID->getFileName();
1756 Buffer += ID->getFile()->getName();
1757 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
1761 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
1765 // Write the offsets table for the preprocessing record.
1766 if (NumPreprocessingRecords > 0) {
1767 // Write the offsets table for identifier IDs.
1768 using namespace llvm;
1769 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1770 Abbrev->Add(BitCodeAbbrevOp(MACRO_DEFINITION_OFFSETS));
1771 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of records
1772 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macro defs
1773 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1774 unsigned MacroDefOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1777 Record.push_back(MACRO_DEFINITION_OFFSETS);
1778 Record.push_back(NumPreprocessingRecords);
1779 Record.push_back(MacroDefinitionOffsets.size());
1780 Stream.EmitRecordWithBlob(MacroDefOffsetAbbrev, Record,
1781 (const char *)data(MacroDefinitionOffsets),
1782 MacroDefinitionOffsets.size() * sizeof(uint32_t));
1786 void ASTWriter::WritePragmaDiagnosticMappings(const Diagnostic &Diag) {
1788 for (Diagnostic::DiagStatePointsTy::const_iterator
1789 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
1791 const Diagnostic::DiagStatePoint &point = *I;
1792 if (point.Loc.isInvalid())
1795 Record.push_back(point.Loc.getRawEncoding());
1796 for (Diagnostic::DiagState::iterator
1797 I = point.State->begin(), E = point.State->end(); I != E; ++I) {
1798 unsigned diag = I->first, map = I->second;
1799 if (map & 0x10) { // mapping from a diagnostic pragma.
1800 Record.push_back(diag);
1801 Record.push_back(map & 0x7);
1804 Record.push_back(-1); // mark the end of the diag/map pairs for this
1808 if (!Record.empty())
1809 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
1812 //===----------------------------------------------------------------------===//
1813 // Type Serialization
1814 //===----------------------------------------------------------------------===//
1816 /// \brief Write the representation of a type to the AST stream.
1817 void ASTWriter::WriteType(QualType T) {
1818 TypeIdx &Idx = TypeIdxs[T];
1819 if (Idx.getIndex() == 0) // we haven't seen this type before.
1820 Idx = TypeIdx(NextTypeID++);
1822 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
1824 // Record the offset for this type.
1825 unsigned Index = Idx.getIndex() - FirstTypeID;
1826 if (TypeOffsets.size() == Index)
1827 TypeOffsets.push_back(Stream.GetCurrentBitNo());
1828 else if (TypeOffsets.size() < Index) {
1829 TypeOffsets.resize(Index + 1);
1830 TypeOffsets[Index] = Stream.GetCurrentBitNo();
1835 // Emit the type's representation.
1836 ASTTypeWriter W(*this, Record);
1838 if (T.hasLocalNonFastQualifiers()) {
1839 Qualifiers Qs = T.getLocalQualifiers();
1840 AddTypeRef(T.getLocalUnqualifiedType(), Record);
1841 Record.push_back(Qs.getAsOpaqueValue());
1842 W.Code = TYPE_EXT_QUAL;
1844 switch (T->getTypeClass()) {
1845 // For all of the concrete, non-dependent types, call the
1846 // appropriate visitor function.
1847 #define TYPE(Class, Base) \
1848 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1849 #define ABSTRACT_TYPE(Class, Base)
1850 #include "clang/AST/TypeNodes.def"
1854 // Emit the serialized record.
1855 Stream.EmitRecord(W.Code, Record);
1857 // Flush any expressions that were written as part of this type.
1861 //===----------------------------------------------------------------------===//
1862 // Declaration Serialization
1863 //===----------------------------------------------------------------------===//
1865 /// \brief Write the block containing all of the declaration IDs
1866 /// lexically declared within the given DeclContext.
1868 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1869 /// bistream, or 0 if no block was written.
1870 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1872 if (DC->decls_empty())
1875 uint64_t Offset = Stream.GetCurrentBitNo();
1877 Record.push_back(DECL_CONTEXT_LEXICAL);
1878 llvm::SmallVector<KindDeclIDPair, 64> Decls;
1879 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1881 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
1883 ++NumLexicalDeclContexts;
1884 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
1885 reinterpret_cast<char*>(Decls.data()),
1886 Decls.size() * sizeof(KindDeclIDPair));
1890 void ASTWriter::WriteTypeDeclOffsets() {
1891 using namespace llvm;
1894 // Write the type offsets array
1895 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1896 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
1897 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1898 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1899 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1901 Record.push_back(TYPE_OFFSET);
1902 Record.push_back(TypeOffsets.size());
1903 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1904 (const char *)data(TypeOffsets),
1905 TypeOffsets.size() * sizeof(TypeOffsets[0]));
1907 // Write the declaration offsets array
1908 Abbrev = new BitCodeAbbrev();
1909 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
1910 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1911 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1912 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1914 Record.push_back(DECL_OFFSET);
1915 Record.push_back(DeclOffsets.size());
1916 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1917 (const char *)data(DeclOffsets),
1918 DeclOffsets.size() * sizeof(DeclOffsets[0]));
1921 //===----------------------------------------------------------------------===//
1922 // Global Method Pool and Selector Serialization
1923 //===----------------------------------------------------------------------===//
1926 // Trait used for the on-disk hash table used in the method pool.
1927 class ASTMethodPoolTrait {
1931 typedef Selector key_type;
1932 typedef key_type key_type_ref;
1936 ObjCMethodList Instance, Factory;
1938 typedef const data_type& data_type_ref;
1940 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
1942 static unsigned ComputeHash(Selector Sel) {
1943 return serialization::ComputeHash(Sel);
1946 std::pair<unsigned,unsigned>
1947 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1948 data_type_ref Methods) {
1949 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1950 clang::io::Emit16(Out, KeyLen);
1951 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
1952 for (const ObjCMethodList *Method = &Methods.Instance; Method;
1953 Method = Method->Next)
1956 for (const ObjCMethodList *Method = &Methods.Factory; Method;
1957 Method = Method->Next)
1960 clang::io::Emit16(Out, DataLen);
1961 return std::make_pair(KeyLen, DataLen);
1964 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1965 uint64_t Start = Out.tell();
1966 assert((Start >> 32) == 0 && "Selector key offset too large");
1967 Writer.SetSelectorOffset(Sel, Start);
1968 unsigned N = Sel.getNumArgs();
1969 clang::io::Emit16(Out, N);
1972 for (unsigned I = 0; I != N; ++I)
1973 clang::io::Emit32(Out,
1974 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1977 void EmitData(llvm::raw_ostream& Out, key_type_ref,
1978 data_type_ref Methods, unsigned DataLen) {
1979 uint64_t Start = Out.tell(); (void)Start;
1980 clang::io::Emit32(Out, Methods.ID);
1981 unsigned NumInstanceMethods = 0;
1982 for (const ObjCMethodList *Method = &Methods.Instance; Method;
1983 Method = Method->Next)
1985 ++NumInstanceMethods;
1987 unsigned NumFactoryMethods = 0;
1988 for (const ObjCMethodList *Method = &Methods.Factory; Method;
1989 Method = Method->Next)
1991 ++NumFactoryMethods;
1993 clang::io::Emit16(Out, NumInstanceMethods);
1994 clang::io::Emit16(Out, NumFactoryMethods);
1995 for (const ObjCMethodList *Method = &Methods.Instance; Method;
1996 Method = Method->Next)
1998 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
1999 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2000 Method = Method->Next)
2002 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2004 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2007 } // end anonymous namespace
2009 /// \brief Write ObjC data: selectors and the method pool.
2011 /// The method pool contains both instance and factory methods, stored
2012 /// in an on-disk hash table indexed by the selector. The hash table also
2013 /// contains an empty entry for every other selector known to Sema.
2014 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2015 using namespace llvm;
2017 // Do we have to do anything at all?
2018 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2020 unsigned NumTableEntries = 0;
2021 // Create and write out the blob that contains selectors and the method pool.
2023 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2024 ASTMethodPoolTrait Trait(*this);
2026 // Create the on-disk hash table representation. We walk through every
2027 // selector we've seen and look it up in the method pool.
2028 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2029 for (llvm::DenseMap<Selector, SelectorID>::iterator
2030 I = SelectorIDs.begin(), E = SelectorIDs.end();
2032 Selector S = I->first;
2033 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2034 ASTMethodPoolTrait::data_type Data = {
2039 if (F != SemaRef.MethodPool.end()) {
2040 Data.Instance = F->second.first;
2041 Data.Factory = F->second.second;
2043 // Only write this selector if it's not in an existing AST or something
2045 if (Chain && I->second < FirstSelectorID) {
2046 // Selector already exists. Did it change?
2047 bool changed = false;
2048 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
2050 if (M->Method->getPCHLevel() == 0)
2053 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
2055 if (M->Method->getPCHLevel() == 0)
2060 } else if (Data.Instance.Method || Data.Factory.Method) {
2061 // A new method pool entry.
2064 Generator.insert(S, Data, Trait);
2067 // Create the on-disk hash table in a buffer.
2068 llvm::SmallString<4096> MethodPool;
2069 uint32_t BucketOffset;
2071 ASTMethodPoolTrait Trait(*this);
2072 llvm::raw_svector_ostream Out(MethodPool);
2073 // Make sure that no bucket is at offset 0
2074 clang::io::Emit32(Out, 0);
2075 BucketOffset = Generator.Emit(Out, Trait);
2078 // Create a blob abbreviation
2079 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2080 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
2081 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2082 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2083 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2084 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
2086 // Write the method pool
2088 Record.push_back(METHOD_POOL);
2089 Record.push_back(BucketOffset);
2090 Record.push_back(NumTableEntries);
2091 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
2093 // Create a blob abbreviation for the selector table offsets.
2094 Abbrev = new BitCodeAbbrev();
2095 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
2096 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2097 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2098 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2100 // Write the selector offsets table.
2102 Record.push_back(SELECTOR_OFFSETS);
2103 Record.push_back(SelectorOffsets.size());
2104 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
2105 (const char *)data(SelectorOffsets),
2106 SelectorOffsets.size() * 4);
2110 /// \brief Write the selectors referenced in @selector expression into AST file.
2111 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
2112 using namespace llvm;
2113 if (SemaRef.ReferencedSelectors.empty())
2118 // Note: this writes out all references even for a dependent AST. But it is
2119 // very tricky to fix, and given that @selector shouldn't really appear in
2120 // headers, probably not worth it. It's not a correctness issue.
2121 for (DenseMap<Selector, SourceLocation>::iterator S =
2122 SemaRef.ReferencedSelectors.begin(),
2123 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
2124 Selector Sel = (*S).first;
2125 SourceLocation Loc = (*S).second;
2126 AddSelectorRef(Sel, Record);
2127 AddSourceLocation(Loc, Record);
2129 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
2132 //===----------------------------------------------------------------------===//
2133 // Identifier Table Serialization
2134 //===----------------------------------------------------------------------===//
2137 class ASTIdentifierTableTrait {
2141 /// \brief Determines whether this is an "interesting" identifier
2142 /// that needs a full IdentifierInfo structure written into the hash
2144 static bool isInterestingIdentifier(const IdentifierInfo *II) {
2145 return II->isPoisoned() ||
2146 II->isExtensionToken() ||
2147 II->hasMacroDefinition() ||
2148 II->getObjCOrBuiltinID() ||
2149 II->getFETokenInfo<void>();
2153 typedef const IdentifierInfo* key_type;
2154 typedef key_type key_type_ref;
2156 typedef IdentID data_type;
2157 typedef data_type data_type_ref;
2159 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP)
2160 : Writer(Writer), PP(PP) { }
2162 static unsigned ComputeHash(const IdentifierInfo* II) {
2163 return llvm::HashString(II->getName());
2166 std::pair<unsigned,unsigned>
2167 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
2169 unsigned KeyLen = II->getLength() + 1;
2170 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
2171 if (isInterestingIdentifier(II)) {
2172 DataLen += 2; // 2 bytes for builtin ID, flags
2173 if (II->hasMacroDefinition() &&
2174 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
2176 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
2177 DEnd = IdentifierResolver::end();
2179 DataLen += sizeof(DeclID);
2181 clang::io::Emit16(Out, DataLen);
2182 // We emit the key length after the data length so that every
2183 // string is preceded by a 16-bit length. This matches the PTH
2184 // format for storing identifiers.
2185 clang::io::Emit16(Out, KeyLen);
2186 return std::make_pair(KeyLen, DataLen);
2189 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
2191 // Record the location of the key data. This is used when generating
2192 // the mapping from persistent IDs to strings.
2193 Writer.SetIdentifierOffset(II, Out.tell());
2194 Out.write(II->getNameStart(), KeyLen);
2197 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
2198 IdentID ID, unsigned) {
2199 if (!isInterestingIdentifier(II)) {
2200 clang::io::Emit32(Out, ID << 1);
2204 clang::io::Emit32(Out, (ID << 1) | 0x01);
2206 bool hasMacroDefinition =
2207 II->hasMacroDefinition() &&
2208 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
2209 Bits = (uint32_t)II->getObjCOrBuiltinID();
2210 Bits = (Bits << 1) | unsigned(hasMacroDefinition);
2211 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
2212 Bits = (Bits << 1) | unsigned(II->isPoisoned());
2213 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
2214 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
2215 clang::io::Emit16(Out, Bits);
2217 if (hasMacroDefinition)
2218 clang::io::Emit32(Out, Writer.getMacroOffset(II));
2220 // Emit the declaration IDs in reverse order, because the
2221 // IdentifierResolver provides the declarations as they would be
2222 // visible (e.g., the function "stat" would come before the struct
2223 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
2224 // adds declarations to the end of the list (so we need to see the
2225 // struct "status" before the function "status").
2226 // Only emit declarations that aren't from a chained PCH, though.
2227 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
2228 IdentifierResolver::end());
2229 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
2230 DEnd = Decls.rend();
2232 clang::io::Emit32(Out, Writer.getDeclID(*D));
2235 } // end anonymous namespace
2237 /// \brief Write the identifier table into the AST file.
2239 /// The identifier table consists of a blob containing string data
2240 /// (the actual identifiers themselves) and a separate "offsets" index
2241 /// that maps identifier IDs to locations within the blob.
2242 void ASTWriter::WriteIdentifierTable(Preprocessor &PP) {
2243 using namespace llvm;
2245 // Create and write out the blob that contains the identifier
2248 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
2249 ASTIdentifierTableTrait Trait(*this, PP);
2251 // Look for any identifiers that were named while processing the
2252 // headers, but are otherwise not needed. We add these to the hash
2253 // table to enable checking of the predefines buffer in the case
2254 // where the user adds new macro definitions when building the AST
2256 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
2257 IDEnd = PP.getIdentifierTable().end();
2259 getIdentifierRef(ID->second);
2261 // Create the on-disk hash table representation. We only store offsets
2262 // for identifiers that appear here for the first time.
2263 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
2264 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
2265 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
2266 ID != IDEnd; ++ID) {
2267 assert(ID->first && "NULL identifier in identifier table");
2268 if (!Chain || !ID->first->isFromAST())
2269 Generator.insert(ID->first, ID->second, Trait);
2272 // Create the on-disk hash table in a buffer.
2273 llvm::SmallString<4096> IdentifierTable;
2274 uint32_t BucketOffset;
2276 ASTIdentifierTableTrait Trait(*this, PP);
2277 llvm::raw_svector_ostream Out(IdentifierTable);
2278 // Make sure that no bucket is at offset 0
2279 clang::io::Emit32(Out, 0);
2280 BucketOffset = Generator.Emit(Out, Trait);
2283 // Create a blob abbreviation
2284 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2285 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
2286 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2287 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2288 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
2290 // Write the identifier table
2292 Record.push_back(IDENTIFIER_TABLE);
2293 Record.push_back(BucketOffset);
2294 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
2297 // Write the offsets table for identifier IDs.
2298 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2299 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
2300 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
2301 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2302 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2305 Record.push_back(IDENTIFIER_OFFSET);
2306 Record.push_back(IdentifierOffsets.size());
2307 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
2308 (const char *)data(IdentifierOffsets),
2309 IdentifierOffsets.size() * sizeof(uint32_t));
2312 //===----------------------------------------------------------------------===//
2313 // DeclContext's Name Lookup Table Serialization
2314 //===----------------------------------------------------------------------===//
2317 // Trait used for the on-disk hash table used in the method pool.
2318 class ASTDeclContextNameLookupTrait {
2322 typedef DeclarationName key_type;
2323 typedef key_type key_type_ref;
2325 typedef DeclContext::lookup_result data_type;
2326 typedef const data_type& data_type_ref;
2328 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
2330 unsigned ComputeHash(DeclarationName Name) {
2331 llvm::FoldingSetNodeID ID;
2332 ID.AddInteger(Name.getNameKind());
2334 switch (Name.getNameKind()) {
2335 case DeclarationName::Identifier:
2336 ID.AddString(Name.getAsIdentifierInfo()->getName());
2338 case DeclarationName::ObjCZeroArgSelector:
2339 case DeclarationName::ObjCOneArgSelector:
2340 case DeclarationName::ObjCMultiArgSelector:
2341 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
2343 case DeclarationName::CXXConstructorName:
2344 case DeclarationName::CXXDestructorName:
2345 case DeclarationName::CXXConversionFunctionName:
2346 ID.AddInteger(Writer.GetOrCreateTypeID(Name.getCXXNameType()));
2348 case DeclarationName::CXXOperatorName:
2349 ID.AddInteger(Name.getCXXOverloadedOperator());
2351 case DeclarationName::CXXLiteralOperatorName:
2352 ID.AddString(Name.getCXXLiteralIdentifier()->getName());
2353 case DeclarationName::CXXUsingDirective:
2357 return ID.ComputeHash();
2360 std::pair<unsigned,unsigned>
2361 EmitKeyDataLength(llvm::raw_ostream& Out, DeclarationName Name,
2362 data_type_ref Lookup) {
2363 unsigned KeyLen = 1;
2364 switch (Name.getNameKind()) {
2365 case DeclarationName::Identifier:
2366 case DeclarationName::ObjCZeroArgSelector:
2367 case DeclarationName::ObjCOneArgSelector:
2368 case DeclarationName::ObjCMultiArgSelector:
2369 case DeclarationName::CXXConstructorName:
2370 case DeclarationName::CXXDestructorName:
2371 case DeclarationName::CXXConversionFunctionName:
2372 case DeclarationName::CXXLiteralOperatorName:
2375 case DeclarationName::CXXOperatorName:
2378 case DeclarationName::CXXUsingDirective:
2381 clang::io::Emit16(Out, KeyLen);
2383 // 2 bytes for num of decls and 4 for each DeclID.
2384 unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first);
2385 clang::io::Emit16(Out, DataLen);
2387 return std::make_pair(KeyLen, DataLen);
2390 void EmitKey(llvm::raw_ostream& Out, DeclarationName Name, unsigned) {
2391 using namespace clang::io;
2393 assert(Name.getNameKind() < 0x100 && "Invalid name kind ?");
2394 Emit8(Out, Name.getNameKind());
2395 switch (Name.getNameKind()) {
2396 case DeclarationName::Identifier:
2397 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
2399 case DeclarationName::ObjCZeroArgSelector:
2400 case DeclarationName::ObjCOneArgSelector:
2401 case DeclarationName::ObjCMultiArgSelector:
2402 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
2404 case DeclarationName::CXXConstructorName:
2405 case DeclarationName::CXXDestructorName:
2406 case DeclarationName::CXXConversionFunctionName:
2407 Emit32(Out, Writer.getTypeID(Name.getCXXNameType()));
2409 case DeclarationName::CXXOperatorName:
2410 assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?");
2411 Emit8(Out, Name.getCXXOverloadedOperator());
2413 case DeclarationName::CXXLiteralOperatorName:
2414 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
2416 case DeclarationName::CXXUsingDirective:
2421 void EmitData(llvm::raw_ostream& Out, key_type_ref,
2422 data_type Lookup, unsigned DataLen) {
2423 uint64_t Start = Out.tell(); (void)Start;
2424 clang::io::Emit16(Out, Lookup.second - Lookup.first);
2425 for (; Lookup.first != Lookup.second; ++Lookup.first)
2426 clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first));
2428 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2431 } // end anonymous namespace
2433 /// \brief Write the block containing all of the declaration IDs
2434 /// visible from the given DeclContext.
2436 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
2437 /// bitstream, or 0 if no block was written.
2438 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
2440 if (DC->getPrimaryContext() != DC)
2443 // Since there is no name lookup into functions or methods, don't bother to
2444 // build a visible-declarations table for these entities.
2445 if (DC->isFunctionOrMethod())
2448 // If not in C++, we perform name lookup for the translation unit via the
2449 // IdentifierInfo chains, don't bother to build a visible-declarations table.
2450 // FIXME: In C++ we need the visible declarations in order to "see" the
2451 // friend declarations, is there a way to do this without writing the table ?
2452 if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus)
2455 // Force the DeclContext to build a its name-lookup table.
2456 if (DC->hasExternalVisibleStorage())
2457 DC->MaterializeVisibleDeclsFromExternalStorage();
2459 DC->lookup(DeclarationName());
2461 // Serialize the contents of the mapping used for lookup. Note that,
2462 // although we have two very different code paths, the serialized
2463 // representation is the same for both cases: a declaration name,
2464 // followed by a size, followed by references to the visible
2465 // declarations that have that name.
2466 uint64_t Offset = Stream.GetCurrentBitNo();
2467 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2468 if (!Map || Map->empty())
2471 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2472 ASTDeclContextNameLookupTrait Trait(*this);
2474 // Create the on-disk hash table representation.
2475 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2477 DeclarationName Name = D->first;
2478 DeclContext::lookup_result Result = D->second.getLookupResult();
2479 Generator.insert(Name, Result, Trait);
2482 // Create the on-disk hash table in a buffer.
2483 llvm::SmallString<4096> LookupTable;
2484 uint32_t BucketOffset;
2486 llvm::raw_svector_ostream Out(LookupTable);
2487 // Make sure that no bucket is at offset 0
2488 clang::io::Emit32(Out, 0);
2489 BucketOffset = Generator.Emit(Out, Trait);
2492 // Write the lookup table
2494 Record.push_back(DECL_CONTEXT_VISIBLE);
2495 Record.push_back(BucketOffset);
2496 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
2499 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
2500 ++NumVisibleDeclContexts;
2504 /// \brief Write an UPDATE_VISIBLE block for the given context.
2506 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
2507 /// DeclContext in a dependent AST file. As such, they only exist for the TU
2508 /// (in C++) and for namespaces.
2509 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
2510 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2511 if (!Map || Map->empty())
2514 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2515 ASTDeclContextNameLookupTrait Trait(*this);
2517 // Create the hash table.
2518 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2520 DeclarationName Name = D->first;
2521 DeclContext::lookup_result Result = D->second.getLookupResult();
2522 // For any name that appears in this table, the results are complete, i.e.
2523 // they overwrite results from previous PCHs. Merging is always a mess.
2524 Generator.insert(Name, Result, Trait);
2527 // Create the on-disk hash table in a buffer.
2528 llvm::SmallString<4096> LookupTable;
2529 uint32_t BucketOffset;
2531 llvm::raw_svector_ostream Out(LookupTable);
2532 // Make sure that no bucket is at offset 0
2533 clang::io::Emit32(Out, 0);
2534 BucketOffset = Generator.Emit(Out, Trait);
2537 // Write the lookup table
2539 Record.push_back(UPDATE_VISIBLE);
2540 Record.push_back(getDeclID(cast<Decl>(DC)));
2541 Record.push_back(BucketOffset);
2542 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
2545 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
2546 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
2548 Record.push_back(Opts.fp_contract);
2549 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
2552 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
2553 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
2554 if (!SemaRef.Context.getLangOptions().OpenCL)
2557 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
2559 #define OPENCLEXT(nm) Record.push_back(Opts.nm);
2560 #include "clang/Basic/OpenCLExtensions.def"
2561 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
2564 //===----------------------------------------------------------------------===//
2565 // General Serialization Routines
2566 //===----------------------------------------------------------------------===//
2568 /// \brief Write a record containing the given attributes.
2569 void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) {
2570 Record.push_back(Attrs.size());
2571 for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){
2572 const Attr * A = *i;
2573 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
2574 AddSourceLocation(A->getLocation(), Record);
2576 #include "clang/Serialization/AttrPCHWrite.inc"
2581 void ASTWriter::AddString(llvm::StringRef Str, RecordDataImpl &Record) {
2582 Record.push_back(Str.size());
2583 Record.insert(Record.end(), Str.begin(), Str.end());
2586 /// \brief Note that the identifier II occurs at the given offset
2587 /// within the identifier table.
2588 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
2589 IdentID ID = IdentifierIDs[II];
2590 // Only store offsets new to this AST file. Other identifier names are looked
2591 // up earlier in the chain and thus don't need an offset.
2592 if (ID >= FirstIdentID)
2593 IdentifierOffsets[ID - FirstIdentID] = Offset;
2596 /// \brief Note that the selector Sel occurs at the given offset
2597 /// within the method pool/selector table.
2598 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
2599 unsigned ID = SelectorIDs[Sel];
2600 assert(ID && "Unknown selector");
2601 // Don't record offsets for selectors that are also available in a different
2603 if (ID < FirstSelectorID)
2605 SelectorOffsets[ID - FirstSelectorID] = Offset;
2608 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
2609 : Stream(Stream), Chain(0), SerializationListener(0),
2610 FirstDeclID(1), NextDeclID(FirstDeclID),
2611 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
2612 FirstIdentID(1), NextIdentID(FirstIdentID), FirstSelectorID(1),
2613 NextSelectorID(FirstSelectorID), FirstMacroID(1), NextMacroID(FirstMacroID),
2614 CollectedStmts(&StmtsToEmit),
2615 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
2616 NumVisibleDeclContexts(0), FirstCXXBaseSpecifiersID(1),
2617 NextCXXBaseSpecifiersID(1)
2621 void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2622 const std::string &OutputFile,
2623 const char *isysroot) {
2624 // Emit the file header.
2625 Stream.Emit((unsigned)'C', 8);
2626 Stream.Emit((unsigned)'P', 8);
2627 Stream.Emit((unsigned)'C', 8);
2628 Stream.Emit((unsigned)'H', 8);
2630 WriteBlockInfoBlock();
2633 WriteASTChain(SemaRef, StatCalls, isysroot);
2635 WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile);
2638 void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2639 const char *isysroot,
2640 const std::string &OutputFile) {
2641 using namespace llvm;
2643 ASTContext &Context = SemaRef.Context;
2644 Preprocessor &PP = SemaRef.PP;
2646 // The translation unit is the first declaration we'll emit.
2647 DeclIDs[Context.getTranslationUnitDecl()] = 1;
2649 DeclTypesToEmit.push(Context.getTranslationUnitDecl());
2651 // Make sure that we emit IdentifierInfos (and any attached
2652 // declarations) for builtins.
2654 IdentifierTable &Table = PP.getIdentifierTable();
2655 llvm::SmallVector<const char *, 32> BuiltinNames;
2656 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
2657 Context.getLangOptions().NoBuiltin);
2658 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
2659 getIdentifierRef(&Table.get(BuiltinNames[I]));
2662 // Build a record containing all of the tentative definitions in this file, in
2663 // TentativeDefinitions order. Generally, this record will be empty for
2665 RecordData TentativeDefinitions;
2666 for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
2667 AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
2670 // Build a record containing all of the file scoped decls in this file.
2671 RecordData UnusedFileScopedDecls;
2672 for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i)
2673 AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
2675 RecordData WeakUndeclaredIdentifiers;
2676 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
2677 WeakUndeclaredIdentifiers.push_back(
2678 SemaRef.WeakUndeclaredIdentifiers.size());
2679 for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
2680 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
2681 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
2682 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
2683 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
2684 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
2685 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
2689 // Build a record containing all of the locally-scoped external
2690 // declarations in this header file. Generally, this record will be
2692 RecordData LocallyScopedExternalDecls;
2693 // FIXME: This is filling in the AST file in densemap order which is
2695 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
2696 TD = SemaRef.LocallyScopedExternalDecls.begin(),
2697 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
2699 AddDeclRef(TD->second, LocallyScopedExternalDecls);
2701 // Build a record containing all of the ext_vector declarations.
2702 RecordData ExtVectorDecls;
2703 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
2704 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
2706 // Build a record containing all of the VTable uses information.
2707 RecordData VTableUses;
2708 if (!SemaRef.VTableUses.empty()) {
2709 VTableUses.push_back(SemaRef.VTableUses.size());
2710 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
2711 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
2712 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
2713 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
2717 // Build a record containing all of dynamic classes declarations.
2718 RecordData DynamicClasses;
2719 for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
2720 AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
2722 // Build a record containing all of pending implicit instantiations.
2723 RecordData PendingInstantiations;
2724 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
2725 I = SemaRef.PendingInstantiations.begin(),
2726 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
2727 AddDeclRef(I->first, PendingInstantiations);
2728 AddSourceLocation(I->second, PendingInstantiations);
2730 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
2731 "There are local ones at end of translation unit!");
2733 // Build a record containing some declaration references.
2734 RecordData SemaDeclRefs;
2735 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
2736 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
2737 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
2740 RecordData CUDASpecialDeclRefs;
2741 if (Context.getcudaConfigureCallDecl()) {
2742 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
2745 // Write the remaining AST contents.
2747 Stream.EnterSubblock(AST_BLOCK_ID, 5);
2748 WriteMetadata(Context, isysroot, OutputFile);
2749 WriteLanguageOptions(Context.getLangOptions());
2750 if (StatCalls && !isysroot)
2751 WriteStatCache(*StatCalls);
2752 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2753 // Write the record of special types.
2756 AddTypeRef(Context.getBuiltinVaListType(), Record);
2757 AddTypeRef(Context.getObjCIdType(), Record);
2758 AddTypeRef(Context.getObjCSelType(), Record);
2759 AddTypeRef(Context.getObjCProtoType(), Record);
2760 AddTypeRef(Context.getObjCClassType(), Record);
2761 AddTypeRef(Context.getRawCFConstantStringType(), Record);
2762 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
2763 AddTypeRef(Context.getFILEType(), Record);
2764 AddTypeRef(Context.getjmp_bufType(), Record);
2765 AddTypeRef(Context.getsigjmp_bufType(), Record);
2766 AddTypeRef(Context.ObjCIdRedefinitionType, Record);
2767 AddTypeRef(Context.ObjCClassRedefinitionType, Record);
2768 AddTypeRef(Context.getRawBlockdescriptorType(), Record);
2769 AddTypeRef(Context.getRawBlockdescriptorExtendedType(), Record);
2770 AddTypeRef(Context.ObjCSelRedefinitionType, Record);
2771 AddTypeRef(Context.getRawNSConstantStringType(), Record);
2772 Record.push_back(Context.isInt128Installed());
2773 Stream.EmitRecord(SPECIAL_TYPES, Record);
2775 // Keep writing types and declarations until all types and
2776 // declarations have been written.
2777 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, 3);
2778 WriteDeclsBlockAbbrevs();
2779 while (!DeclTypesToEmit.empty()) {
2780 DeclOrType DOT = DeclTypesToEmit.front();
2781 DeclTypesToEmit.pop();
2783 WriteType(DOT.getType());
2785 WriteDecl(Context, DOT.getDecl());
2789 WritePreprocessor(PP);
2790 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
2791 WriteSelectors(SemaRef);
2792 WriteReferencedSelectorsPool(SemaRef);
2793 WriteIdentifierTable(PP);
2794 WriteFPPragmaOptions(SemaRef.getFPOptions());
2795 WriteOpenCLExtensions(SemaRef);
2797 WriteTypeDeclOffsets();
2798 WritePragmaDiagnosticMappings(Context.getDiagnostics());
2800 // Write the C++ base-specifier set offsets.
2801 if (!CXXBaseSpecifiersOffsets.empty()) {
2802 // Create a blob abbreviation for the C++ base specifiers offsets.
2803 using namespace llvm;
2805 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2806 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2807 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2808 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2809 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2811 // Write the selector offsets table.
2813 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2814 Record.push_back(CXXBaseSpecifiersOffsets.size());
2815 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
2816 (const char *)CXXBaseSpecifiersOffsets.data(),
2817 CXXBaseSpecifiersOffsets.size() * sizeof(uint32_t));
2820 // Write the record containing external, unnamed definitions.
2821 if (!ExternalDefinitions.empty())
2822 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
2824 // Write the record containing tentative definitions.
2825 if (!TentativeDefinitions.empty())
2826 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
2828 // Write the record containing unused file scoped decls.
2829 if (!UnusedFileScopedDecls.empty())
2830 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
2832 // Write the record containing weak undeclared identifiers.
2833 if (!WeakUndeclaredIdentifiers.empty())
2834 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
2835 WeakUndeclaredIdentifiers);
2837 // Write the record containing locally-scoped external definitions.
2838 if (!LocallyScopedExternalDecls.empty())
2839 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
2840 LocallyScopedExternalDecls);
2842 // Write the record containing ext_vector type names.
2843 if (!ExtVectorDecls.empty())
2844 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
2846 // Write the record containing VTable uses information.
2847 if (!VTableUses.empty())
2848 Stream.EmitRecord(VTABLE_USES, VTableUses);
2850 // Write the record containing dynamic classes declarations.
2851 if (!DynamicClasses.empty())
2852 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
2854 // Write the record containing pending implicit instantiations.
2855 if (!PendingInstantiations.empty())
2856 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
2858 // Write the record containing declaration references of Sema.
2859 if (!SemaDeclRefs.empty())
2860 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
2862 // Write the record containing CUDA-specific declaration references.
2863 if (!CUDASpecialDeclRefs.empty())
2864 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
2866 // Some simple statistics
2868 Record.push_back(NumStatements);
2869 Record.push_back(NumMacros);
2870 Record.push_back(NumLexicalDeclContexts);
2871 Record.push_back(NumVisibleDeclContexts);
2872 Stream.EmitRecord(STATISTICS, Record);
2876 void ASTWriter::WriteASTChain(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2877 const char *isysroot) {
2878 using namespace llvm;
2880 ASTContext &Context = SemaRef.Context;
2881 Preprocessor &PP = SemaRef.PP;
2884 Stream.EnterSubblock(AST_BLOCK_ID, 5);
2885 WriteMetadata(Context, isysroot, "");
2886 if (StatCalls && !isysroot)
2887 WriteStatCache(*StatCalls);
2888 // FIXME: Source manager block should only write new stuff, which could be
2889 // done by tracking the largest ID in the chain
2890 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2892 // The special types are in the chained PCH.
2894 // We don't start with the translation unit, but with its decls that
2895 // don't come from the chained PCH.
2896 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
2897 llvm::SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
2898 for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
2899 E = TU->noload_decls_end();
2901 if ((*I)->getPCHLevel() == 0)
2902 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
2903 else if ((*I)->isChangedSinceDeserialization())
2904 (void)GetDeclRef(*I); // Make sure it's written, but don't record it.
2906 // We also need to write a lexical updates block for the TU.
2907 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
2908 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
2909 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
2910 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
2912 Record.push_back(TU_UPDATE_LEXICAL);
2913 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
2914 reinterpret_cast<const char*>(NewGlobalDecls.data()),
2915 NewGlobalDecls.size() * sizeof(KindDeclIDPair));
2916 // And a visible updates block for the DeclContexts.
2917 Abv = new llvm::BitCodeAbbrev();
2918 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
2919 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
2920 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
2921 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
2922 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
2923 WriteDeclContextVisibleUpdate(TU);
2925 // Build a record containing all of the new tentative definitions in this
2926 // file, in TentativeDefinitions order.
2927 RecordData TentativeDefinitions;
2928 for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
2929 if (SemaRef.TentativeDefinitions[i]->getPCHLevel() == 0)
2930 AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
2933 // Build a record containing all of the file scoped decls in this file.
2934 RecordData UnusedFileScopedDecls;
2935 for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i) {
2936 if (SemaRef.UnusedFileScopedDecls[i]->getPCHLevel() == 0)
2937 AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
2940 // We write the entire table, overwriting the tables from the chain.
2941 RecordData WeakUndeclaredIdentifiers;
2942 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
2943 WeakUndeclaredIdentifiers.push_back(
2944 SemaRef.WeakUndeclaredIdentifiers.size());
2945 for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
2946 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
2947 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
2948 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
2949 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
2950 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
2951 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
2955 // Build a record containing all of the locally-scoped external
2956 // declarations in this header file. Generally, this record will be
2958 RecordData LocallyScopedExternalDecls;
2959 // FIXME: This is filling in the AST file in densemap order which is
2961 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
2962 TD = SemaRef.LocallyScopedExternalDecls.begin(),
2963 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
2964 TD != TDEnd; ++TD) {
2965 if (TD->second->getPCHLevel() == 0)
2966 AddDeclRef(TD->second, LocallyScopedExternalDecls);
2969 // Build a record containing all of the ext_vector declarations.
2970 RecordData ExtVectorDecls;
2971 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I) {
2972 if (SemaRef.ExtVectorDecls[I]->getPCHLevel() == 0)
2973 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
2976 // Build a record containing all of the VTable uses information.
2977 // We write everything here, because it's too hard to determine whether
2978 // a use is new to this part.
2979 RecordData VTableUses;
2980 if (!SemaRef.VTableUses.empty()) {
2981 VTableUses.push_back(SemaRef.VTableUses.size());
2982 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
2983 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
2984 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
2985 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
2989 // Build a record containing all of dynamic classes declarations.
2990 RecordData DynamicClasses;
2991 for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
2992 if (SemaRef.DynamicClasses[I]->getPCHLevel() == 0)
2993 AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
2995 // Build a record containing all of pending implicit instantiations.
2996 RecordData PendingInstantiations;
2997 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
2998 I = SemaRef.PendingInstantiations.begin(),
2999 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
3000 if (I->first->getPCHLevel() == 0) {
3001 AddDeclRef(I->first, PendingInstantiations);
3002 AddSourceLocation(I->second, PendingInstantiations);
3005 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
3006 "There are local ones at end of translation unit!");
3008 // Build a record containing some declaration references.
3009 // It's not worth the effort to avoid duplication here.
3010 RecordData SemaDeclRefs;
3011 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
3012 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
3013 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
3016 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, 3);
3017 WriteDeclsBlockAbbrevs();
3018 for (DeclsToRewriteTy::iterator
3019 I = DeclsToRewrite.begin(), E = DeclsToRewrite.end(); I != E; ++I)
3020 DeclTypesToEmit.push(const_cast<Decl*>(*I));
3021 while (!DeclTypesToEmit.empty()) {
3022 DeclOrType DOT = DeclTypesToEmit.front();
3023 DeclTypesToEmit.pop();
3025 WriteType(DOT.getType());
3027 WriteDecl(Context, DOT.getDecl());
3031 WritePreprocessor(PP);
3032 WriteSelectors(SemaRef);
3033 WriteReferencedSelectorsPool(SemaRef);
3034 WriteIdentifierTable(PP);
3035 WriteFPPragmaOptions(SemaRef.getFPOptions());
3036 WriteOpenCLExtensions(SemaRef);
3038 WriteTypeDeclOffsets();
3039 // FIXME: For chained PCH only write the new mappings (we currently
3040 // write all of them again).
3041 WritePragmaDiagnosticMappings(Context.getDiagnostics());
3043 /// Build a record containing first declarations from a chained PCH and the
3044 /// most recent declarations in this AST that they point to.
3045 RecordData FirstLatestDeclIDs;
3046 for (FirstLatestDeclMap::iterator
3047 I = FirstLatestDecls.begin(), E = FirstLatestDecls.end(); I != E; ++I) {
3048 assert(I->first->getPCHLevel() > I->second->getPCHLevel() &&
3049 "Expected first & second to be in different PCHs");
3050 AddDeclRef(I->first, FirstLatestDeclIDs);
3051 AddDeclRef(I->second, FirstLatestDeclIDs);
3053 if (!FirstLatestDeclIDs.empty())
3054 Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs);
3056 // Write the record containing external, unnamed definitions.
3057 if (!ExternalDefinitions.empty())
3058 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
3060 // Write the record containing tentative definitions.
3061 if (!TentativeDefinitions.empty())
3062 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
3064 // Write the record containing unused file scoped decls.
3065 if (!UnusedFileScopedDecls.empty())
3066 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
3068 // Write the record containing weak undeclared identifiers.
3069 if (!WeakUndeclaredIdentifiers.empty())
3070 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
3071 WeakUndeclaredIdentifiers);
3073 // Write the record containing locally-scoped external definitions.
3074 if (!LocallyScopedExternalDecls.empty())
3075 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
3076 LocallyScopedExternalDecls);
3078 // Write the record containing ext_vector type names.
3079 if (!ExtVectorDecls.empty())
3080 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
3082 // Write the record containing VTable uses information.
3083 if (!VTableUses.empty())
3084 Stream.EmitRecord(VTABLE_USES, VTableUses);
3086 // Write the record containing dynamic classes declarations.
3087 if (!DynamicClasses.empty())
3088 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
3090 // Write the record containing pending implicit instantiations.
3091 if (!PendingInstantiations.empty())
3092 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
3094 // Write the record containing declaration references of Sema.
3095 if (!SemaDeclRefs.empty())
3096 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
3098 // Write the updates to DeclContexts.
3099 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
3100 I = UpdatedDeclContexts.begin(),
3101 E = UpdatedDeclContexts.end();
3103 WriteDeclContextVisibleUpdate(*I);
3105 WriteDeclUpdatesBlocks();
3108 Record.push_back(NumStatements);
3109 Record.push_back(NumMacros);
3110 Record.push_back(NumLexicalDeclContexts);
3111 Record.push_back(NumVisibleDeclContexts);
3112 WriteDeclReplacementsBlock();
3113 Stream.EmitRecord(STATISTICS, Record);
3117 void ASTWriter::WriteDeclUpdatesBlocks() {
3118 if (DeclUpdates.empty())
3121 RecordData OffsetsRecord;
3122 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, 3);
3123 for (DeclUpdateMap::iterator
3124 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
3125 const Decl *D = I->first;
3126 UpdateRecord &URec = I->second;
3128 if (DeclsToRewrite.count(D))
3129 continue; // The decl will be written completely,no need to store updates.
3131 uint64_t Offset = Stream.GetCurrentBitNo();
3132 Stream.EmitRecord(DECL_UPDATES, URec);
3134 OffsetsRecord.push_back(GetDeclRef(D));
3135 OffsetsRecord.push_back(Offset);
3138 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
3141 void ASTWriter::WriteDeclReplacementsBlock() {
3142 if (ReplacedDecls.empty())
3146 for (llvm::SmallVector<std::pair<DeclID, uint64_t>, 16>::iterator
3147 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
3148 Record.push_back(I->first);
3149 Record.push_back(I->second);
3151 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
3154 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
3155 Record.push_back(Loc.getRawEncoding());
3158 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
3159 AddSourceLocation(Range.getBegin(), Record);
3160 AddSourceLocation(Range.getEnd(), Record);
3163 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
3164 Record.push_back(Value.getBitWidth());
3165 const uint64_t *Words = Value.getRawData();
3166 Record.append(Words, Words + Value.getNumWords());
3169 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
3170 Record.push_back(Value.isUnsigned());
3171 AddAPInt(Value, Record);
3174 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
3175 AddAPInt(Value.bitcastToAPInt(), Record);
3178 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
3179 Record.push_back(getIdentifierRef(II));
3182 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
3186 IdentID &ID = IdentifierIDs[II];
3192 MacroID ASTWriter::getMacroDefinitionID(MacroDefinition *MD) {
3196 MacroID &ID = MacroDefinitions[MD];
3202 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
3203 Record.push_back(getSelectorRef(SelRef));
3206 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
3207 if (Sel.getAsOpaquePtr() == 0) {
3211 SelectorID &SID = SelectorIDs[Sel];
3212 if (SID == 0 && Chain) {
3213 // This might trigger a ReadSelector callback, which will set the ID for
3215 Chain->LoadSelector(Sel);
3218 SID = NextSelectorID++;
3223 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
3224 AddDeclRef(Temp->getDestructor(), Record);
3227 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
3228 CXXBaseSpecifier const *BasesEnd,
3229 RecordDataImpl &Record) {
3230 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
3231 CXXBaseSpecifiersToWrite.push_back(
3232 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
3234 Record.push_back(NextCXXBaseSpecifiersID++);
3237 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
3238 const TemplateArgumentLocInfo &Arg,
3239 RecordDataImpl &Record) {
3241 case TemplateArgument::Expression:
3242 AddStmt(Arg.getAsExpr());
3244 case TemplateArgument::Type:
3245 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
3247 case TemplateArgument::Template:
3248 AddSourceRange(Arg.getTemplateQualifierRange(), Record);
3249 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3251 case TemplateArgument::TemplateExpansion:
3252 AddSourceRange(Arg.getTemplateQualifierRange(), Record);
3253 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3254 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
3256 case TemplateArgument::Null:
3257 case TemplateArgument::Integral:
3258 case TemplateArgument::Declaration:
3259 case TemplateArgument::Pack:
3264 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
3265 RecordDataImpl &Record) {
3266 AddTemplateArgument(Arg.getArgument(), Record);
3268 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
3269 bool InfoHasSameExpr
3270 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
3271 Record.push_back(InfoHasSameExpr);
3272 if (InfoHasSameExpr)
3273 return; // Avoid storing the same expr twice.
3275 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
3279 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
3280 RecordDataImpl &Record) {
3282 AddTypeRef(QualType(), Record);
3286 AddTypeLoc(TInfo->getTypeLoc(), Record);
3289 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
3290 AddTypeRef(TL.getType(), Record);
3292 TypeLocWriter TLW(*this, Record);
3293 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
3297 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
3298 Record.push_back(GetOrCreateTypeID(T));
3301 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
3302 return MakeTypeID(T,
3303 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
3306 TypeID ASTWriter::getTypeID(QualType T) const {
3307 return MakeTypeID(T,
3308 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
3311 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
3314 assert(!T.getLocalFastQualifiers());
3316 TypeIdx &Idx = TypeIdxs[T];
3317 if (Idx.getIndex() == 0) {
3318 // We haven't seen this type before. Assign it a new ID and put it
3319 // into the queue of types to emit.
3320 Idx = TypeIdx(NextTypeID++);
3321 DeclTypesToEmit.push(T);
3326 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
3329 assert(!T.getLocalFastQualifiers());
3331 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
3332 assert(I != TypeIdxs.end() && "Type not emitted!");
3336 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
3337 Record.push_back(GetDeclRef(D));
3340 DeclID ASTWriter::GetDeclRef(const Decl *D) {
3344 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
3345 DeclID &ID = DeclIDs[D];
3347 // We haven't seen this declaration before. Give it a new ID and
3348 // enqueue it in the list of declarations to emit.
3350 DeclTypesToEmit.push(const_cast<Decl *>(D));
3351 } else if (ID < FirstDeclID && D->isChangedSinceDeserialization()) {
3352 // We don't add it to the replacement collection here, because we don't
3353 // have the offset yet.
3354 DeclTypesToEmit.push(const_cast<Decl *>(D));
3355 // Reset the flag, so that we don't add this decl multiple times.
3356 const_cast<Decl *>(D)->setChangedSinceDeserialization(false);
3362 DeclID ASTWriter::getDeclID(const Decl *D) {
3366 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
3370 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
3371 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
3372 Record.push_back(Name.getNameKind());
3373 switch (Name.getNameKind()) {
3374 case DeclarationName::Identifier:
3375 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
3378 case DeclarationName::ObjCZeroArgSelector:
3379 case DeclarationName::ObjCOneArgSelector:
3380 case DeclarationName::ObjCMultiArgSelector:
3381 AddSelectorRef(Name.getObjCSelector(), Record);
3384 case DeclarationName::CXXConstructorName:
3385 case DeclarationName::CXXDestructorName:
3386 case DeclarationName::CXXConversionFunctionName:
3387 AddTypeRef(Name.getCXXNameType(), Record);
3390 case DeclarationName::CXXOperatorName:
3391 Record.push_back(Name.getCXXOverloadedOperator());
3394 case DeclarationName::CXXLiteralOperatorName:
3395 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
3398 case DeclarationName::CXXUsingDirective:
3399 // No extra data to emit
3404 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
3405 DeclarationName Name, RecordDataImpl &Record) {
3406 switch (Name.getNameKind()) {
3407 case DeclarationName::CXXConstructorName:
3408 case DeclarationName::CXXDestructorName:
3409 case DeclarationName::CXXConversionFunctionName:
3410 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
3413 case DeclarationName::CXXOperatorName:
3415 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
3418 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
3422 case DeclarationName::CXXLiteralOperatorName:
3424 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
3428 case DeclarationName::Identifier:
3429 case DeclarationName::ObjCZeroArgSelector:
3430 case DeclarationName::ObjCOneArgSelector:
3431 case DeclarationName::ObjCMultiArgSelector:
3432 case DeclarationName::CXXUsingDirective:
3437 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3438 RecordDataImpl &Record) {
3439 AddDeclarationName(NameInfo.getName(), Record);
3440 AddSourceLocation(NameInfo.getLoc(), Record);
3441 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
3444 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
3445 RecordDataImpl &Record) {
3446 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
3447 Record.push_back(Info.NumTemplParamLists);
3448 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
3449 AddTemplateParameterList(Info.TemplParamLists[i], Record);
3452 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
3453 RecordDataImpl &Record) {
3454 // Nested name specifiers usually aren't too long. I think that 8 would
3455 // typically accomodate the vast majority.
3456 llvm::SmallVector<NestedNameSpecifier *, 8> NestedNames;
3458 // Push each of the NNS's onto a stack for serialization in reverse order.
3460 NestedNames.push_back(NNS);
3461 NNS = NNS->getPrefix();
3464 Record.push_back(NestedNames.size());
3465 while(!NestedNames.empty()) {
3466 NNS = NestedNames.pop_back_val();
3467 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
3468 Record.push_back(Kind);
3470 case NestedNameSpecifier::Identifier:
3471 AddIdentifierRef(NNS->getAsIdentifier(), Record);
3474 case NestedNameSpecifier::Namespace:
3475 AddDeclRef(NNS->getAsNamespace(), Record);
3478 case NestedNameSpecifier::NamespaceAlias:
3479 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
3482 case NestedNameSpecifier::TypeSpec:
3483 case NestedNameSpecifier::TypeSpecWithTemplate:
3484 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
3485 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3488 case NestedNameSpecifier::Global:
3489 // Don't need to write an associated value.
3495 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
3496 RecordDataImpl &Record) {
3497 // Nested name specifiers usually aren't too long. I think that 8 would
3498 // typically accomodate the vast majority.
3499 llvm::SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
3501 // Push each of the nested-name-specifiers's onto a stack for
3502 // serialization in reverse order.
3504 NestedNames.push_back(NNS);
3505 NNS = NNS.getPrefix();
3508 Record.push_back(NestedNames.size());
3509 while(!NestedNames.empty()) {
3510 NNS = NestedNames.pop_back_val();
3511 NestedNameSpecifier::SpecifierKind Kind
3512 = NNS.getNestedNameSpecifier()->getKind();
3513 Record.push_back(Kind);
3515 case NestedNameSpecifier::Identifier:
3516 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
3517 AddSourceRange(NNS.getLocalSourceRange(), Record);
3520 case NestedNameSpecifier::Namespace:
3521 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
3522 AddSourceRange(NNS.getLocalSourceRange(), Record);
3525 case NestedNameSpecifier::NamespaceAlias:
3526 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
3527 AddSourceRange(NNS.getLocalSourceRange(), Record);
3530 case NestedNameSpecifier::TypeSpec:
3531 case NestedNameSpecifier::TypeSpecWithTemplate:
3532 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3533 AddTypeLoc(NNS.getTypeLoc(), Record);
3534 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
3537 case NestedNameSpecifier::Global:
3538 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
3544 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
3545 TemplateName::NameKind Kind = Name.getKind();
3546 Record.push_back(Kind);
3548 case TemplateName::Template:
3549 AddDeclRef(Name.getAsTemplateDecl(), Record);
3552 case TemplateName::OverloadedTemplate: {
3553 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
3554 Record.push_back(OvT->size());
3555 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
3557 AddDeclRef(*I, Record);
3561 case TemplateName::QualifiedTemplate: {
3562 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
3563 AddNestedNameSpecifier(QualT->getQualifier(), Record);
3564 Record.push_back(QualT->hasTemplateKeyword());
3565 AddDeclRef(QualT->getTemplateDecl(), Record);
3569 case TemplateName::DependentTemplate: {
3570 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
3571 AddNestedNameSpecifier(DepT->getQualifier(), Record);
3572 Record.push_back(DepT->isIdentifier());
3573 if (DepT->isIdentifier())
3574 AddIdentifierRef(DepT->getIdentifier(), Record);
3576 Record.push_back(DepT->getOperator());
3580 case TemplateName::SubstTemplateTemplateParmPack: {
3581 SubstTemplateTemplateParmPackStorage *SubstPack
3582 = Name.getAsSubstTemplateTemplateParmPack();
3583 AddDeclRef(SubstPack->getParameterPack(), Record);
3584 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
3590 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
3591 RecordDataImpl &Record) {
3592 Record.push_back(Arg.getKind());
3593 switch (Arg.getKind()) {
3594 case TemplateArgument::Null:
3596 case TemplateArgument::Type:
3597 AddTypeRef(Arg.getAsType(), Record);
3599 case TemplateArgument::Declaration:
3600 AddDeclRef(Arg.getAsDecl(), Record);
3602 case TemplateArgument::Integral:
3603 AddAPSInt(*Arg.getAsIntegral(), Record);
3604 AddTypeRef(Arg.getIntegralType(), Record);
3606 case TemplateArgument::Template:
3607 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3609 case TemplateArgument::TemplateExpansion:
3610 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3611 if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
3612 Record.push_back(*NumExpansions + 1);
3614 Record.push_back(0);
3616 case TemplateArgument::Expression:
3617 AddStmt(Arg.getAsExpr());
3619 case TemplateArgument::Pack:
3620 Record.push_back(Arg.pack_size());
3621 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
3623 AddTemplateArgument(*I, Record);
3629 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
3630 RecordDataImpl &Record) {
3631 assert(TemplateParams && "No TemplateParams!");
3632 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
3633 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
3634 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
3635 Record.push_back(TemplateParams->size());
3636 for (TemplateParameterList::const_iterator
3637 P = TemplateParams->begin(), PEnd = TemplateParams->end();
3639 AddDeclRef(*P, Record);
3642 /// \brief Emit a template argument list.
3644 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
3645 RecordDataImpl &Record) {
3646 assert(TemplateArgs && "No TemplateArgs!");
3647 Record.push_back(TemplateArgs->size());
3648 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
3649 AddTemplateArgument(TemplateArgs->get(i), Record);
3654 ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) {
3655 Record.push_back(Set.size());
3656 for (UnresolvedSetImpl::const_iterator
3657 I = Set.begin(), E = Set.end(); I != E; ++I) {
3658 AddDeclRef(I.getDecl(), Record);
3659 Record.push_back(I.getAccess());
3663 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
3664 RecordDataImpl &Record) {
3665 Record.push_back(Base.isVirtual());
3666 Record.push_back(Base.isBaseOfClass());
3667 Record.push_back(Base.getAccessSpecifierAsWritten());
3668 Record.push_back(Base.getInheritConstructors());
3669 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
3670 AddSourceRange(Base.getSourceRange(), Record);
3671 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
3676 void ASTWriter::FlushCXXBaseSpecifiers() {
3678 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
3681 // Record the offset of this base-specifier set.
3682 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - FirstCXXBaseSpecifiersID;
3683 if (Index == CXXBaseSpecifiersOffsets.size())
3684 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
3686 if (Index > CXXBaseSpecifiersOffsets.size())
3687 CXXBaseSpecifiersOffsets.resize(Index + 1);
3688 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
3691 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
3692 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
3693 Record.push_back(BEnd - B);
3694 for (; B != BEnd; ++B)
3695 AddCXXBaseSpecifier(*B, Record);
3696 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
3698 // Flush any expressions that were written as part of the base specifiers.
3702 CXXBaseSpecifiersToWrite.clear();
3705 void ASTWriter::AddCXXCtorInitializers(
3706 const CXXCtorInitializer * const *CtorInitializers,
3707 unsigned NumCtorInitializers,
3708 RecordDataImpl &Record) {
3709 Record.push_back(NumCtorInitializers);
3710 for (unsigned i=0; i != NumCtorInitializers; ++i) {
3711 const CXXCtorInitializer *Init = CtorInitializers[i];
3713 Record.push_back(Init->isBaseInitializer());
3714 if (Init->isBaseInitializer()) {
3715 AddTypeSourceInfo(Init->getBaseClassInfo(), Record);
3716 Record.push_back(Init->isBaseVirtual());
3718 Record.push_back(Init->isIndirectMemberInitializer());
3719 if (Init->isIndirectMemberInitializer())
3720 AddDeclRef(Init->getIndirectMember(), Record);
3722 AddDeclRef(Init->getMember(), Record);
3725 AddSourceLocation(Init->getMemberLocation(), Record);
3726 AddStmt(Init->getInit());
3727 AddSourceLocation(Init->getLParenLoc(), Record);
3728 AddSourceLocation(Init->getRParenLoc(), Record);
3729 Record.push_back(Init->isWritten());
3730 if (Init->isWritten()) {
3731 Record.push_back(Init->getSourceOrder());
3733 Record.push_back(Init->getNumArrayIndices());
3734 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
3735 AddDeclRef(Init->getArrayIndex(i), Record);
3740 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
3741 assert(D->DefinitionData);
3742 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
3743 Record.push_back(Data.UserDeclaredConstructor);
3744 Record.push_back(Data.UserDeclaredCopyConstructor);
3745 Record.push_back(Data.UserDeclaredCopyAssignment);
3746 Record.push_back(Data.UserDeclaredDestructor);
3747 Record.push_back(Data.Aggregate);
3748 Record.push_back(Data.PlainOldData);
3749 Record.push_back(Data.Empty);
3750 Record.push_back(Data.Polymorphic);
3751 Record.push_back(Data.Abstract);
3752 Record.push_back(Data.HasTrivialConstructor);
3753 Record.push_back(Data.HasTrivialCopyConstructor);
3754 Record.push_back(Data.HasTrivialCopyAssignment);
3755 Record.push_back(Data.HasTrivialDestructor);
3756 Record.push_back(Data.ComputedVisibleConversions);
3757 Record.push_back(Data.DeclaredDefaultConstructor);
3758 Record.push_back(Data.DeclaredCopyConstructor);
3759 Record.push_back(Data.DeclaredCopyAssignment);
3760 Record.push_back(Data.DeclaredDestructor);
3762 Record.push_back(Data.NumBases);
3763 if (Data.NumBases > 0)
3764 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
3767 // FIXME: Make VBases lazily computed when needed to avoid storing them.
3768 Record.push_back(Data.NumVBases);
3769 if (Data.NumVBases > 0)
3770 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
3773 AddUnresolvedSet(Data.Conversions, Record);
3774 AddUnresolvedSet(Data.VisibleConversions, Record);
3775 // Data.Definition is the owning decl, no need to write it.
3776 AddDeclRef(Data.FirstFriend, Record);
3779 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
3780 assert(Reader && "Cannot remove chain");
3781 assert(!Chain && "Cannot replace chain");
3782 assert(FirstDeclID == NextDeclID &&
3783 FirstTypeID == NextTypeID &&
3784 FirstIdentID == NextIdentID &&
3785 FirstSelectorID == NextSelectorID &&
3786 FirstMacroID == NextMacroID &&
3787 FirstCXXBaseSpecifiersID == NextCXXBaseSpecifiersID &&
3788 "Setting chain after writing has started.");
3791 FirstDeclID += Chain->getTotalNumDecls();
3792 FirstTypeID += Chain->getTotalNumTypes();
3793 FirstIdentID += Chain->getTotalNumIdentifiers();
3794 FirstSelectorID += Chain->getTotalNumSelectors();
3795 FirstMacroID += Chain->getTotalNumMacroDefinitions();
3796 FirstCXXBaseSpecifiersID += Chain->getTotalNumCXXBaseSpecifiers();
3797 NextDeclID = FirstDeclID;
3798 NextTypeID = FirstTypeID;
3799 NextIdentID = FirstIdentID;
3800 NextSelectorID = FirstSelectorID;
3801 NextMacroID = FirstMacroID;
3802 NextCXXBaseSpecifiersID = FirstCXXBaseSpecifiersID;
3805 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
3806 IdentifierIDs[II] = ID;
3807 if (II->hasMacroDefinition())
3808 DeserializedMacroNames.push_back(II);
3811 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
3812 // Always take the highest-numbered type index. This copes with an interesting
3813 // case for chained AST writing where we schedule writing the type and then,
3814 // later, deserialize the type from another AST. In this case, we want to
3815 // keep the higher-numbered entry so that we can properly write it out to
3817 TypeIdx &StoredIdx = TypeIdxs[T];
3818 if (Idx.getIndex() >= StoredIdx.getIndex())
3822 void ASTWriter::DeclRead(DeclID ID, const Decl *D) {
3826 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
3827 SelectorIDs[S] = ID;
3830 void ASTWriter::MacroDefinitionRead(serialization::MacroID ID,
3831 MacroDefinition *MD) {
3832 MacroDefinitions[MD] = ID;
3835 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
3836 assert(D->isDefinition());
3837 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
3838 // We are interested when a PCH decl is modified.
3839 if (RD->getPCHLevel() > 0) {
3840 // A forward reference was mutated into a definition. Rewrite it.
3841 // FIXME: This happens during template instantiation, should we
3842 // have created a new definition decl instead ?
3846 for (CXXRecordDecl::redecl_iterator
3847 I = RD->redecls_begin(), E = RD->redecls_end(); I != E; ++I) {
3848 CXXRecordDecl *Redecl = cast<CXXRecordDecl>(*I);
3852 // We are interested when a PCH decl is modified.
3853 if (Redecl->getPCHLevel() > 0) {
3854 UpdateRecord &Record = DeclUpdates[Redecl];
3855 Record.push_back(UPD_CXX_SET_DEFINITIONDATA);
3856 assert(Redecl->DefinitionData);
3857 assert(Redecl->DefinitionData->Definition == D);
3858 AddDeclRef(D, Record); // the DefinitionDecl
3863 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
3864 // TU and namespaces are handled elsewhere.
3865 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
3868 if (!(D->getPCHLevel() == 0 && cast<Decl>(DC)->getPCHLevel() > 0))
3869 return; // Not a source decl added to a DeclContext from PCH.
3871 AddUpdatedDeclContext(DC);
3874 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
3875 assert(D->isImplicit());
3876 if (!(D->getPCHLevel() == 0 && RD->getPCHLevel() > 0))
3877 return; // Not a source member added to a class from PCH.
3878 if (!isa<CXXMethodDecl>(D))
3879 return; // We are interested in lazily declared implicit methods.
3881 // A decl coming from PCH was modified.
3882 assert(RD->isDefinition());
3883 UpdateRecord &Record = DeclUpdates[RD];
3884 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
3885 AddDeclRef(D, Record);
3888 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
3889 const ClassTemplateSpecializationDecl *D) {
3890 // The specializations set is kept in the canonical template.
3891 TD = TD->getCanonicalDecl();
3892 if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0))
3893 return; // Not a source specialization added to a template from PCH.
3895 UpdateRecord &Record = DeclUpdates[TD];
3896 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
3897 AddDeclRef(D, Record);
3900 ASTSerializationListener::~ASTSerializationListener() { }