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 "ASTCommon.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclContextInternals.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/Type.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Basic/FileManager.h"
26 #include "clang/Basic/FileSystemStatCache.h"
27 #include "clang/Basic/OnDiskHashTable.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/SourceManagerInternals.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Basic/TargetOptions.h"
32 #include "clang/Basic/Version.h"
33 #include "clang/Basic/VersionTuple.h"
34 #include "clang/Lex/HeaderSearch.h"
35 #include "clang/Lex/HeaderSearchOptions.h"
36 #include "clang/Lex/MacroInfo.h"
37 #include "clang/Lex/PreprocessingRecord.h"
38 #include "clang/Lex/Preprocessor.h"
39 #include "clang/Lex/PreprocessorOptions.h"
40 #include "clang/Sema/IdentifierResolver.h"
41 #include "clang/Sema/Sema.h"
42 #include "clang/Serialization/ASTReader.h"
43 #include "llvm/ADT/APFloat.h"
44 #include "llvm/ADT/APInt.h"
45 #include "llvm/ADT/Hashing.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/Bitcode/BitstreamWriter.h"
48 #include "llvm/Support/FileSystem.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/Path.h"
55 using namespace clang;
56 using namespace clang::serialization;
58 template <typename T, typename Allocator>
59 static StringRef data(const std::vector<T, Allocator> &v) {
60 if (v.empty()) return StringRef();
61 return StringRef(reinterpret_cast<const char*>(&v[0]),
62 sizeof(T) * v.size());
66 static StringRef data(const SmallVectorImpl<T> &v) {
67 return StringRef(reinterpret_cast<const char*>(v.data()),
68 sizeof(T) * v.size());
71 //===----------------------------------------------------------------------===//
73 //===----------------------------------------------------------------------===//
78 ASTWriter::RecordDataImpl &Record;
81 /// \brief Type code that corresponds to the record generated.
84 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
85 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
87 void VisitArrayType(const ArrayType *T);
88 void VisitFunctionType(const FunctionType *T);
89 void VisitTagType(const TagType *T);
91 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
92 #define ABSTRACT_TYPE(Class, Base)
93 #include "clang/AST/TypeNodes.def"
97 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
98 llvm_unreachable("Built-in types are never serialized");
101 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
102 Writer.AddTypeRef(T->getElementType(), Record);
106 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
107 Writer.AddTypeRef(T->getPointeeType(), Record);
111 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
112 Writer.AddTypeRef(T->getPointeeType(), Record);
113 Code = TYPE_BLOCK_POINTER;
116 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
117 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
118 Record.push_back(T->isSpelledAsLValue());
119 Code = TYPE_LVALUE_REFERENCE;
122 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
123 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
124 Code = TYPE_RVALUE_REFERENCE;
127 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
128 Writer.AddTypeRef(T->getPointeeType(), Record);
129 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
130 Code = TYPE_MEMBER_POINTER;
133 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
134 Writer.AddTypeRef(T->getElementType(), Record);
135 Record.push_back(T->getSizeModifier()); // FIXME: stable values
136 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
139 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
141 Writer.AddAPInt(T->getSize(), Record);
142 Code = TYPE_CONSTANT_ARRAY;
145 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
147 Code = TYPE_INCOMPLETE_ARRAY;
150 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
152 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
153 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
154 Writer.AddStmt(T->getSizeExpr());
155 Code = TYPE_VARIABLE_ARRAY;
158 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
159 Writer.AddTypeRef(T->getElementType(), Record);
160 Record.push_back(T->getNumElements());
161 Record.push_back(T->getVectorKind());
165 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
167 Code = TYPE_EXT_VECTOR;
170 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
171 Writer.AddTypeRef(T->getResultType(), Record);
172 FunctionType::ExtInfo C = T->getExtInfo();
173 Record.push_back(C.getNoReturn());
174 Record.push_back(C.getHasRegParm());
175 Record.push_back(C.getRegParm());
176 // FIXME: need to stabilize encoding of calling convention...
177 Record.push_back(C.getCC());
178 Record.push_back(C.getProducesResult());
181 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
182 VisitFunctionType(T);
183 Code = TYPE_FUNCTION_NO_PROTO;
186 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
187 VisitFunctionType(T);
188 Record.push_back(T->getNumArgs());
189 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
190 Writer.AddTypeRef(T->getArgType(I), Record);
191 Record.push_back(T->isVariadic());
192 Record.push_back(T->hasTrailingReturn());
193 Record.push_back(T->getTypeQuals());
194 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
195 Record.push_back(T->getExceptionSpecType());
196 if (T->getExceptionSpecType() == EST_Dynamic) {
197 Record.push_back(T->getNumExceptions());
198 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
199 Writer.AddTypeRef(T->getExceptionType(I), Record);
200 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
201 Writer.AddStmt(T->getNoexceptExpr());
202 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
203 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
204 Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
205 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
206 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
208 Code = TYPE_FUNCTION_PROTO;
211 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
212 Writer.AddDeclRef(T->getDecl(), Record);
213 Code = TYPE_UNRESOLVED_USING;
216 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
217 Writer.AddDeclRef(T->getDecl(), Record);
218 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
219 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
223 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
224 Writer.AddStmt(T->getUnderlyingExpr());
225 Code = TYPE_TYPEOF_EXPR;
228 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
229 Writer.AddTypeRef(T->getUnderlyingType(), Record);
233 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
234 Writer.AddTypeRef(T->getUnderlyingType(), Record);
235 Writer.AddStmt(T->getUnderlyingExpr());
236 Code = TYPE_DECLTYPE;
239 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
240 Writer.AddTypeRef(T->getBaseType(), Record);
241 Writer.AddTypeRef(T->getUnderlyingType(), Record);
242 Record.push_back(T->getUTTKind());
243 Code = TYPE_UNARY_TRANSFORM;
246 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
247 Writer.AddTypeRef(T->getDeducedType(), Record);
248 Record.push_back(T->isDecltypeAuto());
249 if (T->getDeducedType().isNull())
250 Record.push_back(T->isDependentType());
254 void ASTTypeWriter::VisitTagType(const TagType *T) {
255 Record.push_back(T->isDependentType());
256 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
257 assert(!T->isBeingDefined() &&
258 "Cannot serialize in the middle of a type definition");
261 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
266 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
271 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
272 Writer.AddTypeRef(T->getModifiedType(), Record);
273 Writer.AddTypeRef(T->getEquivalentType(), Record);
274 Record.push_back(T->getAttrKind());
275 Code = TYPE_ATTRIBUTED;
279 ASTTypeWriter::VisitSubstTemplateTypeParmType(
280 const SubstTemplateTypeParmType *T) {
281 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
282 Writer.AddTypeRef(T->getReplacementType(), Record);
283 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
287 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
288 const SubstTemplateTypeParmPackType *T) {
289 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
290 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
291 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
295 ASTTypeWriter::VisitTemplateSpecializationType(
296 const TemplateSpecializationType *T) {
297 Record.push_back(T->isDependentType());
298 Writer.AddTemplateName(T->getTemplateName(), Record);
299 Record.push_back(T->getNumArgs());
300 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
301 ArgI != ArgE; ++ArgI)
302 Writer.AddTemplateArgument(*ArgI, Record);
303 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
304 T->isCanonicalUnqualified() ? QualType()
305 : T->getCanonicalTypeInternal(),
307 Code = TYPE_TEMPLATE_SPECIALIZATION;
311 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
313 Writer.AddStmt(T->getSizeExpr());
314 Writer.AddSourceRange(T->getBracketsRange(), Record);
315 Code = TYPE_DEPENDENT_SIZED_ARRAY;
319 ASTTypeWriter::VisitDependentSizedExtVectorType(
320 const DependentSizedExtVectorType *T) {
321 // FIXME: Serialize this type (C++ only)
322 llvm_unreachable("Cannot serialize dependent sized extended vector types");
326 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
327 Record.push_back(T->getDepth());
328 Record.push_back(T->getIndex());
329 Record.push_back(T->isParameterPack());
330 Writer.AddDeclRef(T->getDecl(), Record);
331 Code = TYPE_TEMPLATE_TYPE_PARM;
335 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
336 Record.push_back(T->getKeyword());
337 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
338 Writer.AddIdentifierRef(T->getIdentifier(), Record);
339 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
340 : T->getCanonicalTypeInternal(),
342 Code = TYPE_DEPENDENT_NAME;
346 ASTTypeWriter::VisitDependentTemplateSpecializationType(
347 const DependentTemplateSpecializationType *T) {
348 Record.push_back(T->getKeyword());
349 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
350 Writer.AddIdentifierRef(T->getIdentifier(), Record);
351 Record.push_back(T->getNumArgs());
352 for (DependentTemplateSpecializationType::iterator
353 I = T->begin(), E = T->end(); I != E; ++I)
354 Writer.AddTemplateArgument(*I, Record);
355 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
358 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
359 Writer.AddTypeRef(T->getPattern(), Record);
360 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
361 Record.push_back(*NumExpansions + 1);
364 Code = TYPE_PACK_EXPANSION;
367 void ASTTypeWriter::VisitParenType(const ParenType *T) {
368 Writer.AddTypeRef(T->getInnerType(), Record);
372 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
373 Record.push_back(T->getKeyword());
374 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
375 Writer.AddTypeRef(T->getNamedType(), Record);
376 Code = TYPE_ELABORATED;
379 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
380 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
381 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
382 Code = TYPE_INJECTED_CLASS_NAME;
385 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
386 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
387 Code = TYPE_OBJC_INTERFACE;
390 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
391 Writer.AddTypeRef(T->getBaseType(), Record);
392 Record.push_back(T->getNumProtocols());
393 for (ObjCObjectType::qual_iterator I = T->qual_begin(),
394 E = T->qual_end(); I != E; ++I)
395 Writer.AddDeclRef(*I, Record);
396 Code = TYPE_OBJC_OBJECT;
400 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
401 Writer.AddTypeRef(T->getPointeeType(), Record);
402 Code = TYPE_OBJC_OBJECT_POINTER;
406 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
407 Writer.AddTypeRef(T->getValueType(), Record);
413 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
415 ASTWriter::RecordDataImpl &Record;
418 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
419 : Writer(Writer), Record(Record) { }
421 #define ABSTRACT_TYPELOC(CLASS, PARENT)
422 #define TYPELOC(CLASS, PARENT) \
423 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
424 #include "clang/AST/TypeLocNodes.def"
426 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
427 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
432 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
435 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
436 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
437 if (TL.needsExtraLocalData()) {
438 Record.push_back(TL.getWrittenTypeSpec());
439 Record.push_back(TL.getWrittenSignSpec());
440 Record.push_back(TL.getWrittenWidthSpec());
441 Record.push_back(TL.hasModeAttr());
444 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
445 Writer.AddSourceLocation(TL.getNameLoc(), Record);
447 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
448 Writer.AddSourceLocation(TL.getStarLoc(), Record);
450 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
451 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
453 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
454 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
456 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
457 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
459 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
460 Writer.AddSourceLocation(TL.getStarLoc(), Record);
461 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
463 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
464 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
465 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
466 Record.push_back(TL.getSizeExpr() ? 1 : 0);
467 if (TL.getSizeExpr())
468 Writer.AddStmt(TL.getSizeExpr());
470 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
471 VisitArrayTypeLoc(TL);
473 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
474 VisitArrayTypeLoc(TL);
476 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
477 VisitArrayTypeLoc(TL);
479 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
480 DependentSizedArrayTypeLoc TL) {
481 VisitArrayTypeLoc(TL);
483 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
484 DependentSizedExtVectorTypeLoc TL) {
485 Writer.AddSourceLocation(TL.getNameLoc(), Record);
487 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
488 Writer.AddSourceLocation(TL.getNameLoc(), Record);
490 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
491 Writer.AddSourceLocation(TL.getNameLoc(), Record);
493 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
494 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
495 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
496 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
497 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
498 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
499 Writer.AddDeclRef(TL.getArg(i), Record);
501 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
502 VisitFunctionTypeLoc(TL);
504 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
505 VisitFunctionTypeLoc(TL);
507 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
508 Writer.AddSourceLocation(TL.getNameLoc(), Record);
510 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
511 Writer.AddSourceLocation(TL.getNameLoc(), Record);
513 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
514 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
515 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
516 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
518 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
519 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
520 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
521 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
522 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
524 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
525 Writer.AddSourceLocation(TL.getNameLoc(), Record);
527 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
528 Writer.AddSourceLocation(TL.getKWLoc(), Record);
529 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
530 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
531 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
533 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
534 Writer.AddSourceLocation(TL.getNameLoc(), Record);
536 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
537 Writer.AddSourceLocation(TL.getNameLoc(), Record);
539 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
540 Writer.AddSourceLocation(TL.getNameLoc(), Record);
542 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
543 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
544 if (TL.hasAttrOperand()) {
545 SourceRange range = TL.getAttrOperandParensRange();
546 Writer.AddSourceLocation(range.getBegin(), Record);
547 Writer.AddSourceLocation(range.getEnd(), Record);
549 if (TL.hasAttrExprOperand()) {
550 Expr *operand = TL.getAttrExprOperand();
551 Record.push_back(operand ? 1 : 0);
552 if (operand) Writer.AddStmt(operand);
553 } else if (TL.hasAttrEnumOperand()) {
554 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
557 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
558 Writer.AddSourceLocation(TL.getNameLoc(), Record);
560 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
561 SubstTemplateTypeParmTypeLoc TL) {
562 Writer.AddSourceLocation(TL.getNameLoc(), Record);
564 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
565 SubstTemplateTypeParmPackTypeLoc TL) {
566 Writer.AddSourceLocation(TL.getNameLoc(), Record);
568 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
569 TemplateSpecializationTypeLoc TL) {
570 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
571 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
572 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
573 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
574 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
575 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
576 TL.getArgLoc(i).getLocInfo(), Record);
578 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
579 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
580 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
582 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
583 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
584 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
586 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
587 Writer.AddSourceLocation(TL.getNameLoc(), Record);
589 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
590 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
591 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
592 Writer.AddSourceLocation(TL.getNameLoc(), Record);
594 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
595 DependentTemplateSpecializationTypeLoc TL) {
596 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
597 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
598 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
599 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
600 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
601 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
602 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
603 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
604 TL.getArgLoc(I).getLocInfo(), Record);
606 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
607 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
609 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
610 Writer.AddSourceLocation(TL.getNameLoc(), Record);
612 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
613 Record.push_back(TL.hasBaseTypeAsWritten());
614 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
615 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
616 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
617 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
619 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
620 Writer.AddSourceLocation(TL.getStarLoc(), Record);
622 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
623 Writer.AddSourceLocation(TL.getKWLoc(), Record);
624 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
625 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
628 //===----------------------------------------------------------------------===//
629 // ASTWriter Implementation
630 //===----------------------------------------------------------------------===//
632 static void EmitBlockID(unsigned ID, const char *Name,
633 llvm::BitstreamWriter &Stream,
634 ASTWriter::RecordDataImpl &Record) {
636 Record.push_back(ID);
637 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
639 // Emit the block name if present.
640 if (Name == 0 || Name[0] == 0) return;
643 Record.push_back(*Name++);
644 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
647 static void EmitRecordID(unsigned ID, const char *Name,
648 llvm::BitstreamWriter &Stream,
649 ASTWriter::RecordDataImpl &Record) {
651 Record.push_back(ID);
653 Record.push_back(*Name++);
654 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
657 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
658 ASTWriter::RecordDataImpl &Record) {
659 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
661 RECORD(STMT_NULL_PTR);
663 RECORD(STMT_COMPOUND);
665 RECORD(STMT_DEFAULT);
667 RECORD(STMT_ATTRIBUTED);
674 RECORD(STMT_INDIRECT_GOTO);
675 RECORD(STMT_CONTINUE);
681 RECORD(EXPR_PREDEFINED);
682 RECORD(EXPR_DECL_REF);
683 RECORD(EXPR_INTEGER_LITERAL);
684 RECORD(EXPR_FLOATING_LITERAL);
685 RECORD(EXPR_IMAGINARY_LITERAL);
686 RECORD(EXPR_STRING_LITERAL);
687 RECORD(EXPR_CHARACTER_LITERAL);
689 RECORD(EXPR_UNARY_OPERATOR);
690 RECORD(EXPR_SIZEOF_ALIGN_OF);
691 RECORD(EXPR_ARRAY_SUBSCRIPT);
694 RECORD(EXPR_BINARY_OPERATOR);
695 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
696 RECORD(EXPR_CONDITIONAL_OPERATOR);
697 RECORD(EXPR_IMPLICIT_CAST);
698 RECORD(EXPR_CSTYLE_CAST);
699 RECORD(EXPR_COMPOUND_LITERAL);
700 RECORD(EXPR_EXT_VECTOR_ELEMENT);
701 RECORD(EXPR_INIT_LIST);
702 RECORD(EXPR_DESIGNATED_INIT);
703 RECORD(EXPR_IMPLICIT_VALUE_INIT);
705 RECORD(EXPR_ADDR_LABEL);
708 RECORD(EXPR_GNU_NULL);
709 RECORD(EXPR_SHUFFLE_VECTOR);
711 RECORD(EXPR_GENERIC_SELECTION);
712 RECORD(EXPR_OBJC_STRING_LITERAL);
713 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
714 RECORD(EXPR_OBJC_ARRAY_LITERAL);
715 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
716 RECORD(EXPR_OBJC_ENCODE);
717 RECORD(EXPR_OBJC_SELECTOR_EXPR);
718 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
719 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
720 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
721 RECORD(EXPR_OBJC_KVC_REF_EXPR);
722 RECORD(EXPR_OBJC_MESSAGE_EXPR);
723 RECORD(STMT_OBJC_FOR_COLLECTION);
724 RECORD(STMT_OBJC_CATCH);
725 RECORD(STMT_OBJC_FINALLY);
726 RECORD(STMT_OBJC_AT_TRY);
727 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
728 RECORD(STMT_OBJC_AT_THROW);
729 RECORD(EXPR_OBJC_BOOL_LITERAL);
730 RECORD(EXPR_CXX_OPERATOR_CALL);
731 RECORD(EXPR_CXX_CONSTRUCT);
732 RECORD(EXPR_CXX_STATIC_CAST);
733 RECORD(EXPR_CXX_DYNAMIC_CAST);
734 RECORD(EXPR_CXX_REINTERPRET_CAST);
735 RECORD(EXPR_CXX_CONST_CAST);
736 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
737 RECORD(EXPR_USER_DEFINED_LITERAL);
738 RECORD(EXPR_CXX_BOOL_LITERAL);
739 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
740 RECORD(EXPR_CXX_TYPEID_EXPR);
741 RECORD(EXPR_CXX_TYPEID_TYPE);
742 RECORD(EXPR_CXX_UUIDOF_EXPR);
743 RECORD(EXPR_CXX_UUIDOF_TYPE);
744 RECORD(EXPR_CXX_THIS);
745 RECORD(EXPR_CXX_THROW);
746 RECORD(EXPR_CXX_DEFAULT_ARG);
747 RECORD(EXPR_CXX_BIND_TEMPORARY);
748 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
749 RECORD(EXPR_CXX_NEW);
750 RECORD(EXPR_CXX_DELETE);
751 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
752 RECORD(EXPR_EXPR_WITH_CLEANUPS);
753 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
754 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
755 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
756 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
757 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
758 RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
759 RECORD(EXPR_CXX_NOEXCEPT);
760 RECORD(EXPR_OPAQUE_VALUE);
761 RECORD(EXPR_BINARY_TYPE_TRAIT);
762 RECORD(EXPR_PACK_EXPANSION);
763 RECORD(EXPR_SIZEOF_PACK);
764 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
765 RECORD(EXPR_CUDA_KERNEL_CALL);
769 void ASTWriter::WriteBlockInfoBlock() {
771 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
773 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
774 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
777 BLOCK(CONTROL_BLOCK);
780 RECORD(LANGUAGE_OPTIONS);
781 RECORD(TARGET_OPTIONS);
782 RECORD(ORIGINAL_FILE);
783 RECORD(ORIGINAL_PCH_DIR);
784 RECORD(ORIGINAL_FILE_ID);
785 RECORD(INPUT_FILE_OFFSETS);
786 RECORD(DIAGNOSTIC_OPTIONS);
787 RECORD(FILE_SYSTEM_OPTIONS);
788 RECORD(HEADER_SEARCH_OPTIONS);
789 RECORD(PREPROCESSOR_OPTIONS);
791 BLOCK(INPUT_FILES_BLOCK);
794 // AST Top-Level Block.
798 RECORD(IDENTIFIER_OFFSET);
799 RECORD(IDENTIFIER_TABLE);
800 RECORD(EXTERNAL_DEFINITIONS);
801 RECORD(SPECIAL_TYPES);
803 RECORD(TENTATIVE_DEFINITIONS);
804 RECORD(UNUSED_FILESCOPED_DECLS);
805 RECORD(LOCALLY_SCOPED_EXTERN_C_DECLS);
806 RECORD(SELECTOR_OFFSETS);
808 RECORD(PP_COUNTER_VALUE);
809 RECORD(SOURCE_LOCATION_OFFSETS);
810 RECORD(SOURCE_LOCATION_PRELOADS);
811 RECORD(EXT_VECTOR_DECLS);
812 RECORD(PPD_ENTITIES_OFFSETS);
813 RECORD(REFERENCED_SELECTOR_POOL);
814 RECORD(TU_UPDATE_LEXICAL);
815 RECORD(LOCAL_REDECLARATIONS_MAP);
816 RECORD(SEMA_DECL_REFS);
817 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
818 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
819 RECORD(DECL_REPLACEMENTS);
820 RECORD(UPDATE_VISIBLE);
821 RECORD(DECL_UPDATE_OFFSETS);
822 RECORD(DECL_UPDATES);
823 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
824 RECORD(DIAG_PRAGMA_MAPPINGS);
825 RECORD(CUDA_SPECIAL_DECL_REFS);
826 RECORD(HEADER_SEARCH_TABLE);
827 RECORD(FP_PRAGMA_OPTIONS);
828 RECORD(OPENCL_EXTENSIONS);
829 RECORD(DELEGATING_CTORS);
830 RECORD(KNOWN_NAMESPACES);
831 RECORD(UNDEFINED_BUT_USED);
832 RECORD(MODULE_OFFSET_MAP);
833 RECORD(SOURCE_MANAGER_LINE_TABLE);
834 RECORD(OBJC_CATEGORIES_MAP);
835 RECORD(FILE_SORTED_DECLS);
836 RECORD(IMPORTED_MODULES);
837 RECORD(MERGED_DECLARATIONS);
838 RECORD(LOCAL_REDECLARATIONS);
839 RECORD(OBJC_CATEGORIES);
840 RECORD(MACRO_OFFSET);
843 // SourceManager Block.
844 BLOCK(SOURCE_MANAGER_BLOCK);
845 RECORD(SM_SLOC_FILE_ENTRY);
846 RECORD(SM_SLOC_BUFFER_ENTRY);
847 RECORD(SM_SLOC_BUFFER_BLOB);
848 RECORD(SM_SLOC_EXPANSION_ENTRY);
850 // Preprocessor Block.
851 BLOCK(PREPROCESSOR_BLOCK);
852 RECORD(PP_MACRO_OBJECT_LIKE);
853 RECORD(PP_MACRO_FUNCTION_LIKE);
856 // Decls and Types block.
857 BLOCK(DECLTYPES_BLOCK);
858 RECORD(TYPE_EXT_QUAL);
859 RECORD(TYPE_COMPLEX);
860 RECORD(TYPE_POINTER);
861 RECORD(TYPE_BLOCK_POINTER);
862 RECORD(TYPE_LVALUE_REFERENCE);
863 RECORD(TYPE_RVALUE_REFERENCE);
864 RECORD(TYPE_MEMBER_POINTER);
865 RECORD(TYPE_CONSTANT_ARRAY);
866 RECORD(TYPE_INCOMPLETE_ARRAY);
867 RECORD(TYPE_VARIABLE_ARRAY);
869 RECORD(TYPE_EXT_VECTOR);
870 RECORD(TYPE_FUNCTION_PROTO);
871 RECORD(TYPE_FUNCTION_NO_PROTO);
872 RECORD(TYPE_TYPEDEF);
873 RECORD(TYPE_TYPEOF_EXPR);
877 RECORD(TYPE_OBJC_INTERFACE);
878 RECORD(TYPE_OBJC_OBJECT);
879 RECORD(TYPE_OBJC_OBJECT_POINTER);
880 RECORD(TYPE_DECLTYPE);
881 RECORD(TYPE_ELABORATED);
882 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
883 RECORD(TYPE_UNRESOLVED_USING);
884 RECORD(TYPE_INJECTED_CLASS_NAME);
885 RECORD(TYPE_OBJC_OBJECT);
886 RECORD(TYPE_TEMPLATE_TYPE_PARM);
887 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
888 RECORD(TYPE_DEPENDENT_NAME);
889 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
890 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
892 RECORD(TYPE_PACK_EXPANSION);
893 RECORD(TYPE_ATTRIBUTED);
894 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
896 RECORD(DECL_TYPEDEF);
899 RECORD(DECL_ENUM_CONSTANT);
900 RECORD(DECL_FUNCTION);
901 RECORD(DECL_OBJC_METHOD);
902 RECORD(DECL_OBJC_INTERFACE);
903 RECORD(DECL_OBJC_PROTOCOL);
904 RECORD(DECL_OBJC_IVAR);
905 RECORD(DECL_OBJC_AT_DEFS_FIELD);
906 RECORD(DECL_OBJC_CATEGORY);
907 RECORD(DECL_OBJC_CATEGORY_IMPL);
908 RECORD(DECL_OBJC_IMPLEMENTATION);
909 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
910 RECORD(DECL_OBJC_PROPERTY);
911 RECORD(DECL_OBJC_PROPERTY_IMPL);
913 RECORD(DECL_MS_PROPERTY);
915 RECORD(DECL_IMPLICIT_PARAM);
916 RECORD(DECL_PARM_VAR);
917 RECORD(DECL_FILE_SCOPE_ASM);
919 RECORD(DECL_CONTEXT_LEXICAL);
920 RECORD(DECL_CONTEXT_VISIBLE);
921 RECORD(DECL_NAMESPACE);
922 RECORD(DECL_NAMESPACE_ALIAS);
924 RECORD(DECL_USING_SHADOW);
925 RECORD(DECL_USING_DIRECTIVE);
926 RECORD(DECL_UNRESOLVED_USING_VALUE);
927 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
928 RECORD(DECL_LINKAGE_SPEC);
929 RECORD(DECL_CXX_RECORD);
930 RECORD(DECL_CXX_METHOD);
931 RECORD(DECL_CXX_CONSTRUCTOR);
932 RECORD(DECL_CXX_DESTRUCTOR);
933 RECORD(DECL_CXX_CONVERSION);
934 RECORD(DECL_ACCESS_SPEC);
936 RECORD(DECL_FRIEND_TEMPLATE);
937 RECORD(DECL_CLASS_TEMPLATE);
938 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
939 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
940 RECORD(DECL_FUNCTION_TEMPLATE);
941 RECORD(DECL_TEMPLATE_TYPE_PARM);
942 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
943 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
944 RECORD(DECL_STATIC_ASSERT);
945 RECORD(DECL_CXX_BASE_SPECIFIERS);
946 RECORD(DECL_INDIRECTFIELD);
947 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
949 // Statements and Exprs can occur in the Decls and Types block.
950 AddStmtsExprs(Stream, Record);
952 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
953 RECORD(PPD_MACRO_EXPANSION);
954 RECORD(PPD_MACRO_DEFINITION);
955 RECORD(PPD_INCLUSION_DIRECTIVE);
962 /// \brief Adjusts the given filename to only write out the portion of the
963 /// filename that is not part of the system root directory.
965 /// \param Filename the file name to adjust.
967 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
968 /// the returned filename will be adjusted by this system root.
970 /// \returns either the original filename (if it needs no adjustment) or the
971 /// adjusted filename (which points into the @p Filename parameter).
973 adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) {
974 assert(Filename && "No file name to adjust?");
976 if (isysroot.empty())
979 // Verify that the filename and the system root have the same prefix.
981 for (; Filename[Pos] && Pos < isysroot.size(); ++Pos)
982 if (Filename[Pos] != isysroot[Pos])
983 return Filename; // Prefixes don't match.
985 // We hit the end of the filename before we hit the end of the system root.
989 // If the file name has a '/' at the current position, skip over the '/'.
990 // We distinguish sysroot-based includes from absolute includes by the
991 // absence of '/' at the beginning of sysroot-based includes.
992 if (Filename[Pos] == '/')
995 return Filename + Pos;
998 /// \brief Write the control block.
999 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1001 const std::string &OutputFile) {
1002 using namespace llvm;
1003 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1007 BitCodeAbbrev *MetadataAbbrev = new BitCodeAbbrev();
1008 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1009 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1010 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1011 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1012 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1013 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1014 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1015 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1016 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
1017 Record.push_back(METADATA);
1018 Record.push_back(VERSION_MAJOR);
1019 Record.push_back(VERSION_MINOR);
1020 Record.push_back(CLANG_VERSION_MAJOR);
1021 Record.push_back(CLANG_VERSION_MINOR);
1022 Record.push_back(!isysroot.empty());
1023 Record.push_back(ASTHasCompilerErrors);
1024 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1025 getClangFullRepositoryVersion());
1029 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1030 SmallVector<char, 128> ModulePaths;
1033 for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end();
1035 // Skip modules that weren't directly imported.
1036 if (!(*M)->isDirectlyImported())
1039 Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding
1040 AddSourceLocation((*M)->ImportLoc, Record);
1041 Record.push_back((*M)->File->getSize());
1042 Record.push_back((*M)->File->getModificationTime());
1043 // FIXME: This writes the absolute path for AST files we depend on.
1044 const std::string &FileName = (*M)->FileName;
1045 Record.push_back(FileName.size());
1046 Record.append(FileName.begin(), FileName.end());
1048 Stream.EmitRecord(IMPORTS, Record);
1051 // Language options.
1053 const LangOptions &LangOpts = Context.getLangOpts();
1054 #define LANGOPT(Name, Bits, Default, Description) \
1055 Record.push_back(LangOpts.Name);
1056 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1057 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1058 #include "clang/Basic/LangOptions.def"
1059 #define SANITIZER(NAME, ID) Record.push_back(LangOpts.Sanitize.ID);
1060 #include "clang/Basic/Sanitizers.def"
1062 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1063 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1065 Record.push_back(LangOpts.CurrentModule.size());
1066 Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end());
1069 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1070 for (CommentOptions::BlockCommandNamesTy::const_iterator
1071 I = LangOpts.CommentOpts.BlockCommandNames.begin(),
1072 IEnd = LangOpts.CommentOpts.BlockCommandNames.end();
1074 AddString(*I, Record);
1076 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1078 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1082 const TargetInfo &Target = Context.getTargetInfo();
1083 const TargetOptions &TargetOpts = Target.getTargetOpts();
1084 AddString(TargetOpts.Triple, Record);
1085 AddString(TargetOpts.CPU, Record);
1086 AddString(TargetOpts.ABI, Record);
1087 AddString(TargetOpts.CXXABI, Record);
1088 AddString(TargetOpts.LinkerVersion, Record);
1089 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1090 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1091 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1093 Record.push_back(TargetOpts.Features.size());
1094 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1095 AddString(TargetOpts.Features[I], Record);
1097 Stream.EmitRecord(TARGET_OPTIONS, Record);
1099 // Diagnostic options.
1101 const DiagnosticOptions &DiagOpts
1102 = Context.getDiagnostics().getDiagnosticOptions();
1103 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1104 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1105 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1106 #include "clang/Basic/DiagnosticOptions.def"
1107 Record.push_back(DiagOpts.Warnings.size());
1108 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1109 AddString(DiagOpts.Warnings[I], Record);
1110 // Note: we don't serialize the log or serialization file names, because they
1111 // are generally transient files and will almost always be overridden.
1112 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1114 // File system options.
1116 const FileSystemOptions &FSOpts
1117 = Context.getSourceManager().getFileManager().getFileSystemOptions();
1118 AddString(FSOpts.WorkingDir, Record);
1119 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1121 // Header search options.
1123 const HeaderSearchOptions &HSOpts
1124 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1125 AddString(HSOpts.Sysroot, Record);
1128 Record.push_back(HSOpts.UserEntries.size());
1129 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1130 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1131 AddString(Entry.Path, Record);
1132 Record.push_back(static_cast<unsigned>(Entry.Group));
1133 Record.push_back(Entry.IsFramework);
1134 Record.push_back(Entry.IgnoreSysRoot);
1137 // System header prefixes.
1138 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1139 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1140 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1141 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1144 AddString(HSOpts.ResourceDir, Record);
1145 AddString(HSOpts.ModuleCachePath, Record);
1146 Record.push_back(HSOpts.DisableModuleHash);
1147 Record.push_back(HSOpts.UseBuiltinIncludes);
1148 Record.push_back(HSOpts.UseStandardSystemIncludes);
1149 Record.push_back(HSOpts.UseStandardCXXIncludes);
1150 Record.push_back(HSOpts.UseLibcxx);
1151 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1153 // Preprocessor options.
1155 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1157 // Macro definitions.
1158 Record.push_back(PPOpts.Macros.size());
1159 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1160 AddString(PPOpts.Macros[I].first, Record);
1161 Record.push_back(PPOpts.Macros[I].second);
1165 Record.push_back(PPOpts.Includes.size());
1166 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1167 AddString(PPOpts.Includes[I], Record);
1170 Record.push_back(PPOpts.MacroIncludes.size());
1171 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1172 AddString(PPOpts.MacroIncludes[I], Record);
1174 Record.push_back(PPOpts.UsePredefines);
1175 // Detailed record is important since it is used for the module cache hash.
1176 Record.push_back(PPOpts.DetailedRecord);
1177 AddString(PPOpts.ImplicitPCHInclude, Record);
1178 AddString(PPOpts.ImplicitPTHInclude, Record);
1179 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1180 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1182 // Original file name and file ID
1183 SourceManager &SM = Context.getSourceManager();
1184 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1185 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
1186 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1187 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1188 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1189 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1191 SmallString<128> MainFilePath(MainFile->getName());
1193 llvm::sys::fs::make_absolute(MainFilePath);
1195 const char *MainFileNameStr = MainFilePath.c_str();
1196 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
1199 Record.push_back(ORIGINAL_FILE);
1200 Record.push_back(SM.getMainFileID().getOpaqueValue());
1201 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
1205 Record.push_back(SM.getMainFileID().getOpaqueValue());
1206 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1208 // Original PCH directory
1209 if (!OutputFile.empty() && OutputFile != "-") {
1210 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1211 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1212 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1213 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1215 SmallString<128> OutputPath(OutputFile);
1217 llvm::sys::fs::make_absolute(OutputPath);
1218 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1221 Record.push_back(ORIGINAL_PCH_DIR);
1222 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1225 WriteInputFiles(Context.SourceMgr,
1226 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1232 /// \brief An input file.
1233 struct InputFileEntry {
1234 const FileEntry *File;
1236 bool BufferOverridden;
1240 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1241 HeaderSearchOptions &HSOpts,
1242 StringRef isysroot) {
1243 using namespace llvm;
1244 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1247 // Create input-file abbreviation.
1248 BitCodeAbbrev *IFAbbrev = new BitCodeAbbrev();
1249 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1250 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1251 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1252 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1253 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1254 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1255 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1257 // Get all ContentCache objects for files, sorted by whether the file is a
1258 // system one or not. System files go at the back, users files at the front.
1259 std::deque<InputFileEntry> SortedFiles;
1260 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1261 // Get this source location entry.
1262 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1263 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1265 // We only care about file entries that were not overridden.
1266 if (!SLoc->isFile())
1268 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1269 if (!Cache->OrigEntry)
1272 InputFileEntry Entry;
1273 Entry.File = Cache->OrigEntry;
1274 Entry.IsSystemFile = Cache->IsSystemFile;
1275 Entry.BufferOverridden = Cache->BufferOverridden;
1276 if (Cache->IsSystemFile)
1277 SortedFiles.push_back(Entry);
1279 SortedFiles.push_front(Entry);
1282 // If we have an isysroot for a Darwin SDK, include its SDKSettings.plist in
1283 // the set of (non-system) input files. This is simple heuristic for
1284 // detecting whether the system headers may have changed, because it is too
1285 // expensive to stat() all of the system headers.
1286 FileManager &FileMgr = SourceMgr.getFileManager();
1287 if (!HSOpts.Sysroot.empty() && !Chain) {
1288 llvm::SmallString<128> SDKSettingsFileName(HSOpts.Sysroot);
1289 llvm::sys::path::append(SDKSettingsFileName, "SDKSettings.plist");
1290 if (const FileEntry *SDKSettingsFile = FileMgr.getFile(SDKSettingsFileName)) {
1291 InputFileEntry Entry = { SDKSettingsFile, false, false };
1292 SortedFiles.push_front(Entry);
1296 unsigned UserFilesNum = 0;
1297 // Write out all of the input files.
1298 std::vector<uint32_t> InputFileOffsets;
1299 for (std::deque<InputFileEntry>::iterator
1300 I = SortedFiles.begin(), E = SortedFiles.end(); I != E; ++I) {
1301 const InputFileEntry &Entry = *I;
1303 uint32_t &InputFileID = InputFileIDs[Entry.File];
1304 if (InputFileID != 0)
1305 continue; // already recorded this file.
1307 // Record this entry's offset.
1308 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1310 InputFileID = InputFileOffsets.size();
1312 if (!Entry.IsSystemFile)
1316 Record.push_back(INPUT_FILE);
1317 Record.push_back(InputFileOffsets.size());
1319 // Emit size/modification time for this file.
1320 Record.push_back(Entry.File->getSize());
1321 Record.push_back(Entry.File->getModificationTime());
1323 // Whether this file was overridden.
1324 Record.push_back(Entry.BufferOverridden);
1326 // Turn the file name into an absolute path, if it isn't already.
1327 const char *Filename = Entry.File->getName();
1328 SmallString<128> FilePath(Filename);
1330 // Ask the file manager to fixup the relative path for us. This will
1331 // honor the working directory.
1332 FileMgr.FixupRelativePath(FilePath);
1334 // FIXME: This call to make_absolute shouldn't be necessary, the
1335 // call to FixupRelativePath should always return an absolute path.
1336 llvm::sys::fs::make_absolute(FilePath);
1337 Filename = FilePath.c_str();
1339 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1341 Stream.EmitRecordWithBlob(IFAbbrevCode, Record, Filename);
1346 // Create input file offsets abbreviation.
1347 BitCodeAbbrev *OffsetsAbbrev = new BitCodeAbbrev();
1348 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1349 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1350 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1352 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1353 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1355 // Write input file offsets.
1357 Record.push_back(INPUT_FILE_OFFSETS);
1358 Record.push_back(InputFileOffsets.size());
1359 Record.push_back(UserFilesNum);
1360 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, data(InputFileOffsets));
1363 //===----------------------------------------------------------------------===//
1364 // Source Manager Serialization
1365 //===----------------------------------------------------------------------===//
1367 /// \brief Create an abbreviation for the SLocEntry that refers to a
1369 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1370 using namespace llvm;
1371 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1372 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1373 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1374 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1375 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1376 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1377 // FileEntry fields.
1378 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1379 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1380 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1381 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1382 return Stream.EmitAbbrev(Abbrev);
1385 /// \brief Create an abbreviation for the SLocEntry that refers to a
1387 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1388 using namespace llvm;
1389 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1390 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1391 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1392 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1393 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1394 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1395 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1396 return Stream.EmitAbbrev(Abbrev);
1399 /// \brief Create an abbreviation for the SLocEntry that refers to a
1401 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1402 using namespace llvm;
1403 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1404 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1405 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1406 return Stream.EmitAbbrev(Abbrev);
1409 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1411 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1412 using namespace llvm;
1413 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1414 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1415 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1416 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1417 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1418 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1419 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1420 return Stream.EmitAbbrev(Abbrev);
1424 // Trait used for the on-disk hash table of header search information.
1425 class HeaderFileInfoTrait {
1427 const HeaderSearch &HS;
1429 // Keep track of the framework names we've used during serialization.
1430 SmallVector<char, 128> FrameworkStringData;
1431 llvm::StringMap<unsigned> FrameworkNameOffset;
1434 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1435 : Writer(Writer), HS(HS) { }
1438 const FileEntry *FE;
1439 const char *Filename;
1441 typedef const key_type &key_type_ref;
1443 typedef HeaderFileInfo data_type;
1444 typedef const data_type &data_type_ref;
1446 static unsigned ComputeHash(key_type_ref key) {
1447 // The hash is based only on size/time of the file, so that the reader can
1448 // match even when symlinking or excess path elements ("foo/../", "../")
1449 // change the form of the name. However, complete path is still the key.
1450 return llvm::hash_combine(key.FE->getSize(),
1451 key.FE->getModificationTime());
1454 std::pair<unsigned,unsigned>
1455 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1456 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
1457 clang::io::Emit16(Out, KeyLen);
1458 unsigned DataLen = 1 + 2 + 4 + 4;
1459 if (Data.isModuleHeader)
1461 clang::io::Emit8(Out, DataLen);
1462 return std::make_pair(KeyLen, DataLen);
1465 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1466 clang::io::Emit64(Out, key.FE->getSize());
1468 clang::io::Emit64(Out, key.FE->getModificationTime());
1470 Out.write(key.Filename, KeyLen);
1473 void EmitData(raw_ostream &Out, key_type_ref key,
1474 data_type_ref Data, unsigned DataLen) {
1475 using namespace clang::io;
1476 uint64_t Start = Out.tell(); (void)Start;
1478 unsigned char Flags = (Data.isImport << 5)
1479 | (Data.isPragmaOnce << 4)
1480 | (Data.DirInfo << 2)
1481 | (Data.Resolved << 1)
1482 | Data.IndexHeaderMapHeader;
1483 Emit8(Out, (uint8_t)Flags);
1484 Emit16(Out, (uint16_t) Data.NumIncludes);
1486 if (!Data.ControllingMacro)
1487 Emit32(Out, (uint32_t)Data.ControllingMacroID);
1489 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
1491 unsigned Offset = 0;
1492 if (!Data.Framework.empty()) {
1493 // If this header refers into a framework, save the framework name.
1494 llvm::StringMap<unsigned>::iterator Pos
1495 = FrameworkNameOffset.find(Data.Framework);
1496 if (Pos == FrameworkNameOffset.end()) {
1497 Offset = FrameworkStringData.size() + 1;
1498 FrameworkStringData.append(Data.Framework.begin(),
1499 Data.Framework.end());
1500 FrameworkStringData.push_back(0);
1502 FrameworkNameOffset[Data.Framework] = Offset;
1504 Offset = Pos->second;
1506 Emit32(Out, Offset);
1508 if (Data.isModuleHeader) {
1509 Module *Mod = HS.findModuleForHeader(key.FE);
1510 Emit32(Out, Writer.getExistingSubmoduleID(Mod));
1513 assert(Out.tell() - Start == DataLen && "Wrong data length");
1516 const char *strings_begin() const { return FrameworkStringData.begin(); }
1517 const char *strings_end() const { return FrameworkStringData.end(); }
1519 } // end anonymous namespace
1521 /// \brief Write the header search block for the list of files that
1523 /// \param HS The header search structure to save.
1524 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) {
1525 SmallVector<const FileEntry *, 16> FilesByUID;
1526 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1528 if (FilesByUID.size() > HS.header_file_size())
1529 FilesByUID.resize(HS.header_file_size());
1531 HeaderFileInfoTrait GeneratorTrait(*this, HS);
1532 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1533 SmallVector<const char *, 4> SavedStrings;
1534 unsigned NumHeaderSearchEntries = 0;
1535 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1536 const FileEntry *File = FilesByUID[UID];
1540 // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
1541 // from the external source if it was not provided already.
1542 const HeaderFileInfo &HFI = HS.getFileInfo(File);
1543 if (HFI.External && Chain)
1546 // Turn the file name into an absolute path, if it isn't already.
1547 const char *Filename = File->getName();
1548 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1550 // If we performed any translation on the file name at all, we need to
1551 // save this string, since the generator will refer to it later.
1552 if (Filename != File->getName()) {
1553 Filename = strdup(Filename);
1554 SavedStrings.push_back(Filename);
1557 HeaderFileInfoTrait::key_type key = { File, Filename };
1558 Generator.insert(key, HFI, GeneratorTrait);
1559 ++NumHeaderSearchEntries;
1562 // Create the on-disk hash table in a buffer.
1563 SmallString<4096> TableData;
1564 uint32_t BucketOffset;
1566 llvm::raw_svector_ostream Out(TableData);
1567 // Make sure that no bucket is at offset 0
1568 clang::io::Emit32(Out, 0);
1569 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1572 // Create a blob abbreviation
1573 using namespace llvm;
1574 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1575 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1576 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1577 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1578 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1579 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1580 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1582 // Write the header search table
1584 Record.push_back(HEADER_SEARCH_TABLE);
1585 Record.push_back(BucketOffset);
1586 Record.push_back(NumHeaderSearchEntries);
1587 Record.push_back(TableData.size());
1588 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1589 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1591 // Free all of the strings we had to duplicate.
1592 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1593 free(const_cast<char *>(SavedStrings[I]));
1596 /// \brief Writes the block containing the serialized form of the
1599 /// TODO: We should probably use an on-disk hash table (stored in a
1600 /// blob), indexed based on the file name, so that we only create
1601 /// entries for files that we actually need. In the common case (no
1602 /// errors), we probably won't have to create file entries for any of
1603 /// the files in the AST.
1604 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1605 const Preprocessor &PP,
1606 StringRef isysroot) {
1609 // Enter the source manager block.
1610 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1612 // Abbreviations for the various kinds of source-location entries.
1613 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1614 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1615 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1616 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1618 // Write out the source location entry table. We skip the first
1619 // entry, which is always the same dummy entry.
1620 std::vector<uint32_t> SLocEntryOffsets;
1621 RecordData PreloadSLocs;
1622 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1623 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
1625 // Get this source location entry.
1626 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1627 FileID FID = FileID::get(I);
1628 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
1630 // Record the offset of this source-location entry.
1631 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1633 // Figure out which record code to use.
1635 if (SLoc->isFile()) {
1636 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1637 if (Cache->OrigEntry) {
1638 Code = SM_SLOC_FILE_ENTRY;
1640 Code = SM_SLOC_BUFFER_ENTRY;
1642 Code = SM_SLOC_EXPANSION_ENTRY;
1644 Record.push_back(Code);
1646 // Starting offset of this entry within this module, so skip the dummy.
1647 Record.push_back(SLoc->getOffset() - 2);
1648 if (SLoc->isFile()) {
1649 const SrcMgr::FileInfo &File = SLoc->getFile();
1650 Record.push_back(File.getIncludeLoc().getRawEncoding());
1651 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1652 Record.push_back(File.hasLineDirectives());
1654 const SrcMgr::ContentCache *Content = File.getContentCache();
1655 if (Content->OrigEntry) {
1656 assert(Content->OrigEntry == Content->ContentsEntry &&
1657 "Writing to AST an overridden file is not supported");
1659 // The source location entry is a file. Emit input file ID.
1660 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1661 Record.push_back(InputFileIDs[Content->OrigEntry]);
1663 Record.push_back(File.NumCreatedFIDs);
1665 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
1666 if (FDI != FileDeclIDs.end()) {
1667 Record.push_back(FDI->second->FirstDeclIndex);
1668 Record.push_back(FDI->second->DeclIDs.size());
1670 Record.push_back(0);
1671 Record.push_back(0);
1674 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1676 if (Content->BufferOverridden) {
1678 Record.push_back(SM_SLOC_BUFFER_BLOB);
1679 const llvm::MemoryBuffer *Buffer
1680 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1681 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1682 StringRef(Buffer->getBufferStart(),
1683 Buffer->getBufferSize() + 1));
1686 // The source location entry is a buffer. The blob associated
1687 // with this entry contains the contents of the buffer.
1689 // We add one to the size so that we capture the trailing NULL
1690 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1691 // the reader side).
1692 const llvm::MemoryBuffer *Buffer
1693 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1694 const char *Name = Buffer->getBufferIdentifier();
1695 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1696 StringRef(Name, strlen(Name) + 1));
1698 Record.push_back(SM_SLOC_BUFFER_BLOB);
1699 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1700 StringRef(Buffer->getBufferStart(),
1701 Buffer->getBufferSize() + 1));
1703 if (strcmp(Name, "<built-in>") == 0) {
1704 PreloadSLocs.push_back(SLocEntryOffsets.size());
1708 // The source location entry is a macro expansion.
1709 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
1710 Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
1711 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
1712 Record.push_back(Expansion.isMacroArgExpansion() ? 0
1713 : Expansion.getExpansionLocEnd().getRawEncoding());
1715 // Compute the token length for this macro expansion.
1716 unsigned NextOffset = SourceMgr.getNextLocalOffset();
1718 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
1719 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1720 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
1726 if (SLocEntryOffsets.empty())
1729 // Write the source-location offsets table into the AST block. This
1730 // table is used for lazily loading source-location information.
1731 using namespace llvm;
1732 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1733 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1734 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1735 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
1736 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1737 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1740 Record.push_back(SOURCE_LOCATION_OFFSETS);
1741 Record.push_back(SLocEntryOffsets.size());
1742 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
1743 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
1745 // Write the source location entry preloads array, telling the AST
1746 // reader which source locations entries it should load eagerly.
1747 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1749 // Write the line table. It depends on remapping working, so it must come
1750 // after the source location offsets.
1751 if (SourceMgr.hasLineTable()) {
1752 LineTableInfo &LineTable = SourceMgr.getLineTable();
1755 // Emit the file names
1756 Record.push_back(LineTable.getNumFilenames());
1757 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1758 // Emit the file name
1759 const char *Filename = LineTable.getFilename(I);
1760 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1761 unsigned FilenameLen = Filename? strlen(Filename) : 0;
1762 Record.push_back(FilenameLen);
1764 Record.insert(Record.end(), Filename, Filename + FilenameLen);
1767 // Emit the line entries
1768 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1770 // Only emit entries for local files.
1771 if (L->first.ID < 0)
1775 Record.push_back(L->first.ID);
1777 // Emit the line entries
1778 Record.push_back(L->second.size());
1779 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1780 LEEnd = L->second.end();
1781 LE != LEEnd; ++LE) {
1782 Record.push_back(LE->FileOffset);
1783 Record.push_back(LE->LineNo);
1784 Record.push_back(LE->FilenameID);
1785 Record.push_back((unsigned)LE->FileKind);
1786 Record.push_back(LE->IncludeOffset);
1789 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
1793 //===----------------------------------------------------------------------===//
1794 // Preprocessor Serialization
1795 //===----------------------------------------------------------------------===//
1798 class ASTMacroTableTrait {
1800 typedef IdentID key_type;
1801 typedef key_type key_type_ref;
1804 uint32_t MacroDirectivesOffset;
1807 typedef Data data_type;
1808 typedef const data_type &data_type_ref;
1810 static unsigned ComputeHash(IdentID IdID) {
1811 return llvm::hash_value(IdID);
1814 std::pair<unsigned,unsigned>
1815 static EmitKeyDataLength(raw_ostream& Out,
1816 key_type_ref Key, data_type_ref Data) {
1817 unsigned KeyLen = 4; // IdentID.
1818 unsigned DataLen = 4; // MacroDirectivesOffset.
1819 return std::make_pair(KeyLen, DataLen);
1822 static void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
1823 clang::io::Emit32(Out, Key);
1826 static void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
1828 clang::io::Emit32(Out, Data.MacroDirectivesOffset);
1831 } // end anonymous namespace
1833 static int compareMacroDirectives(const void *XPtr, const void *YPtr) {
1834 const std::pair<const IdentifierInfo *, MacroDirective *> &X =
1835 *(const std::pair<const IdentifierInfo *, MacroDirective *>*)XPtr;
1836 const std::pair<const IdentifierInfo *, MacroDirective *> &Y =
1837 *(const std::pair<const IdentifierInfo *, MacroDirective *>*)YPtr;
1838 return X.first->getName().compare(Y.first->getName());
1841 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
1842 const Preprocessor &PP) {
1843 if (MacroInfo *MI = MD->getMacroInfo())
1844 if (MI->isBuiltinMacro())
1848 SourceLocation Loc = MD->getLocation();
1849 if (Loc.isInvalid())
1851 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
1858 /// \brief Writes the block containing the serialized form of the
1861 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
1862 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1864 WritePreprocessorDetail(*PPRec);
1868 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1869 if (PP.getCounterValue() != 0) {
1870 Record.push_back(PP.getCounterValue());
1871 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1875 // Enter the preprocessor block.
1876 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1878 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1879 // FIXME: use diagnostics subsystem for localization etc.
1880 if (PP.SawDateOrTime())
1881 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1884 // Loop over all the macro directives that are live at the end of the file,
1885 // emitting each to the PP section.
1887 // Construct the list of macro directives that need to be serialized.
1888 SmallVector<std::pair<const IdentifierInfo *, MacroDirective *>, 2>
1890 for (Preprocessor::macro_iterator
1891 I = PP.macro_begin(/*IncludeExternalMacros=*/false),
1892 E = PP.macro_end(/*IncludeExternalMacros=*/false);
1894 MacroDirectives.push_back(std::make_pair(I->first, I->second));
1897 // Sort the set of macro definitions that need to be serialized by the
1898 // name of the macro, to provide a stable ordering.
1899 llvm::array_pod_sort(MacroDirectives.begin(), MacroDirectives.end(),
1900 &compareMacroDirectives);
1902 OnDiskChainedHashTableGenerator<ASTMacroTableTrait> Generator;
1904 // Emit the macro directives as a list and associate the offset with the
1905 // identifier they belong to.
1906 for (unsigned I = 0, N = MacroDirectives.size(); I != N; ++I) {
1907 const IdentifierInfo *Name = MacroDirectives[I].first;
1908 uint64_t MacroDirectiveOffset = Stream.GetCurrentBitNo();
1909 MacroDirective *MD = MacroDirectives[I].second;
1911 // If the macro or identifier need no updates, don't write the macro history
1913 // FIXME: Chain the macro history instead of re-writing it.
1914 if (MD->isFromPCH() &&
1915 Name->isFromAST() && !Name->hasChangedSinceDeserialization())
1918 // Emit the macro directives in reverse source order.
1919 for (; MD; MD = MD->getPrevious()) {
1922 if (shouldIgnoreMacro(MD, IsModule, PP))
1925 AddSourceLocation(MD->getLocation(), Record);
1926 Record.push_back(MD->getKind());
1927 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
1928 MacroID InfoID = getMacroRef(DefMD->getInfo(), Name);
1929 Record.push_back(InfoID);
1930 Record.push_back(DefMD->isImported());
1931 Record.push_back(DefMD->isAmbiguous());
1933 } else if (VisibilityMacroDirective *
1934 VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
1935 Record.push_back(VisMD->isPublic());
1941 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
1944 IdentMacroDirectivesOffsetMap[Name] = MacroDirectiveOffset;
1946 IdentID NameID = getIdentifierRef(Name);
1947 ASTMacroTableTrait::Data data;
1948 data.MacroDirectivesOffset = MacroDirectiveOffset;
1949 Generator.insert(NameID, data);
1952 /// \brief Offsets of each of the macros into the bitstream, indexed by
1953 /// the local macro ID
1955 /// For each identifier that is associated with a macro, this map
1956 /// provides the offset into the bitstream where that macro is
1958 std::vector<uint32_t> MacroOffsets;
1960 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
1961 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
1962 MacroInfo *MI = MacroInfosToEmit[I].MI;
1963 MacroID ID = MacroInfosToEmit[I].ID;
1965 if (ID < FirstMacroID) {
1966 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
1970 // Record the local offset of this macro.
1971 unsigned Index = ID - FirstMacroID;
1972 if (Index == MacroOffsets.size())
1973 MacroOffsets.push_back(Stream.GetCurrentBitNo());
1975 if (Index > MacroOffsets.size())
1976 MacroOffsets.resize(Index + 1);
1978 MacroOffsets[Index] = Stream.GetCurrentBitNo();
1981 AddIdentifierRef(Name, Record);
1982 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
1983 AddSourceLocation(MI->getDefinitionLoc(), Record);
1984 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
1985 Record.push_back(MI->isUsed());
1987 if (MI->isObjectLike()) {
1988 Code = PP_MACRO_OBJECT_LIKE;
1990 Code = PP_MACRO_FUNCTION_LIKE;
1992 Record.push_back(MI->isC99Varargs());
1993 Record.push_back(MI->isGNUVarargs());
1994 Record.push_back(MI->hasCommaPasting());
1995 Record.push_back(MI->getNumArgs());
1996 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1998 AddIdentifierRef(*I, Record);
2001 // If we have a detailed preprocessing record, record the macro definition
2002 // ID that corresponds to this macro.
2004 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2006 Stream.EmitRecord(Code, Record);
2009 // Emit the tokens array.
2010 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2011 // Note that we know that the preprocessor does not have any annotation
2012 // tokens in it because they are created by the parser, and thus can't
2013 // be in a macro definition.
2014 const Token &Tok = MI->getReplacementToken(TokNo);
2015 AddToken(Tok, Record);
2016 Stream.EmitRecord(PP_TOKEN, Record);
2024 // Create the on-disk hash table in a buffer.
2025 SmallString<4096> MacroTable;
2026 uint32_t BucketOffset;
2028 llvm::raw_svector_ostream Out(MacroTable);
2029 // Make sure that no bucket is at offset 0
2030 clang::io::Emit32(Out, 0);
2031 BucketOffset = Generator.Emit(Out);
2034 // Write the macro table
2035 using namespace llvm;
2036 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2037 Abbrev->Add(BitCodeAbbrevOp(MACRO_TABLE));
2038 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2039 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2040 unsigned MacroTableAbbrev = Stream.EmitAbbrev(Abbrev);
2042 Record.push_back(MACRO_TABLE);
2043 Record.push_back(BucketOffset);
2044 Stream.EmitRecordWithBlob(MacroTableAbbrev, Record, MacroTable.str());
2047 // Write the offsets table for macro IDs.
2048 using namespace llvm;
2049 Abbrev = new BitCodeAbbrev();
2050 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2051 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2052 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2053 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2055 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2057 Record.push_back(MACRO_OFFSET);
2058 Record.push_back(MacroOffsets.size());
2059 Record.push_back(FirstMacroID - NUM_PREDEF_MACRO_IDS);
2060 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record,
2061 data(MacroOffsets));
2064 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2065 if (PPRec.local_begin() == PPRec.local_end())
2068 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2070 // Enter the preprocessor block.
2071 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2073 // If the preprocessor has a preprocessing record, emit it.
2074 unsigned NumPreprocessingRecords = 0;
2075 using namespace llvm;
2077 // Set up the abbreviation for
2078 unsigned InclusionAbbrev = 0;
2080 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2081 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2082 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2083 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2084 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2085 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2086 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2087 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2090 unsigned FirstPreprocessorEntityID
2091 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2092 + NUM_PREDEF_PP_ENTITY_IDS;
2093 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2095 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2096 EEnd = PPRec.local_end();
2098 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2101 PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(),
2102 Stream.GetCurrentBitNo()));
2104 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
2105 // Record this macro definition's ID.
2106 MacroDefinitions[MD] = NextPreprocessorEntityID;
2108 AddIdentifierRef(MD->getName(), Record);
2109 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2113 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
2114 Record.push_back(ME->isBuiltinMacro());
2115 if (ME->isBuiltinMacro())
2116 AddIdentifierRef(ME->getName(), Record);
2118 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2119 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2123 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
2124 Record.push_back(PPD_INCLUSION_DIRECTIVE);
2125 Record.push_back(ID->getFileName().size());
2126 Record.push_back(ID->wasInQuotes());
2127 Record.push_back(static_cast<unsigned>(ID->getKind()));
2128 Record.push_back(ID->importedModule());
2129 SmallString<64> Buffer;
2130 Buffer += ID->getFileName();
2131 // Check that the FileEntry is not null because it was not resolved and
2132 // we create a PCH even with compiler errors.
2134 Buffer += ID->getFile()->getName();
2135 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2139 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2143 // Write the offsets table for the preprocessing record.
2144 if (NumPreprocessingRecords > 0) {
2145 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2147 // Write the offsets table for identifier IDs.
2148 using namespace llvm;
2149 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2150 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2151 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2152 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2153 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2156 Record.push_back(PPD_ENTITIES_OFFSETS);
2157 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
2158 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2159 data(PreprocessedEntityOffsets));
2163 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2164 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2165 if (Known != SubmoduleIDs.end())
2166 return Known->second;
2168 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2171 unsigned ASTWriter::getExistingSubmoduleID(Module *Mod) const {
2175 llvm::DenseMap<Module *, unsigned>::const_iterator
2176 Known = SubmoduleIDs.find(Mod);
2177 if (Known != SubmoduleIDs.end())
2178 return Known->second;
2183 /// \brief Compute the number of modules within the given tree (including the
2185 static unsigned getNumberOfModules(Module *Mod) {
2186 unsigned ChildModules = 0;
2187 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2188 SubEnd = Mod->submodule_end();
2189 Sub != SubEnd; ++Sub)
2190 ChildModules += getNumberOfModules(*Sub);
2192 return ChildModules + 1;
2195 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2196 // Determine the dependencies of our module and each of it's submodules.
2197 // FIXME: This feels like it belongs somewhere else, but there are no
2198 // other consumers of this information.
2199 SourceManager &SrcMgr = PP->getSourceManager();
2200 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2201 for (ASTContext::import_iterator I = Context->local_import_begin(),
2202 IEnd = Context->local_import_end();
2204 if (Module *ImportedFrom
2205 = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(),
2207 ImportedFrom->Imports.push_back(I->getImportedModule());
2211 // Enter the submodule description block.
2212 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
2214 // Write the abbreviations needed for the submodules block.
2215 using namespace llvm;
2216 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2217 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2218 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2219 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2220 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2221 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2222 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2223 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2224 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2225 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2226 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2227 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2228 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2230 Abbrev = new BitCodeAbbrev();
2231 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2232 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2233 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2235 Abbrev = new BitCodeAbbrev();
2236 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2237 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2238 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2240 Abbrev = new BitCodeAbbrev();
2241 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2242 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2243 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2245 Abbrev = new BitCodeAbbrev();
2246 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2247 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2248 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2250 Abbrev = new BitCodeAbbrev();
2251 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2252 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2253 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2255 Abbrev = new BitCodeAbbrev();
2256 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2257 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2258 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2260 Abbrev = new BitCodeAbbrev();
2261 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2262 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2263 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2264 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2266 Abbrev = new BitCodeAbbrev();
2267 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2268 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2269 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2271 Abbrev = new BitCodeAbbrev();
2272 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2273 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2274 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2275 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2277 // Write the submodule metadata block.
2279 Record.push_back(getNumberOfModules(WritingModule));
2280 Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
2281 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2283 // Write all of the submodules.
2284 std::queue<Module *> Q;
2285 Q.push(WritingModule);
2286 while (!Q.empty()) {
2287 Module *Mod = Q.front();
2289 unsigned ID = getSubmoduleID(Mod);
2291 // Emit the definition of the block.
2293 Record.push_back(SUBMODULE_DEFINITION);
2294 Record.push_back(ID);
2296 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2297 Record.push_back(SubmoduleIDs[Mod->Parent]);
2299 Record.push_back(0);
2301 Record.push_back(Mod->IsFramework);
2302 Record.push_back(Mod->IsExplicit);
2303 Record.push_back(Mod->IsSystem);
2304 Record.push_back(Mod->InferSubmodules);
2305 Record.push_back(Mod->InferExplicitSubmodules);
2306 Record.push_back(Mod->InferExportWildcard);
2307 Record.push_back(Mod->ConfigMacrosExhaustive);
2308 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2310 // Emit the requirements.
2311 for (unsigned I = 0, N = Mod->Requires.size(); I != N; ++I) {
2313 Record.push_back(SUBMODULE_REQUIRES);
2314 Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
2315 Mod->Requires[I].data(),
2316 Mod->Requires[I].size());
2319 // Emit the umbrella header, if there is one.
2320 if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) {
2322 Record.push_back(SUBMODULE_UMBRELLA_HEADER);
2323 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2324 UmbrellaHeader->getName());
2325 } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) {
2327 Record.push_back(SUBMODULE_UMBRELLA_DIR);
2328 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2329 UmbrellaDir->getName());
2332 // Emit the headers.
2333 for (unsigned I = 0, N = Mod->Headers.size(); I != N; ++I) {
2335 Record.push_back(SUBMODULE_HEADER);
2336 Stream.EmitRecordWithBlob(HeaderAbbrev, Record,
2337 Mod->Headers[I]->getName());
2339 // Emit the excluded headers.
2340 for (unsigned I = 0, N = Mod->ExcludedHeaders.size(); I != N; ++I) {
2342 Record.push_back(SUBMODULE_EXCLUDED_HEADER);
2343 Stream.EmitRecordWithBlob(ExcludedHeaderAbbrev, Record,
2344 Mod->ExcludedHeaders[I]->getName());
2346 ArrayRef<const FileEntry *>
2347 TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2348 for (unsigned I = 0, N = TopHeaders.size(); I != N; ++I) {
2350 Record.push_back(SUBMODULE_TOPHEADER);
2351 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record,
2352 TopHeaders[I]->getName());
2355 // Emit the imports.
2356 if (!Mod->Imports.empty()) {
2358 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
2359 unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
2360 assert(ImportedID && "Unknown submodule!");
2361 Record.push_back(ImportedID);
2363 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2366 // Emit the exports.
2367 if (!Mod->Exports.empty()) {
2369 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
2370 if (Module *Exported = Mod->Exports[I].getPointer()) {
2371 unsigned ExportedID = SubmoduleIDs[Exported];
2372 assert(ExportedID > 0 && "Unknown submodule ID?");
2373 Record.push_back(ExportedID);
2375 Record.push_back(0);
2378 Record.push_back(Mod->Exports[I].getInt());
2380 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2383 // Emit the link libraries.
2384 for (unsigned I = 0, N = Mod->LinkLibraries.size(); I != N; ++I) {
2386 Record.push_back(SUBMODULE_LINK_LIBRARY);
2387 Record.push_back(Mod->LinkLibraries[I].IsFramework);
2388 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record,
2389 Mod->LinkLibraries[I].Library);
2392 // Emit the conflicts.
2393 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2395 Record.push_back(SUBMODULE_CONFLICT);
2396 unsigned OtherID = getSubmoduleID(Mod->Conflicts[I].Other);
2397 assert(OtherID && "Unknown submodule!");
2398 Record.push_back(OtherID);
2399 Stream.EmitRecordWithBlob(ConflictAbbrev, Record,
2400 Mod->Conflicts[I].Message);
2403 // Emit the configuration macros.
2404 for (unsigned I = 0, N = Mod->ConfigMacros.size(); I != N; ++I) {
2406 Record.push_back(SUBMODULE_CONFIG_MACRO);
2407 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record,
2408 Mod->ConfigMacros[I]);
2411 // Queue up the submodules of this module.
2412 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2413 SubEnd = Mod->submodule_end();
2414 Sub != SubEnd; ++Sub)
2420 assert((NextSubmoduleID - FirstSubmoduleID
2421 == getNumberOfModules(WritingModule)) && "Wrong # of submodules");
2424 serialization::SubmoduleID
2425 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
2426 if (Loc.isInvalid() || !WritingModule)
2427 return 0; // No submodule
2429 // Find the module that owns this location.
2430 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2432 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
2436 // Check whether this submodule is part of our own module.
2437 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
2440 return getSubmoduleID(OwningMod);
2443 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2445 // Make sure set diagnostic pragmas don't affect the translation unit that
2446 // imports the module.
2447 // FIXME: Make diagnostic pragma sections work properly with modules.
2451 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2453 unsigned CurrID = 0;
2454 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
2456 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
2457 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2459 const DiagnosticsEngine::DiagStatePoint &point = *I;
2460 if (point.Loc.isInvalid())
2463 Record.push_back(point.Loc.getRawEncoding());
2464 unsigned &DiagStateID = DiagStateIDMap[point.State];
2465 Record.push_back(DiagStateID);
2467 if (DiagStateID == 0) {
2468 DiagStateID = ++CurrID;
2469 for (DiagnosticsEngine::DiagState::const_iterator
2470 I = point.State->begin(), E = point.State->end(); I != E; ++I) {
2471 if (I->second.isPragma()) {
2472 Record.push_back(I->first);
2473 Record.push_back(I->second.getMapping());
2476 Record.push_back(-1); // mark the end of the diag/map pairs for this
2481 if (!Record.empty())
2482 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2485 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2486 if (CXXBaseSpecifiersOffsets.empty())
2491 // Create a blob abbreviation for the C++ base specifiers offsets.
2492 using namespace llvm;
2494 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2495 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2496 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2497 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2498 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2500 // Write the base specifier offsets table.
2502 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2503 Record.push_back(CXXBaseSpecifiersOffsets.size());
2504 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
2505 data(CXXBaseSpecifiersOffsets));
2508 //===----------------------------------------------------------------------===//
2509 // Type Serialization
2510 //===----------------------------------------------------------------------===//
2512 /// \brief Write the representation of a type to the AST stream.
2513 void ASTWriter::WriteType(QualType T) {
2514 TypeIdx &Idx = TypeIdxs[T];
2515 if (Idx.getIndex() == 0) // we haven't seen this type before.
2516 Idx = TypeIdx(NextTypeID++);
2518 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2520 // Record the offset for this type.
2521 unsigned Index = Idx.getIndex() - FirstTypeID;
2522 if (TypeOffsets.size() == Index)
2523 TypeOffsets.push_back(Stream.GetCurrentBitNo());
2524 else if (TypeOffsets.size() < Index) {
2525 TypeOffsets.resize(Index + 1);
2526 TypeOffsets[Index] = Stream.GetCurrentBitNo();
2531 // Emit the type's representation.
2532 ASTTypeWriter W(*this, Record);
2534 if (T.hasLocalNonFastQualifiers()) {
2535 Qualifiers Qs = T.getLocalQualifiers();
2536 AddTypeRef(T.getLocalUnqualifiedType(), Record);
2537 Record.push_back(Qs.getAsOpaqueValue());
2538 W.Code = TYPE_EXT_QUAL;
2540 switch (T->getTypeClass()) {
2541 // For all of the concrete, non-dependent types, call the
2542 // appropriate visitor function.
2543 #define TYPE(Class, Base) \
2544 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
2545 #define ABSTRACT_TYPE(Class, Base)
2546 #include "clang/AST/TypeNodes.def"
2550 // Emit the serialized record.
2551 Stream.EmitRecord(W.Code, Record);
2553 // Flush any expressions that were written as part of this type.
2557 //===----------------------------------------------------------------------===//
2558 // Declaration Serialization
2559 //===----------------------------------------------------------------------===//
2561 /// \brief Write the block containing all of the declaration IDs
2562 /// lexically declared within the given DeclContext.
2564 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2565 /// bistream, or 0 if no block was written.
2566 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2568 if (DC->decls_empty())
2571 uint64_t Offset = Stream.GetCurrentBitNo();
2573 Record.push_back(DECL_CONTEXT_LEXICAL);
2574 SmallVector<KindDeclIDPair, 64> Decls;
2575 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
2577 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
2579 ++NumLexicalDeclContexts;
2580 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
2584 void ASTWriter::WriteTypeDeclOffsets() {
2585 using namespace llvm;
2588 // Write the type offsets array
2589 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2590 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2591 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2592 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2593 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2594 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2596 Record.push_back(TYPE_OFFSET);
2597 Record.push_back(TypeOffsets.size());
2598 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
2599 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
2601 // Write the declaration offsets array
2602 Abbrev = new BitCodeAbbrev();
2603 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2604 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2605 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2606 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2607 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2609 Record.push_back(DECL_OFFSET);
2610 Record.push_back(DeclOffsets.size());
2611 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
2612 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
2615 void ASTWriter::WriteFileDeclIDsMap() {
2616 using namespace llvm;
2619 // Join the vectors of DeclIDs from all files.
2620 SmallVector<DeclID, 256> FileSortedIDs;
2621 for (FileDeclIDsTy::iterator
2622 FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) {
2623 DeclIDInFileInfo &Info = *FI->second;
2624 Info.FirstDeclIndex = FileSortedIDs.size();
2625 for (LocDeclIDsTy::iterator
2626 DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI)
2627 FileSortedIDs.push_back(DI->second);
2630 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2631 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2632 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2633 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2634 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
2635 Record.push_back(FILE_SORTED_DECLS);
2636 Record.push_back(FileSortedIDs.size());
2637 Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs));
2640 void ASTWriter::WriteComments() {
2641 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2642 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
2644 for (ArrayRef<RawComment *>::iterator I = RawComments.begin(),
2645 E = RawComments.end();
2648 AddSourceRange((*I)->getSourceRange(), Record);
2649 Record.push_back((*I)->getKind());
2650 Record.push_back((*I)->isTrailingComment());
2651 Record.push_back((*I)->isAlmostTrailingComment());
2652 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2657 //===----------------------------------------------------------------------===//
2658 // Global Method Pool and Selector Serialization
2659 //===----------------------------------------------------------------------===//
2662 // Trait used for the on-disk hash table used in the method pool.
2663 class ASTMethodPoolTrait {
2667 typedef Selector key_type;
2668 typedef key_type key_type_ref;
2672 ObjCMethodList Instance, Factory;
2674 typedef const data_type& data_type_ref;
2676 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2678 static unsigned ComputeHash(Selector Sel) {
2679 return serialization::ComputeHash(Sel);
2682 std::pair<unsigned,unsigned>
2683 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2684 data_type_ref Methods) {
2685 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2686 clang::io::Emit16(Out, KeyLen);
2687 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2688 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2689 Method = Method->getNext())
2692 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2693 Method = Method->getNext())
2696 clang::io::Emit16(Out, DataLen);
2697 return std::make_pair(KeyLen, DataLen);
2700 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
2701 uint64_t Start = Out.tell();
2702 assert((Start >> 32) == 0 && "Selector key offset too large");
2703 Writer.SetSelectorOffset(Sel, Start);
2704 unsigned N = Sel.getNumArgs();
2705 clang::io::Emit16(Out, N);
2708 for (unsigned I = 0; I != N; ++I)
2709 clang::io::Emit32(Out,
2710 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2713 void EmitData(raw_ostream& Out, key_type_ref,
2714 data_type_ref Methods, unsigned DataLen) {
2715 uint64_t Start = Out.tell(); (void)Start;
2716 clang::io::Emit32(Out, Methods.ID);
2717 unsigned NumInstanceMethods = 0;
2718 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2719 Method = Method->getNext())
2721 ++NumInstanceMethods;
2723 unsigned NumFactoryMethods = 0;
2724 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2725 Method = Method->getNext())
2727 ++NumFactoryMethods;
2729 unsigned InstanceBits = Methods.Instance.getBits();
2730 assert(InstanceBits < 4);
2731 unsigned NumInstanceMethodsAndBits =
2732 (NumInstanceMethods << 2) | InstanceBits;
2733 unsigned FactoryBits = Methods.Factory.getBits();
2734 assert(FactoryBits < 4);
2735 unsigned NumFactoryMethodsAndBits = (NumFactoryMethods << 2) | FactoryBits;
2736 clang::io::Emit16(Out, NumInstanceMethodsAndBits);
2737 clang::io::Emit16(Out, NumFactoryMethodsAndBits);
2738 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2739 Method = Method->getNext())
2741 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2742 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2743 Method = Method->getNext())
2745 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2747 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2750 } // end anonymous namespace
2752 /// \brief Write ObjC data: selectors and the method pool.
2754 /// The method pool contains both instance and factory methods, stored
2755 /// in an on-disk hash table indexed by the selector. The hash table also
2756 /// contains an empty entry for every other selector known to Sema.
2757 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2758 using namespace llvm;
2760 // Do we have to do anything at all?
2761 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2763 unsigned NumTableEntries = 0;
2764 // Create and write out the blob that contains selectors and the method pool.
2766 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2767 ASTMethodPoolTrait Trait(*this);
2769 // Create the on-disk hash table representation. We walk through every
2770 // selector we've seen and look it up in the method pool.
2771 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2772 for (llvm::DenseMap<Selector, SelectorID>::iterator
2773 I = SelectorIDs.begin(), E = SelectorIDs.end();
2775 Selector S = I->first;
2776 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2777 ASTMethodPoolTrait::data_type Data = {
2782 if (F != SemaRef.MethodPool.end()) {
2783 Data.Instance = F->second.first;
2784 Data.Factory = F->second.second;
2786 // Only write this selector if it's not in an existing AST or something
2788 if (Chain && I->second < FirstSelectorID) {
2789 // Selector already exists. Did it change?
2790 bool changed = false;
2791 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
2793 if (!M->Method->isFromASTFile())
2796 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
2798 if (!M->Method->isFromASTFile())
2803 } else if (Data.Instance.Method || Data.Factory.Method) {
2804 // A new method pool entry.
2807 Generator.insert(S, Data, Trait);
2810 // Create the on-disk hash table in a buffer.
2811 SmallString<4096> MethodPool;
2812 uint32_t BucketOffset;
2814 ASTMethodPoolTrait Trait(*this);
2815 llvm::raw_svector_ostream Out(MethodPool);
2816 // Make sure that no bucket is at offset 0
2817 clang::io::Emit32(Out, 0);
2818 BucketOffset = Generator.Emit(Out, Trait);
2821 // Create a blob abbreviation
2822 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2823 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
2824 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2825 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2826 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2827 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
2829 // Write the method pool
2831 Record.push_back(METHOD_POOL);
2832 Record.push_back(BucketOffset);
2833 Record.push_back(NumTableEntries);
2834 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
2836 // Create a blob abbreviation for the selector table offsets.
2837 Abbrev = new BitCodeAbbrev();
2838 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
2839 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2840 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2841 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2842 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2844 // Write the selector offsets table.
2846 Record.push_back(SELECTOR_OFFSETS);
2847 Record.push_back(SelectorOffsets.size());
2848 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
2849 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
2850 data(SelectorOffsets));
2854 /// \brief Write the selectors referenced in @selector expression into AST file.
2855 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
2856 using namespace llvm;
2857 if (SemaRef.ReferencedSelectors.empty())
2862 // Note: this writes out all references even for a dependent AST. But it is
2863 // very tricky to fix, and given that @selector shouldn't really appear in
2864 // headers, probably not worth it. It's not a correctness issue.
2865 for (DenseMap<Selector, SourceLocation>::iterator S =
2866 SemaRef.ReferencedSelectors.begin(),
2867 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
2868 Selector Sel = (*S).first;
2869 SourceLocation Loc = (*S).second;
2870 AddSelectorRef(Sel, Record);
2871 AddSourceLocation(Loc, Record);
2873 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
2876 //===----------------------------------------------------------------------===//
2877 // Identifier Table Serialization
2878 //===----------------------------------------------------------------------===//
2881 class ASTIdentifierTableTrait {
2884 IdentifierResolver &IdResolver;
2887 /// \brief Determines whether this is an "interesting" identifier
2888 /// that needs a full IdentifierInfo structure written into the hash
2890 bool isInterestingIdentifier(IdentifierInfo *II, MacroDirective *&Macro) {
2891 if (II->isPoisoned() ||
2892 II->isExtensionToken() ||
2893 II->getObjCOrBuiltinID() ||
2894 II->hasRevertedTokenIDToIdentifier() ||
2895 II->getFETokenInfo<void>())
2898 return hadMacroDefinition(II, Macro);
2901 bool hadMacroDefinition(IdentifierInfo *II, MacroDirective *&Macro) {
2902 if (!II->hadMacroDefinition())
2905 if (Macro || (Macro = PP.getMacroDirectiveHistory(II))) {
2907 return !shouldIgnoreMacro(Macro, IsModule, PP);
2909 if (getFirstPublicSubmoduleMacro(Macro, ModID))
2916 DefMacroDirective *getFirstPublicSubmoduleMacro(MacroDirective *MD,
2917 SubmoduleID &ModID) {
2919 if (DefMacroDirective *DefMD = getPublicSubmoduleMacro(MD, ModID))
2920 if (!shouldIgnoreMacro(DefMD, IsModule, PP))
2925 DefMacroDirective *getNextPublicSubmoduleMacro(DefMacroDirective *MD,
2926 SubmoduleID &ModID) {
2927 if (DefMacroDirective *
2928 DefMD = getPublicSubmoduleMacro(MD->getPrevious(), ModID))
2929 if (!shouldIgnoreMacro(DefMD, IsModule, PP))
2934 /// \brief Traverses the macro directives history and returns the latest
2935 /// macro that is public and not undefined in the same submodule.
2936 /// A macro that is defined in submodule A and undefined in submodule B,
2937 /// will still be considered as defined/exported from submodule A.
2938 DefMacroDirective *getPublicSubmoduleMacro(MacroDirective *MD,
2939 SubmoduleID &ModID) {
2943 SubmoduleID OrigModID = ModID;
2944 bool isUndefined = false;
2945 Optional<bool> isPublic;
2946 for (; MD; MD = MD->getPrevious()) {
2950 SubmoduleID ThisModID = getSubmoduleID(MD);
2951 if (ThisModID == 0) {
2952 isUndefined = false;
2953 isPublic = Optional<bool>();
2956 if (ThisModID != ModID){
2958 isUndefined = false;
2959 isPublic = Optional<bool>();
2961 // We are looking for a definition in a different submodule than the one
2962 // that we started with. If a submodule has re-definitions of the same
2963 // macro, only the last definition will be used as the "exported" one.
2964 if (ModID == OrigModID)
2967 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2968 if (!isUndefined && (!isPublic.hasValue() || isPublic.getValue()))
2973 if (isa<UndefMacroDirective>(MD)) {
2978 VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
2979 if (!isPublic.hasValue())
2980 isPublic = VisMD->isPublic();
2986 SubmoduleID getSubmoduleID(MacroDirective *MD) {
2987 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2988 MacroInfo *MI = DefMD->getInfo();
2989 if (unsigned ID = MI->getOwningModuleID())
2991 return Writer.inferSubmoduleIDFromLocation(MI->getDefinitionLoc());
2993 return Writer.inferSubmoduleIDFromLocation(MD->getLocation());
2997 typedef IdentifierInfo* key_type;
2998 typedef key_type key_type_ref;
3000 typedef IdentID data_type;
3001 typedef data_type data_type_ref;
3003 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3004 IdentifierResolver &IdResolver, bool IsModule)
3005 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { }
3007 static unsigned ComputeHash(const IdentifierInfo* II) {
3008 return llvm::HashString(II->getName());
3011 std::pair<unsigned,unsigned>
3012 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3013 unsigned KeyLen = II->getLength() + 1;
3014 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3015 MacroDirective *Macro = 0;
3016 if (isInterestingIdentifier(II, Macro)) {
3017 DataLen += 2; // 2 bytes for builtin ID
3018 DataLen += 2; // 2 bytes for flags
3019 if (hadMacroDefinition(II, Macro)) {
3020 DataLen += 4; // MacroDirectives offset.
3023 for (DefMacroDirective *
3024 DefMD = getFirstPublicSubmoduleMacro(Macro, ModID);
3025 DefMD; DefMD = getNextPublicSubmoduleMacro(DefMD, ModID)) {
3026 DataLen += 4; // MacroInfo ID.
3032 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3033 DEnd = IdResolver.end();
3035 DataLen += sizeof(DeclID);
3037 clang::io::Emit16(Out, DataLen);
3038 // We emit the key length after the data length so that every
3039 // string is preceded by a 16-bit length. This matches the PTH
3040 // format for storing identifiers.
3041 clang::io::Emit16(Out, KeyLen);
3042 return std::make_pair(KeyLen, DataLen);
3045 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3047 // Record the location of the key data. This is used when generating
3048 // the mapping from persistent IDs to strings.
3049 Writer.SetIdentifierOffset(II, Out.tell());
3050 Out.write(II->getNameStart(), KeyLen);
3053 void EmitData(raw_ostream& Out, IdentifierInfo* II,
3054 IdentID ID, unsigned) {
3055 MacroDirective *Macro = 0;
3056 if (!isInterestingIdentifier(II, Macro)) {
3057 clang::io::Emit32(Out, ID << 1);
3061 clang::io::Emit32(Out, (ID << 1) | 0x01);
3062 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3063 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3064 clang::io::Emit16(Out, Bits);
3066 bool HadMacroDefinition = hadMacroDefinition(II, Macro);
3067 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3068 Bits = (Bits << 1) | unsigned(IsModule);
3069 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3070 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3071 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3072 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3073 clang::io::Emit16(Out, Bits);
3075 if (HadMacroDefinition) {
3076 clang::io::Emit32(Out, Writer.getMacroDirectivesOffset(II));
3078 // Write the IDs of macros coming from different submodules.
3080 for (DefMacroDirective *
3081 DefMD = getFirstPublicSubmoduleMacro(Macro, ModID);
3082 DefMD; DefMD = getNextPublicSubmoduleMacro(DefMD, ModID)) {
3083 MacroID InfoID = Writer.getMacroID(DefMD->getInfo());
3085 clang::io::Emit32(Out, InfoID);
3087 clang::io::Emit32(Out, 0);
3091 // Emit the declaration IDs in reverse order, because the
3092 // IdentifierResolver provides the declarations as they would be
3093 // visible (e.g., the function "stat" would come before the struct
3094 // "stat"), but the ASTReader adds declarations to the end of the list
3095 // (so we need to see the struct "status" before the function "status").
3096 // Only emit declarations that aren't from a chained PCH, though.
3097 SmallVector<Decl *, 16> Decls(IdResolver.begin(II),
3099 for (SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
3100 DEnd = Decls.rend();
3102 clang::io::Emit32(Out, Writer.getDeclID(getMostRecentLocalDecl(*D)));
3105 /// \brief Returns the most recent local decl or the given decl if there are
3106 /// no local ones. The given decl is assumed to be the most recent one.
3107 Decl *getMostRecentLocalDecl(Decl *Orig) {
3108 // The only way a "from AST file" decl would be more recent from a local one
3109 // is if it came from a module.
3110 if (!PP.getLangOpts().Modules)
3113 // Look for a local in the decl chain.
3114 for (Decl *D = Orig; D; D = D->getPreviousDecl()) {
3115 if (!D->isFromASTFile())
3117 // If we come up a decl from a (chained-)PCH stop since we won't find a
3119 if (D->getOwningModuleID() == 0)
3126 } // end anonymous namespace
3128 /// \brief Write the identifier table into the AST file.
3130 /// The identifier table consists of a blob containing string data
3131 /// (the actual identifiers themselves) and a separate "offsets" index
3132 /// that maps identifier IDs to locations within the blob.
3133 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3134 IdentifierResolver &IdResolver,
3136 using namespace llvm;
3138 // Create and write out the blob that contains the identifier
3141 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3142 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
3144 // Look for any identifiers that were named while processing the
3145 // headers, but are otherwise not needed. We add these to the hash
3146 // table to enable checking of the predefines buffer in the case
3147 // where the user adds new macro definitions when building the AST
3149 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3150 IDEnd = PP.getIdentifierTable().end();
3152 getIdentifierRef(ID->second);
3154 // Create the on-disk hash table representation. We only store offsets
3155 // for identifiers that appear here for the first time.
3156 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3157 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
3158 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
3159 ID != IDEnd; ++ID) {
3160 assert(ID->first && "NULL identifier in identifier table");
3161 if (!Chain || !ID->first->isFromAST() ||
3162 ID->first->hasChangedSinceDeserialization())
3163 Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second,
3167 // Create the on-disk hash table in a buffer.
3168 SmallString<4096> IdentifierTable;
3169 uint32_t BucketOffset;
3171 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
3172 llvm::raw_svector_ostream Out(IdentifierTable);
3173 // Make sure that no bucket is at offset 0
3174 clang::io::Emit32(Out, 0);
3175 BucketOffset = Generator.Emit(Out, Trait);
3178 // Create a blob abbreviation
3179 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3180 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3181 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3182 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3183 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
3185 // Write the identifier table
3187 Record.push_back(IDENTIFIER_TABLE);
3188 Record.push_back(BucketOffset);
3189 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
3192 // Write the offsets table for identifier IDs.
3193 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3194 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3195 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3196 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3197 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3198 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3201 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3202 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3206 Record.push_back(IDENTIFIER_OFFSET);
3207 Record.push_back(IdentifierOffsets.size());
3208 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
3209 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3210 data(IdentifierOffsets));
3213 //===----------------------------------------------------------------------===//
3214 // DeclContext's Name Lookup Table Serialization
3215 //===----------------------------------------------------------------------===//
3218 // Trait used for the on-disk hash table used in the method pool.
3219 class ASTDeclContextNameLookupTrait {
3223 typedef DeclarationName key_type;
3224 typedef key_type key_type_ref;
3226 typedef DeclContext::lookup_result data_type;
3227 typedef const data_type& data_type_ref;
3229 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3231 unsigned ComputeHash(DeclarationName Name) {
3232 llvm::FoldingSetNodeID ID;
3233 ID.AddInteger(Name.getNameKind());
3235 switch (Name.getNameKind()) {
3236 case DeclarationName::Identifier:
3237 ID.AddString(Name.getAsIdentifierInfo()->getName());
3239 case DeclarationName::ObjCZeroArgSelector:
3240 case DeclarationName::ObjCOneArgSelector:
3241 case DeclarationName::ObjCMultiArgSelector:
3242 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
3244 case DeclarationName::CXXConstructorName:
3245 case DeclarationName::CXXDestructorName:
3246 case DeclarationName::CXXConversionFunctionName:
3248 case DeclarationName::CXXOperatorName:
3249 ID.AddInteger(Name.getCXXOverloadedOperator());
3251 case DeclarationName::CXXLiteralOperatorName:
3252 ID.AddString(Name.getCXXLiteralIdentifier()->getName());
3253 case DeclarationName::CXXUsingDirective:
3257 return ID.ComputeHash();
3260 std::pair<unsigned,unsigned>
3261 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
3262 data_type_ref Lookup) {
3263 unsigned KeyLen = 1;
3264 switch (Name.getNameKind()) {
3265 case DeclarationName::Identifier:
3266 case DeclarationName::ObjCZeroArgSelector:
3267 case DeclarationName::ObjCOneArgSelector:
3268 case DeclarationName::ObjCMultiArgSelector:
3269 case DeclarationName::CXXLiteralOperatorName:
3272 case DeclarationName::CXXOperatorName:
3275 case DeclarationName::CXXConstructorName:
3276 case DeclarationName::CXXDestructorName:
3277 case DeclarationName::CXXConversionFunctionName:
3278 case DeclarationName::CXXUsingDirective:
3281 clang::io::Emit16(Out, KeyLen);
3283 // 2 bytes for num of decls and 4 for each DeclID.
3284 unsigned DataLen = 2 + 4 * Lookup.size();
3285 clang::io::Emit16(Out, DataLen);
3287 return std::make_pair(KeyLen, DataLen);
3290 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
3291 using namespace clang::io;
3293 Emit8(Out, Name.getNameKind());
3294 switch (Name.getNameKind()) {
3295 case DeclarationName::Identifier:
3296 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
3298 case DeclarationName::ObjCZeroArgSelector:
3299 case DeclarationName::ObjCOneArgSelector:
3300 case DeclarationName::ObjCMultiArgSelector:
3301 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
3303 case DeclarationName::CXXOperatorName:
3304 assert(Name.getCXXOverloadedOperator() < NUM_OVERLOADED_OPERATORS &&
3305 "Invalid operator?");
3306 Emit8(Out, Name.getCXXOverloadedOperator());
3308 case DeclarationName::CXXLiteralOperatorName:
3309 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
3311 case DeclarationName::CXXConstructorName:
3312 case DeclarationName::CXXDestructorName:
3313 case DeclarationName::CXXConversionFunctionName:
3314 case DeclarationName::CXXUsingDirective:
3318 llvm_unreachable("Invalid name kind?");
3321 void EmitData(raw_ostream& Out, key_type_ref,
3322 data_type Lookup, unsigned DataLen) {
3323 uint64_t Start = Out.tell(); (void)Start;
3324 clang::io::Emit16(Out, Lookup.size());
3325 for (DeclContext::lookup_iterator I = Lookup.begin(), E = Lookup.end();
3327 clang::io::Emit32(Out, Writer.GetDeclRef(*I));
3329 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3332 } // end anonymous namespace
3334 /// \brief Write the block containing all of the declaration IDs
3335 /// visible from the given DeclContext.
3337 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3338 /// bitstream, or 0 if no block was written.
3339 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3341 if (DC->getPrimaryContext() != DC)
3344 // Since there is no name lookup into functions or methods, don't bother to
3345 // build a visible-declarations table for these entities.
3346 if (DC->isFunctionOrMethod())
3349 // If not in C++, we perform name lookup for the translation unit via the
3350 // IdentifierInfo chains, don't bother to build a visible-declarations table.
3351 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3354 // Serialize the contents of the mapping used for lookup. Note that,
3355 // although we have two very different code paths, the serialized
3356 // representation is the same for both cases: a declaration name,
3357 // followed by a size, followed by references to the visible
3358 // declarations that have that name.
3359 uint64_t Offset = Stream.GetCurrentBitNo();
3360 StoredDeclsMap *Map = DC->buildLookup();
3361 if (!Map || Map->empty())
3364 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
3365 ASTDeclContextNameLookupTrait Trait(*this);
3367 // Create the on-disk hash table representation.
3368 DeclarationName ConversionName;
3369 SmallVector<NamedDecl *, 4> ConversionDecls;
3370 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
3372 DeclarationName Name = D->first;
3373 DeclContext::lookup_result Result = D->second.getLookupResult();
3374 if (!Result.empty()) {
3375 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3376 // Hash all conversion function names to the same name. The actual
3377 // type information in conversion function name is not used in the
3378 // key (since such type information is not stable across different
3379 // modules), so the intended effect is to coalesce all of the conversion
3380 // functions under a single key.
3381 if (!ConversionName)
3382 ConversionName = Name;
3383 ConversionDecls.append(Result.begin(), Result.end());
3387 Generator.insert(Name, Result, Trait);
3391 // Add the conversion functions
3392 if (!ConversionDecls.empty()) {
3393 Generator.insert(ConversionName,
3394 DeclContext::lookup_result(ConversionDecls.begin(),
3395 ConversionDecls.end()),
3399 // Create the on-disk hash table in a buffer.
3400 SmallString<4096> LookupTable;
3401 uint32_t BucketOffset;
3403 llvm::raw_svector_ostream Out(LookupTable);
3404 // Make sure that no bucket is at offset 0
3405 clang::io::Emit32(Out, 0);
3406 BucketOffset = Generator.Emit(Out, Trait);
3409 // Write the lookup table
3411 Record.push_back(DECL_CONTEXT_VISIBLE);
3412 Record.push_back(BucketOffset);
3413 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3416 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
3417 ++NumVisibleDeclContexts;
3421 /// \brief Write an UPDATE_VISIBLE block for the given context.
3423 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3424 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3425 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3426 /// enumeration members (in C++11).
3427 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3428 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
3429 if (!Map || Map->empty())
3432 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
3433 ASTDeclContextNameLookupTrait Trait(*this);
3435 // Create the hash table.
3436 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
3438 DeclarationName Name = D->first;
3439 DeclContext::lookup_result Result = D->second.getLookupResult();
3440 // For any name that appears in this table, the results are complete, i.e.
3441 // they overwrite results from previous PCHs. Merging is always a mess.
3442 if (!Result.empty())
3443 Generator.insert(Name, Result, Trait);
3446 // Create the on-disk hash table in a buffer.
3447 SmallString<4096> LookupTable;
3448 uint32_t BucketOffset;
3450 llvm::raw_svector_ostream Out(LookupTable);
3451 // Make sure that no bucket is at offset 0
3452 clang::io::Emit32(Out, 0);
3453 BucketOffset = Generator.Emit(Out, Trait);
3456 // Write the lookup table
3458 Record.push_back(UPDATE_VISIBLE);
3459 Record.push_back(getDeclID(cast<Decl>(DC)));
3460 Record.push_back(BucketOffset);
3461 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
3464 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3465 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3467 Record.push_back(Opts.fp_contract);
3468 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3471 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3472 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3473 if (!SemaRef.Context.getLangOpts().OpenCL)
3476 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3478 #define OPENCLEXT(nm) Record.push_back(Opts.nm);
3479 #include "clang/Basic/OpenCLExtensions.def"
3480 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3483 void ASTWriter::WriteRedeclarations() {
3484 RecordData LocalRedeclChains;
3485 SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
3487 for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
3488 Decl *First = Redeclarations[I];
3489 assert(First->getPreviousDecl() == 0 && "Not the first declaration?");
3491 Decl *MostRecent = First->getMostRecentDecl();
3493 // If we only have a single declaration, there is no point in storing
3494 // a redeclaration chain.
3495 if (First == MostRecent)
3498 unsigned Offset = LocalRedeclChains.size();
3500 LocalRedeclChains.push_back(0); // Placeholder for the size.
3502 // Collect the set of local redeclarations of this declaration.
3503 for (Decl *Prev = MostRecent; Prev != First;
3504 Prev = Prev->getPreviousDecl()) {
3505 if (!Prev->isFromASTFile()) {
3506 AddDeclRef(Prev, LocalRedeclChains);
3511 if (!First->isFromASTFile() && Chain) {
3512 Decl *FirstFromAST = MostRecent;
3513 for (Decl *Prev = MostRecent; Prev; Prev = Prev->getPreviousDecl()) {
3514 if (Prev->isFromASTFile())
3515 FirstFromAST = Prev;
3518 Chain->MergedDecls[FirstFromAST].push_back(getDeclID(First));
3521 LocalRedeclChains[Offset] = Size;
3523 // Reverse the set of local redeclarations, so that we store them in
3524 // order (since we found them in reverse order).
3525 std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
3527 // Add the mapping from the first ID from the AST to the set of local
3529 LocalRedeclarationsInfo Info = { getDeclID(First), Offset };
3530 LocalRedeclsMap.push_back(Info);
3532 assert(N == Redeclarations.size() &&
3533 "Deserialized a declaration we shouldn't have");
3536 if (LocalRedeclChains.empty())
3539 // Sort the local redeclarations map by the first declaration ID,
3540 // since the reader will be performing binary searches on this information.
3541 llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
3543 // Emit the local redeclarations map.
3544 using namespace llvm;
3545 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3546 Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
3547 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3548 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3549 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3552 Record.push_back(LOCAL_REDECLARATIONS_MAP);
3553 Record.push_back(LocalRedeclsMap.size());
3554 Stream.EmitRecordWithBlob(AbbrevID, Record,
3555 reinterpret_cast<char*>(LocalRedeclsMap.data()),
3556 LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
3558 // Emit the redeclaration chains.
3559 Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
3562 void ASTWriter::WriteObjCCategories() {
3563 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3564 RecordData Categories;
3566 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3568 unsigned StartIndex = Categories.size();
3570 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3572 // Allocate space for the size.
3573 Categories.push_back(0);
3575 // Add the categories.
3576 for (ObjCInterfaceDecl::known_categories_iterator
3577 Cat = Class->known_categories_begin(),
3578 CatEnd = Class->known_categories_end();
3579 Cat != CatEnd; ++Cat, ++Size) {
3580 assert(getDeclID(*Cat) != 0 && "Bogus category");
3581 AddDeclRef(*Cat, Categories);
3585 Categories[StartIndex] = Size;
3587 // Record this interface -> category map.
3588 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3589 CategoriesMap.push_back(CatInfo);
3592 // Sort the categories map by the definition ID, since the reader will be
3593 // performing binary searches on this information.
3594 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3596 // Emit the categories map.
3597 using namespace llvm;
3598 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3599 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3600 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3601 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3602 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3605 Record.push_back(OBJC_CATEGORIES_MAP);
3606 Record.push_back(CategoriesMap.size());
3607 Stream.EmitRecordWithBlob(AbbrevID, Record,
3608 reinterpret_cast<char*>(CategoriesMap.data()),
3609 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3611 // Emit the category lists.
3612 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3615 void ASTWriter::WriteMergedDecls() {
3616 if (!Chain || Chain->MergedDecls.empty())
3620 for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(),
3621 IEnd = Chain->MergedDecls.end();
3623 DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID()
3624 : getDeclID(I->first);
3625 assert(CanonID && "Merged declaration not known?");
3627 Record.push_back(CanonID);
3628 Record.push_back(I->second.size());
3629 Record.append(I->second.begin(), I->second.end());
3631 Stream.EmitRecord(MERGED_DECLARATIONS, Record);
3634 //===----------------------------------------------------------------------===//
3635 // General Serialization Routines
3636 //===----------------------------------------------------------------------===//
3638 /// \brief Write a record containing the given attributes.
3639 void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
3640 RecordDataImpl &Record) {
3641 Record.push_back(Attrs.size());
3642 for (ArrayRef<const Attr *>::iterator i = Attrs.begin(),
3643 e = Attrs.end(); i != e; ++i){
3645 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
3646 AddSourceRange(A->getRange(), Record);
3648 #include "clang/Serialization/AttrPCHWrite.inc"
3653 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
3654 AddSourceLocation(Tok.getLocation(), Record);
3655 Record.push_back(Tok.getLength());
3657 // FIXME: When reading literal tokens, reconstruct the literal pointer
3659 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
3660 // FIXME: Should translate token kind to a stable encoding.
3661 Record.push_back(Tok.getKind());
3662 // FIXME: Should translate token flags to a stable encoding.
3663 Record.push_back(Tok.getFlags());
3666 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
3667 Record.push_back(Str.size());
3668 Record.insert(Record.end(), Str.begin(), Str.end());
3671 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
3672 RecordDataImpl &Record) {
3673 Record.push_back(Version.getMajor());
3674 if (Optional<unsigned> Minor = Version.getMinor())
3675 Record.push_back(*Minor + 1);
3677 Record.push_back(0);
3678 if (Optional<unsigned> Subminor = Version.getSubminor())
3679 Record.push_back(*Subminor + 1);
3681 Record.push_back(0);
3684 /// \brief Note that the identifier II occurs at the given offset
3685 /// within the identifier table.
3686 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
3687 IdentID ID = IdentifierIDs[II];
3688 // Only store offsets new to this AST file. Other identifier names are looked
3689 // up earlier in the chain and thus don't need an offset.
3690 if (ID >= FirstIdentID)
3691 IdentifierOffsets[ID - FirstIdentID] = Offset;
3694 /// \brief Note that the selector Sel occurs at the given offset
3695 /// within the method pool/selector table.
3696 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
3697 unsigned ID = SelectorIDs[Sel];
3698 assert(ID && "Unknown selector");
3699 // Don't record offsets for selectors that are also available in a different
3701 if (ID < FirstSelectorID)
3703 SelectorOffsets[ID - FirstSelectorID] = Offset;
3706 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
3707 : Stream(Stream), Context(0), PP(0), Chain(0), WritingModule(0),
3708 WritingAST(false), DoneWritingDeclsAndTypes(false),
3709 ASTHasCompilerErrors(false),
3710 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
3711 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
3712 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
3713 FirstMacroID(NUM_PREDEF_MACRO_IDS), NextMacroID(FirstMacroID),
3714 FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
3715 NextSubmoduleID(FirstSubmoduleID),
3716 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
3717 CollectedStmts(&StmtsToEmit),
3718 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
3719 NumVisibleDeclContexts(0),
3720 NextCXXBaseSpecifiersID(1),
3721 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0),
3722 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0),
3723 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0),
3724 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0),
3725 DeclTypedefAbbrev(0),
3726 DeclVarAbbrev(0), DeclFieldAbbrev(0),
3727 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0)
3731 ASTWriter::~ASTWriter() {
3732 for (FileDeclIDsTy::iterator
3733 I = FileDeclIDs.begin(), E = FileDeclIDs.end(); I != E; ++I)
3737 void ASTWriter::WriteAST(Sema &SemaRef,
3738 const std::string &OutputFile,
3739 Module *WritingModule, StringRef isysroot,
3743 ASTHasCompilerErrors = hasErrors;
3745 // Emit the file header.
3746 Stream.Emit((unsigned)'C', 8);
3747 Stream.Emit((unsigned)'P', 8);
3748 Stream.Emit((unsigned)'C', 8);
3749 Stream.Emit((unsigned)'H', 8);
3751 WriteBlockInfoBlock();
3753 Context = &SemaRef.Context;
3755 this->WritingModule = WritingModule;
3756 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
3759 this->WritingModule = 0;
3764 template<typename Vector>
3765 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
3766 ASTWriter::RecordData &Record) {
3767 for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end();
3769 Writer.AddDeclRef(*I, Record);
3773 void ASTWriter::WriteASTCore(Sema &SemaRef,
3775 const std::string &OutputFile,
3776 Module *WritingModule) {
3777 using namespace llvm;
3779 bool isModule = WritingModule != 0;
3781 // Make sure that the AST reader knows to finalize itself.
3783 Chain->finalizeForWriting();
3785 ASTContext &Context = SemaRef.Context;
3786 Preprocessor &PP = SemaRef.PP;
3788 // Set up predefined declaration IDs.
3789 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
3790 if (Context.ObjCIdDecl)
3791 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
3792 if (Context.ObjCSelDecl)
3793 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
3794 if (Context.ObjCClassDecl)
3795 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
3796 if (Context.ObjCProtocolClassDecl)
3797 DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID;
3798 if (Context.Int128Decl)
3799 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
3800 if (Context.UInt128Decl)
3801 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
3802 if (Context.ObjCInstanceTypeDecl)
3803 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
3804 if (Context.BuiltinVaListDecl)
3805 DeclIDs[Context.getBuiltinVaListDecl()] = PREDEF_DECL_BUILTIN_VA_LIST_ID;
3808 // Make sure that we emit IdentifierInfos (and any attached
3809 // declarations) for builtins. We don't need to do this when we're
3810 // emitting chained PCH files, because all of the builtins will be
3811 // in the original PCH file.
3812 // FIXME: Modules won't like this at all.
3813 IdentifierTable &Table = PP.getIdentifierTable();
3814 SmallVector<const char *, 32> BuiltinNames;
3815 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
3816 Context.getLangOpts().NoBuiltin);
3817 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
3818 getIdentifierRef(&Table.get(BuiltinNames[I]));
3821 // If there are any out-of-date identifiers, bring them up to date.
3822 if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) {
3823 // Find out-of-date identifiers.
3824 SmallVector<IdentifierInfo *, 4> OutOfDate;
3825 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3826 IDEnd = PP.getIdentifierTable().end();
3827 ID != IDEnd; ++ID) {
3828 if (ID->second->isOutOfDate())
3829 OutOfDate.push_back(ID->second);
3832 // Update the out-of-date identifiers.
3833 for (unsigned I = 0, N = OutOfDate.size(); I != N; ++I) {
3834 ExtSource->updateOutOfDateIdentifier(*OutOfDate[I]);
3838 // Build a record containing all of the tentative definitions in this file, in
3839 // TentativeDefinitions order. Generally, this record will be empty for
3841 RecordData TentativeDefinitions;
3842 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
3844 // Build a record containing all of the file scoped decls in this file.
3845 RecordData UnusedFileScopedDecls;
3847 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
3848 UnusedFileScopedDecls);
3850 // Build a record containing all of the delegating constructors we still need
3852 RecordData DelegatingCtorDecls;
3854 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
3856 // Write the set of weak, undeclared identifiers. We always write the
3857 // entire table, since later PCH files in a PCH chain are only interested in
3858 // the results at the end of the chain.
3859 RecordData WeakUndeclaredIdentifiers;
3860 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
3861 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
3862 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
3863 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
3864 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
3865 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
3866 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
3867 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
3871 // Build a record containing all of the locally-scoped extern "C"
3872 // declarations in this header file. Generally, this record will be
3874 RecordData LocallyScopedExternCDecls;
3875 // FIXME: This is filling in the AST file in densemap order which is
3877 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3878 TD = SemaRef.LocallyScopedExternCDecls.begin(),
3879 TDEnd = SemaRef.LocallyScopedExternCDecls.end();
3880 TD != TDEnd; ++TD) {
3881 if (!TD->second->isFromASTFile())
3882 AddDeclRef(TD->second, LocallyScopedExternCDecls);
3885 // Build a record containing all of the ext_vector declarations.
3886 RecordData ExtVectorDecls;
3887 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
3889 // Build a record containing all of the VTable uses information.
3890 RecordData VTableUses;
3891 if (!SemaRef.VTableUses.empty()) {
3892 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
3893 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
3894 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
3895 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
3899 // Build a record containing all of dynamic classes declarations.
3900 RecordData DynamicClasses;
3901 AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses);
3903 // Build a record containing all of pending implicit instantiations.
3904 RecordData PendingInstantiations;
3905 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
3906 I = SemaRef.PendingInstantiations.begin(),
3907 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
3908 AddDeclRef(I->first, PendingInstantiations);
3909 AddSourceLocation(I->second, PendingInstantiations);
3911 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
3912 "There are local ones at end of translation unit!");
3914 // Build a record containing some declaration references.
3915 RecordData SemaDeclRefs;
3916 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
3917 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
3918 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
3921 RecordData CUDASpecialDeclRefs;
3922 if (Context.getcudaConfigureCallDecl()) {
3923 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
3926 // Build a record containing all of the known namespaces.
3927 RecordData KnownNamespaces;
3928 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
3929 I = SemaRef.KnownNamespaces.begin(),
3930 IEnd = SemaRef.KnownNamespaces.end();
3933 AddDeclRef(I->first, KnownNamespaces);
3936 // Build a record of all used, undefined objects that require definitions.
3937 RecordData UndefinedButUsed;
3939 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
3940 SemaRef.getUndefinedButUsed(Undefined);
3941 for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
3942 I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
3943 AddDeclRef(I->first, UndefinedButUsed);
3944 AddSourceLocation(I->second, UndefinedButUsed);
3947 // Write the control block
3948 WriteControlBlock(PP, Context, isysroot, OutputFile);
3950 // Write the remaining AST contents.
3952 Stream.EnterSubblock(AST_BLOCK_ID, 5);
3954 // This is so that older clang versions, before the introduction
3955 // of the control block, can read and reject the newer PCH format.
3957 Record.push_back(VERSION_MAJOR);
3958 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
3960 // Create a lexical update block containing all of the declarations in the
3961 // translation unit that do not come from other AST files.
3962 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3963 SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
3964 for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
3965 E = TU->noload_decls_end();
3967 if (!(*I)->isFromASTFile())
3968 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
3971 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
3972 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
3973 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3974 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
3976 Record.push_back(TU_UPDATE_LEXICAL);
3977 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
3978 data(NewGlobalDecls));
3980 // And a visible updates block for the translation unit.
3981 Abv = new llvm::BitCodeAbbrev();
3982 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
3983 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3984 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
3985 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3986 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
3987 WriteDeclContextVisibleUpdate(TU);
3989 // If the translation unit has an anonymous namespace, and we don't already
3990 // have an update block for it, write it as an update block.
3991 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
3992 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
3993 if (Record.empty()) {
3994 Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE);
3995 Record.push_back(reinterpret_cast<uint64_t>(NS));
3999 // Make sure visible decls, added to DeclContexts previously loaded from
4000 // an AST file, are registered for serialization.
4001 for (SmallVector<const Decl *, 16>::iterator
4002 I = UpdatingVisibleDecls.begin(),
4003 E = UpdatingVisibleDecls.end(); I != E; ++I) {
4007 // Resolve any declaration pointers within the declaration updates block.
4008 ResolveDeclUpdatesBlocks();
4010 // Form the record of special types.
4011 RecordData SpecialTypes;
4012 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4013 AddTypeRef(Context.getFILEType(), SpecialTypes);
4014 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4015 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4016 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4017 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4018 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4019 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4021 // Keep writing types and declarations until all types and
4022 // declarations have been written.
4023 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
4024 WriteDeclsBlockAbbrevs();
4025 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
4026 E = DeclsToRewrite.end();
4028 DeclTypesToEmit.push(const_cast<Decl*>(*I));
4029 while (!DeclTypesToEmit.empty()) {
4030 DeclOrType DOT = DeclTypesToEmit.front();
4031 DeclTypesToEmit.pop();
4033 WriteType(DOT.getType());
4035 WriteDecl(Context, DOT.getDecl());
4039 DoneWritingDeclsAndTypes = true;
4041 WriteFileDeclIDsMap();
4042 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
4046 // Write the mapping information describing our module dependencies and how
4047 // each of those modules were mapped into our own offset/ID space, so that
4048 // the reader can build the appropriate mapping to its own offset/ID space.
4049 // The map consists solely of a blob with the following format:
4050 // *(module-name-len:i16 module-name:len*i8
4051 // source-location-offset:i32
4052 // identifier-id:i32
4053 // preprocessed-entity-id:i32
4054 // macro-definition-id:i32
4057 // declaration-id:i32
4058 // c++-base-specifiers-id:i32
4061 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
4062 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4063 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4064 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
4065 SmallString<2048> Buffer;
4067 llvm::raw_svector_ostream Out(Buffer);
4068 for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(),
4069 MEnd = Chain->ModuleMgr.end();
4071 StringRef FileName = (*M)->FileName;
4072 io::Emit16(Out, FileName.size());
4073 Out.write(FileName.data(), FileName.size());
4074 io::Emit32(Out, (*M)->SLocEntryBaseOffset);
4075 io::Emit32(Out, (*M)->BaseIdentifierID);
4076 io::Emit32(Out, (*M)->BaseMacroID);
4077 io::Emit32(Out, (*M)->BasePreprocessedEntityID);
4078 io::Emit32(Out, (*M)->BaseSubmoduleID);
4079 io::Emit32(Out, (*M)->BaseSelectorID);
4080 io::Emit32(Out, (*M)->BaseDeclID);
4081 io::Emit32(Out, (*M)->BaseTypeIndex);
4085 Record.push_back(MODULE_OFFSET_MAP);
4086 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4087 Buffer.data(), Buffer.size());
4089 WritePreprocessor(PP, isModule);
4090 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
4091 WriteSelectors(SemaRef);
4092 WriteReferencedSelectorsPool(SemaRef);
4093 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4094 WriteFPPragmaOptions(SemaRef.getFPOptions());
4095 WriteOpenCLExtensions(SemaRef);
4097 WriteTypeDeclOffsets();
4098 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
4100 WriteCXXBaseSpecifiersOffsets();
4102 // If we're emitting a module, write out the submodule information.
4104 WriteSubmodules(WritingModule);
4106 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4108 // Write the record containing external, unnamed definitions.
4109 if (!ExternalDefinitions.empty())
4110 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
4112 // Write the record containing tentative definitions.
4113 if (!TentativeDefinitions.empty())
4114 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4116 // Write the record containing unused file scoped decls.
4117 if (!UnusedFileScopedDecls.empty())
4118 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4120 // Write the record containing weak undeclared identifiers.
4121 if (!WeakUndeclaredIdentifiers.empty())
4122 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4123 WeakUndeclaredIdentifiers);
4125 // Write the record containing locally-scoped extern "C" definitions.
4126 if (!LocallyScopedExternCDecls.empty())
4127 Stream.EmitRecord(LOCALLY_SCOPED_EXTERN_C_DECLS,
4128 LocallyScopedExternCDecls);
4130 // Write the record containing ext_vector type names.
4131 if (!ExtVectorDecls.empty())
4132 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4134 // Write the record containing VTable uses information.
4135 if (!VTableUses.empty())
4136 Stream.EmitRecord(VTABLE_USES, VTableUses);
4138 // Write the record containing dynamic classes declarations.
4139 if (!DynamicClasses.empty())
4140 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
4142 // Write the record containing pending implicit instantiations.
4143 if (!PendingInstantiations.empty())
4144 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4146 // Write the record containing declaration references of Sema.
4147 if (!SemaDeclRefs.empty())
4148 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4150 // Write the record containing CUDA-specific declaration references.
4151 if (!CUDASpecialDeclRefs.empty())
4152 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4154 // Write the delegating constructors.
4155 if (!DelegatingCtorDecls.empty())
4156 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4158 // Write the known namespaces.
4159 if (!KnownNamespaces.empty())
4160 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4162 // Write the undefined internal functions and variables, and inline functions.
4163 if (!UndefinedButUsed.empty())
4164 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4166 // Write the visible updates to DeclContexts.
4167 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
4168 I = UpdatedDeclContexts.begin(),
4169 E = UpdatedDeclContexts.end();
4171 WriteDeclContextVisibleUpdate(*I);
4173 if (!WritingModule) {
4174 // Write the submodules that were imported, if any.
4175 RecordData ImportedModules;
4176 for (ASTContext::import_iterator I = Context.local_import_begin(),
4177 IEnd = Context.local_import_end();
4179 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4180 ImportedModules.push_back(SubmoduleIDs[I->getImportedModule()]);
4182 if (!ImportedModules.empty()) {
4184 llvm::array_pod_sort(ImportedModules.begin(), ImportedModules.end());
4186 // Unique module IDs.
4187 ImportedModules.erase(std::unique(ImportedModules.begin(),
4188 ImportedModules.end()),
4189 ImportedModules.end());
4191 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4195 WriteDeclUpdatesBlocks();
4196 WriteDeclReplacementsBlock();
4197 WriteRedeclarations();
4199 WriteObjCCategories();
4201 // Some simple statistics
4203 Record.push_back(NumStatements);
4204 Record.push_back(NumMacros);
4205 Record.push_back(NumLexicalDeclContexts);
4206 Record.push_back(NumVisibleDeclContexts);
4207 Stream.EmitRecord(STATISTICS, Record);
4211 /// \brief Go through the declaration update blocks and resolve declaration
4212 /// pointers into declaration IDs.
4213 void ASTWriter::ResolveDeclUpdatesBlocks() {
4214 for (DeclUpdateMap::iterator
4215 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
4216 const Decl *D = I->first;
4217 UpdateRecord &URec = I->second;
4220 continue; // The decl will be written completely
4222 unsigned Idx = 0, N = URec.size();
4224 switch ((DeclUpdateKind)URec[Idx++]) {
4225 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4226 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4227 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
4228 URec[Idx] = GetDeclRef(reinterpret_cast<Decl *>(URec[Idx]));
4232 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4240 void ASTWriter::WriteDeclUpdatesBlocks() {
4241 if (DeclUpdates.empty())
4244 RecordData OffsetsRecord;
4245 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
4246 for (DeclUpdateMap::iterator
4247 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
4248 const Decl *D = I->first;
4249 UpdateRecord &URec = I->second;
4252 continue; // The decl will be written completely,no need to store updates.
4254 uint64_t Offset = Stream.GetCurrentBitNo();
4255 Stream.EmitRecord(DECL_UPDATES, URec);
4257 OffsetsRecord.push_back(GetDeclRef(D));
4258 OffsetsRecord.push_back(Offset);
4261 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
4264 void ASTWriter::WriteDeclReplacementsBlock() {
4265 if (ReplacedDecls.empty())
4269 for (SmallVector<ReplacedDeclInfo, 16>::iterator
4270 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
4271 Record.push_back(I->ID);
4272 Record.push_back(I->Offset);
4273 Record.push_back(I->Loc);
4275 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
4278 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
4279 Record.push_back(Loc.getRawEncoding());
4282 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
4283 AddSourceLocation(Range.getBegin(), Record);
4284 AddSourceLocation(Range.getEnd(), Record);
4287 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
4288 Record.push_back(Value.getBitWidth());
4289 const uint64_t *Words = Value.getRawData();
4290 Record.append(Words, Words + Value.getNumWords());
4293 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
4294 Record.push_back(Value.isUnsigned());
4295 AddAPInt(Value, Record);
4298 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
4299 AddAPInt(Value.bitcastToAPInt(), Record);
4302 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
4303 Record.push_back(getIdentifierRef(II));
4306 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
4310 IdentID &ID = IdentifierIDs[II];
4316 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
4317 // Don't emit builtin macros like __LINE__ to the AST file unless they
4318 // have been redefined by the header (in which case they are not
4320 if (MI == 0 || MI->isBuiltinMacro())
4323 MacroID &ID = MacroIDs[MI];
4326 MacroInfoToEmitData Info = { Name, MI, ID };
4327 MacroInfosToEmit.push_back(Info);
4332 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
4333 if (MI == 0 || MI->isBuiltinMacro())
4336 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4337 return MacroIDs[MI];
4340 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
4341 assert(IdentMacroDirectivesOffsetMap[Name] && "not set!");
4342 return IdentMacroDirectivesOffsetMap[Name];
4345 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
4346 Record.push_back(getSelectorRef(SelRef));
4349 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
4350 if (Sel.getAsOpaquePtr() == 0) {
4354 SelectorID SID = SelectorIDs[Sel];
4355 if (SID == 0 && Chain) {
4356 // This might trigger a ReadSelector callback, which will set the ID for
4358 Chain->LoadSelector(Sel);
4359 SID = SelectorIDs[Sel];
4362 SID = NextSelectorID++;
4363 SelectorIDs[Sel] = SID;
4368 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
4369 AddDeclRef(Temp->getDestructor(), Record);
4372 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
4373 CXXBaseSpecifier const *BasesEnd,
4374 RecordDataImpl &Record) {
4375 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4376 CXXBaseSpecifiersToWrite.push_back(
4377 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4379 Record.push_back(NextCXXBaseSpecifiersID++);
4382 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
4383 const TemplateArgumentLocInfo &Arg,
4384 RecordDataImpl &Record) {
4386 case TemplateArgument::Expression:
4387 AddStmt(Arg.getAsExpr());
4389 case TemplateArgument::Type:
4390 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
4392 case TemplateArgument::Template:
4393 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
4394 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4396 case TemplateArgument::TemplateExpansion:
4397 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
4398 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4399 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
4401 case TemplateArgument::Null:
4402 case TemplateArgument::Integral:
4403 case TemplateArgument::Declaration:
4404 case TemplateArgument::NullPtr:
4405 case TemplateArgument::Pack:
4406 // FIXME: Is this right?
4411 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
4412 RecordDataImpl &Record) {
4413 AddTemplateArgument(Arg.getArgument(), Record);
4415 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4416 bool InfoHasSameExpr
4417 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4418 Record.push_back(InfoHasSameExpr);
4419 if (InfoHasSameExpr)
4420 return; // Avoid storing the same expr twice.
4422 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
4426 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
4427 RecordDataImpl &Record) {
4429 AddTypeRef(QualType(), Record);
4433 AddTypeLoc(TInfo->getTypeLoc(), Record);
4436 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
4437 AddTypeRef(TL.getType(), Record);
4439 TypeLocWriter TLW(*this, Record);
4440 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
4444 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
4445 Record.push_back(GetOrCreateTypeID(T));
4448 TypeID ASTWriter::GetOrCreateTypeID( QualType T) {
4449 return MakeTypeID(*Context, T,
4450 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
4453 TypeID ASTWriter::getTypeID(QualType T) const {
4454 return MakeTypeID(*Context, T,
4455 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
4458 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
4461 assert(!T.getLocalFastQualifiers());
4463 TypeIdx &Idx = TypeIdxs[T];
4464 if (Idx.getIndex() == 0) {
4465 if (DoneWritingDeclsAndTypes) {
4466 assert(0 && "New type seen after serializing all the types to emit!");
4470 // We haven't seen this type before. Assign it a new ID and put it
4471 // into the queue of types to emit.
4472 Idx = TypeIdx(NextTypeID++);
4473 DeclTypesToEmit.push(T);
4478 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
4481 assert(!T.getLocalFastQualifiers());
4483 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4484 assert(I != TypeIdxs.end() && "Type not emitted!");
4488 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
4489 Record.push_back(GetDeclRef(D));
4492 DeclID ASTWriter::GetDeclRef(const Decl *D) {
4493 assert(WritingAST && "Cannot request a declaration ID before AST writing");
4499 // If D comes from an AST file, its declaration ID is already known and
4501 if (D->isFromASTFile())
4502 return D->getGlobalID();
4504 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
4505 DeclID &ID = DeclIDs[D];
4507 if (DoneWritingDeclsAndTypes) {
4508 assert(0 && "New decl seen after serializing all the decls to emit!");
4512 // We haven't seen this declaration before. Give it a new ID and
4513 // enqueue it in the list of declarations to emit.
4515 DeclTypesToEmit.push(const_cast<Decl *>(D));
4521 DeclID ASTWriter::getDeclID(const Decl *D) {
4525 // If D comes from an AST file, its declaration ID is already known and
4527 if (D->isFromASTFile())
4528 return D->getGlobalID();
4530 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
4534 static inline bool compLocDecl(std::pair<unsigned, serialization::DeclID> L,
4535 std::pair<unsigned, serialization::DeclID> R) {
4536 return L.first < R.first;
4539 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
4543 SourceLocation Loc = D->getLocation();
4544 if (Loc.isInvalid())
4547 // We only keep track of the file-level declarations of each file.
4548 if (!D->getLexicalDeclContext()->isFileContext())
4550 // FIXME: ParmVarDecls that are part of a function type of a parameter of
4551 // a function/objc method, should not have TU as lexical context.
4552 if (isa<ParmVarDecl>(D))
4555 SourceManager &SM = Context->getSourceManager();
4556 SourceLocation FileLoc = SM.getFileLoc(Loc);
4557 assert(SM.isLocalSourceLocation(FileLoc));
4560 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
4561 if (FID.isInvalid())
4563 assert(SM.getSLocEntry(FID).isFile());
4565 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
4567 Info = new DeclIDInFileInfo();
4569 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
4570 LocDeclIDsTy &Decls = Info->DeclIDs;
4572 if (Decls.empty() || Decls.back().first <= Offset) {
4573 Decls.push_back(LocDecl);
4577 LocDeclIDsTy::iterator
4578 I = std::upper_bound(Decls.begin(), Decls.end(), LocDecl, compLocDecl);
4580 Decls.insert(I, LocDecl);
4583 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
4584 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
4585 Record.push_back(Name.getNameKind());
4586 switch (Name.getNameKind()) {
4587 case DeclarationName::Identifier:
4588 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
4591 case DeclarationName::ObjCZeroArgSelector:
4592 case DeclarationName::ObjCOneArgSelector:
4593 case DeclarationName::ObjCMultiArgSelector:
4594 AddSelectorRef(Name.getObjCSelector(), Record);
4597 case DeclarationName::CXXConstructorName:
4598 case DeclarationName::CXXDestructorName:
4599 case DeclarationName::CXXConversionFunctionName:
4600 AddTypeRef(Name.getCXXNameType(), Record);
4603 case DeclarationName::CXXOperatorName:
4604 Record.push_back(Name.getCXXOverloadedOperator());
4607 case DeclarationName::CXXLiteralOperatorName:
4608 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
4611 case DeclarationName::CXXUsingDirective:
4612 // No extra data to emit
4617 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
4618 DeclarationName Name, RecordDataImpl &Record) {
4619 switch (Name.getNameKind()) {
4620 case DeclarationName::CXXConstructorName:
4621 case DeclarationName::CXXDestructorName:
4622 case DeclarationName::CXXConversionFunctionName:
4623 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
4626 case DeclarationName::CXXOperatorName:
4628 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
4631 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
4635 case DeclarationName::CXXLiteralOperatorName:
4637 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
4641 case DeclarationName::Identifier:
4642 case DeclarationName::ObjCZeroArgSelector:
4643 case DeclarationName::ObjCOneArgSelector:
4644 case DeclarationName::ObjCMultiArgSelector:
4645 case DeclarationName::CXXUsingDirective:
4650 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4651 RecordDataImpl &Record) {
4652 AddDeclarationName(NameInfo.getName(), Record);
4653 AddSourceLocation(NameInfo.getLoc(), Record);
4654 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
4657 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
4658 RecordDataImpl &Record) {
4659 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
4660 Record.push_back(Info.NumTemplParamLists);
4661 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
4662 AddTemplateParameterList(Info.TemplParamLists[i], Record);
4665 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
4666 RecordDataImpl &Record) {
4667 // Nested name specifiers usually aren't too long. I think that 8 would
4668 // typically accommodate the vast majority.
4669 SmallVector<NestedNameSpecifier *, 8> NestedNames;
4671 // Push each of the NNS's onto a stack for serialization in reverse order.
4673 NestedNames.push_back(NNS);
4674 NNS = NNS->getPrefix();
4677 Record.push_back(NestedNames.size());
4678 while(!NestedNames.empty()) {
4679 NNS = NestedNames.pop_back_val();
4680 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
4681 Record.push_back(Kind);
4683 case NestedNameSpecifier::Identifier:
4684 AddIdentifierRef(NNS->getAsIdentifier(), Record);
4687 case NestedNameSpecifier::Namespace:
4688 AddDeclRef(NNS->getAsNamespace(), Record);
4691 case NestedNameSpecifier::NamespaceAlias:
4692 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
4695 case NestedNameSpecifier::TypeSpec:
4696 case NestedNameSpecifier::TypeSpecWithTemplate:
4697 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
4698 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
4701 case NestedNameSpecifier::Global:
4702 // Don't need to write an associated value.
4708 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4709 RecordDataImpl &Record) {
4710 // Nested name specifiers usually aren't too long. I think that 8 would
4711 // typically accommodate the vast majority.
4712 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
4714 // Push each of the nested-name-specifiers's onto a stack for
4715 // serialization in reverse order.
4717 NestedNames.push_back(NNS);
4718 NNS = NNS.getPrefix();
4721 Record.push_back(NestedNames.size());
4722 while(!NestedNames.empty()) {
4723 NNS = NestedNames.pop_back_val();
4724 NestedNameSpecifier::SpecifierKind Kind
4725 = NNS.getNestedNameSpecifier()->getKind();
4726 Record.push_back(Kind);
4728 case NestedNameSpecifier::Identifier:
4729 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
4730 AddSourceRange(NNS.getLocalSourceRange(), Record);
4733 case NestedNameSpecifier::Namespace:
4734 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
4735 AddSourceRange(NNS.getLocalSourceRange(), Record);
4738 case NestedNameSpecifier::NamespaceAlias:
4739 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
4740 AddSourceRange(NNS.getLocalSourceRange(), Record);
4743 case NestedNameSpecifier::TypeSpec:
4744 case NestedNameSpecifier::TypeSpecWithTemplate:
4745 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
4746 AddTypeLoc(NNS.getTypeLoc(), Record);
4747 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
4750 case NestedNameSpecifier::Global:
4751 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
4757 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
4758 TemplateName::NameKind Kind = Name.getKind();
4759 Record.push_back(Kind);
4761 case TemplateName::Template:
4762 AddDeclRef(Name.getAsTemplateDecl(), Record);
4765 case TemplateName::OverloadedTemplate: {
4766 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
4767 Record.push_back(OvT->size());
4768 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
4770 AddDeclRef(*I, Record);
4774 case TemplateName::QualifiedTemplate: {
4775 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
4776 AddNestedNameSpecifier(QualT->getQualifier(), Record);
4777 Record.push_back(QualT->hasTemplateKeyword());
4778 AddDeclRef(QualT->getTemplateDecl(), Record);
4782 case TemplateName::DependentTemplate: {
4783 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
4784 AddNestedNameSpecifier(DepT->getQualifier(), Record);
4785 Record.push_back(DepT->isIdentifier());
4786 if (DepT->isIdentifier())
4787 AddIdentifierRef(DepT->getIdentifier(), Record);
4789 Record.push_back(DepT->getOperator());
4793 case TemplateName::SubstTemplateTemplateParm: {
4794 SubstTemplateTemplateParmStorage *subst
4795 = Name.getAsSubstTemplateTemplateParm();
4796 AddDeclRef(subst->getParameter(), Record);
4797 AddTemplateName(subst->getReplacement(), Record);
4801 case TemplateName::SubstTemplateTemplateParmPack: {
4802 SubstTemplateTemplateParmPackStorage *SubstPack
4803 = Name.getAsSubstTemplateTemplateParmPack();
4804 AddDeclRef(SubstPack->getParameterPack(), Record);
4805 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
4811 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
4812 RecordDataImpl &Record) {
4813 Record.push_back(Arg.getKind());
4814 switch (Arg.getKind()) {
4815 case TemplateArgument::Null:
4817 case TemplateArgument::Type:
4818 AddTypeRef(Arg.getAsType(), Record);
4820 case TemplateArgument::Declaration:
4821 AddDeclRef(Arg.getAsDecl(), Record);
4822 Record.push_back(Arg.isDeclForReferenceParam());
4824 case TemplateArgument::NullPtr:
4825 AddTypeRef(Arg.getNullPtrType(), Record);
4827 case TemplateArgument::Integral:
4828 AddAPSInt(Arg.getAsIntegral(), Record);
4829 AddTypeRef(Arg.getIntegralType(), Record);
4831 case TemplateArgument::Template:
4832 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
4834 case TemplateArgument::TemplateExpansion:
4835 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
4836 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
4837 Record.push_back(*NumExpansions + 1);
4839 Record.push_back(0);
4841 case TemplateArgument::Expression:
4842 AddStmt(Arg.getAsExpr());
4844 case TemplateArgument::Pack:
4845 Record.push_back(Arg.pack_size());
4846 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
4848 AddTemplateArgument(*I, Record);
4854 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
4855 RecordDataImpl &Record) {
4856 assert(TemplateParams && "No TemplateParams!");
4857 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
4858 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
4859 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
4860 Record.push_back(TemplateParams->size());
4861 for (TemplateParameterList::const_iterator
4862 P = TemplateParams->begin(), PEnd = TemplateParams->end();
4864 AddDeclRef(*P, Record);
4867 /// \brief Emit a template argument list.
4869 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
4870 RecordDataImpl &Record) {
4871 assert(TemplateArgs && "No TemplateArgs!");
4872 Record.push_back(TemplateArgs->size());
4873 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
4874 AddTemplateArgument(TemplateArgs->get(i), Record);
4879 ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
4880 Record.push_back(Set.size());
4881 for (ASTUnresolvedSet::const_iterator
4882 I = Set.begin(), E = Set.end(); I != E; ++I) {
4883 AddDeclRef(I.getDecl(), Record);
4884 Record.push_back(I.getAccess());
4888 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
4889 RecordDataImpl &Record) {
4890 Record.push_back(Base.isVirtual());
4891 Record.push_back(Base.isBaseOfClass());
4892 Record.push_back(Base.getAccessSpecifierAsWritten());
4893 Record.push_back(Base.getInheritConstructors());
4894 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
4895 AddSourceRange(Base.getSourceRange(), Record);
4896 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
4901 void ASTWriter::FlushCXXBaseSpecifiers() {
4903 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
4906 // Record the offset of this base-specifier set.
4907 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
4908 if (Index == CXXBaseSpecifiersOffsets.size())
4909 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
4911 if (Index > CXXBaseSpecifiersOffsets.size())
4912 CXXBaseSpecifiersOffsets.resize(Index + 1);
4913 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
4916 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
4917 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
4918 Record.push_back(BEnd - B);
4919 for (; B != BEnd; ++B)
4920 AddCXXBaseSpecifier(*B, Record);
4921 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
4923 // Flush any expressions that were written as part of the base specifiers.
4927 CXXBaseSpecifiersToWrite.clear();
4930 void ASTWriter::AddCXXCtorInitializers(
4931 const CXXCtorInitializer * const *CtorInitializers,
4932 unsigned NumCtorInitializers,
4933 RecordDataImpl &Record) {
4934 Record.push_back(NumCtorInitializers);
4935 for (unsigned i=0; i != NumCtorInitializers; ++i) {
4936 const CXXCtorInitializer *Init = CtorInitializers[i];
4938 if (Init->isBaseInitializer()) {
4939 Record.push_back(CTOR_INITIALIZER_BASE);
4940 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
4941 Record.push_back(Init->isBaseVirtual());
4942 } else if (Init->isDelegatingInitializer()) {
4943 Record.push_back(CTOR_INITIALIZER_DELEGATING);
4944 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
4945 } else if (Init->isMemberInitializer()){
4946 Record.push_back(CTOR_INITIALIZER_MEMBER);
4947 AddDeclRef(Init->getMember(), Record);
4949 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
4950 AddDeclRef(Init->getIndirectMember(), Record);
4953 AddSourceLocation(Init->getMemberLocation(), Record);
4954 AddStmt(Init->getInit());
4955 AddSourceLocation(Init->getLParenLoc(), Record);
4956 AddSourceLocation(Init->getRParenLoc(), Record);
4957 Record.push_back(Init->isWritten());
4958 if (Init->isWritten()) {
4959 Record.push_back(Init->getSourceOrder());
4961 Record.push_back(Init->getNumArrayIndices());
4962 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
4963 AddDeclRef(Init->getArrayIndex(i), Record);
4968 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
4969 assert(D->DefinitionData);
4970 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
4971 Record.push_back(Data.IsLambda);
4972 Record.push_back(Data.UserDeclaredConstructor);
4973 Record.push_back(Data.UserDeclaredSpecialMembers);
4974 Record.push_back(Data.Aggregate);
4975 Record.push_back(Data.PlainOldData);
4976 Record.push_back(Data.Empty);
4977 Record.push_back(Data.Polymorphic);
4978 Record.push_back(Data.Abstract);
4979 Record.push_back(Data.IsStandardLayout);
4980 Record.push_back(Data.HasNoNonEmptyBases);
4981 Record.push_back(Data.HasPrivateFields);
4982 Record.push_back(Data.HasProtectedFields);
4983 Record.push_back(Data.HasPublicFields);
4984 Record.push_back(Data.HasMutableFields);
4985 Record.push_back(Data.HasOnlyCMembers);
4986 Record.push_back(Data.HasInClassInitializer);
4987 Record.push_back(Data.HasUninitializedReferenceMember);
4988 Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
4989 Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
4990 Record.push_back(Data.NeedOverloadResolutionForDestructor);
4991 Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
4992 Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
4993 Record.push_back(Data.DefaultedDestructorIsDeleted);
4994 Record.push_back(Data.HasTrivialSpecialMembers);
4995 Record.push_back(Data.HasIrrelevantDestructor);
4996 Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
4997 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
4998 Record.push_back(Data.HasConstexprDefaultConstructor);
4999 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
5000 Record.push_back(Data.ComputedVisibleConversions);
5001 Record.push_back(Data.UserProvidedDefaultConstructor);
5002 Record.push_back(Data.DeclaredSpecialMembers);
5003 Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
5004 Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
5005 Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5006 Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
5007 Record.push_back(Data.FailedImplicitMoveConstructor);
5008 Record.push_back(Data.FailedImplicitMoveAssignment);
5009 // IsLambda bit is already saved.
5011 Record.push_back(Data.NumBases);
5012 if (Data.NumBases > 0)
5013 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
5016 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5017 Record.push_back(Data.NumVBases);
5018 if (Data.NumVBases > 0)
5019 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
5022 AddUnresolvedSet(Data.Conversions, Record);
5023 AddUnresolvedSet(Data.VisibleConversions, Record);
5024 // Data.Definition is the owning decl, no need to write it.
5025 AddDeclRef(Data.FirstFriend, Record);
5027 // Add lambda-specific data.
5028 if (Data.IsLambda) {
5029 CXXRecordDecl::LambdaDefinitionData &Lambda = D->getLambdaData();
5030 Record.push_back(Lambda.Dependent);
5031 Record.push_back(Lambda.NumCaptures);
5032 Record.push_back(Lambda.NumExplicitCaptures);
5033 Record.push_back(Lambda.ManglingNumber);
5034 AddDeclRef(Lambda.ContextDecl, Record);
5035 AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
5036 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5037 LambdaExpr::Capture &Capture = Lambda.Captures[I];
5038 AddSourceLocation(Capture.getLocation(), Record);
5039 Record.push_back(Capture.isImplicit());
5040 Record.push_back(Capture.getCaptureKind()); // FIXME: stable!
5041 VarDecl *Var = Capture.capturesVariable()? Capture.getCapturedVar() : 0;
5042 AddDeclRef(Var, Record);
5043 AddSourceLocation(Capture.isPackExpansion()? Capture.getEllipsisLoc()
5050 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5051 assert(Reader && "Cannot remove chain");
5052 assert((!Chain || Chain == Reader) && "Cannot replace chain");
5053 assert(FirstDeclID == NextDeclID &&
5054 FirstTypeID == NextTypeID &&
5055 FirstIdentID == NextIdentID &&
5056 FirstMacroID == NextMacroID &&
5057 FirstSubmoduleID == NextSubmoduleID &&
5058 FirstSelectorID == NextSelectorID &&
5059 "Setting chain after writing has started.");
5063 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5064 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5065 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5066 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5067 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5068 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5069 NextDeclID = FirstDeclID;
5070 NextTypeID = FirstTypeID;
5071 NextIdentID = FirstIdentID;
5072 NextMacroID = FirstMacroID;
5073 NextSelectorID = FirstSelectorID;
5074 NextSubmoduleID = FirstSubmoduleID;
5077 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5078 // Always keep the highest ID. See \p TypeRead() for more information.
5079 IdentID &StoredID = IdentifierIDs[II];
5084 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5085 // Always keep the highest ID. See \p TypeRead() for more information.
5086 MacroID &StoredID = MacroIDs[MI];
5091 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5092 // Always take the highest-numbered type index. This copes with an interesting
5093 // case for chained AST writing where we schedule writing the type and then,
5094 // later, deserialize the type from another AST. In this case, we want to
5095 // keep the higher-numbered entry so that we can properly write it out to
5097 TypeIdx &StoredIdx = TypeIdxs[T];
5098 if (Idx.getIndex() >= StoredIdx.getIndex())
5102 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5103 // Always keep the highest ID. See \p TypeRead() for more information.
5104 SelectorID &StoredID = SelectorIDs[S];
5109 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5110 MacroDefinition *MD) {
5111 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5112 MacroDefinitions[MD] = ID;
5115 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5116 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5117 SubmoduleIDs[Mod] = ID;
5120 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5121 assert(D->isCompleteDefinition());
5122 assert(!WritingAST && "Already writing the AST!");
5123 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
5124 // We are interested when a PCH decl is modified.
5125 if (RD->isFromASTFile()) {
5126 // A forward reference was mutated into a definition. Rewrite it.
5127 // FIXME: This happens during template instantiation, should we
5128 // have created a new definition decl instead ?
5134 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5135 assert(!WritingAST && "Already writing the AST!");
5137 // TU and namespaces are handled elsewhere.
5138 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
5141 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
5142 return; // Not a source decl added to a DeclContext from PCH.
5144 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5145 AddUpdatedDeclContext(DC);
5146 UpdatingVisibleDecls.push_back(D);
5149 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5150 assert(!WritingAST && "Already writing the AST!");
5151 assert(D->isImplicit());
5152 if (!(!D->isFromASTFile() && RD->isFromASTFile()))
5153 return; // Not a source member added to a class from PCH.
5154 if (!isa<CXXMethodDecl>(D))
5155 return; // We are interested in lazily declared implicit methods.
5157 // A decl coming from PCH was modified.
5158 assert(RD->isCompleteDefinition());
5159 UpdateRecord &Record = DeclUpdates[RD];
5160 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
5161 Record.push_back(reinterpret_cast<uint64_t>(D));
5164 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
5165 const ClassTemplateSpecializationDecl *D) {
5166 // The specializations set is kept in the canonical template.
5167 assert(!WritingAST && "Already writing the AST!");
5168 TD = TD->getCanonicalDecl();
5169 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5170 return; // Not a source specialization added to a template from PCH.
5172 UpdateRecord &Record = DeclUpdates[TD];
5173 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
5174 Record.push_back(reinterpret_cast<uint64_t>(D));
5177 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
5178 const FunctionDecl *D) {
5179 // The specializations set is kept in the canonical template.
5180 assert(!WritingAST && "Already writing the AST!");
5181 TD = TD->getCanonicalDecl();
5182 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5183 return; // Not a source specialization added to a template from PCH.
5185 UpdateRecord &Record = DeclUpdates[TD];
5186 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
5187 Record.push_back(reinterpret_cast<uint64_t>(D));
5190 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
5191 assert(!WritingAST && "Already writing the AST!");
5192 if (!D->isFromASTFile())
5193 return; // Declaration not imported from PCH.
5195 // Implicit decl from a PCH was defined.
5196 // FIXME: Should implicit definition be a separate FunctionDecl?
5200 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
5201 assert(!WritingAST && "Already writing the AST!");
5202 if (!D->isFromASTFile())
5205 // Since the actual instantiation is delayed, this really means that we need
5206 // to update the instantiation location.
5207 UpdateRecord &Record = DeclUpdates[D];
5208 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER);
5210 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record);
5213 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5214 const ObjCInterfaceDecl *IFD) {
5215 assert(!WritingAST && "Already writing the AST!");
5216 if (!IFD->isFromASTFile())
5217 return; // Declaration not imported from PCH.
5219 assert(IFD->getDefinition() && "Category on a class without a definition?");
5220 ObjCClassesWithCategories.insert(
5221 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5225 void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
5226 const ObjCPropertyDecl *OrigProp,
5227 const ObjCCategoryDecl *ClassExt) {
5228 const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
5232 assert(!WritingAST && "Already writing the AST!");
5233 if (!D->isFromASTFile())
5234 return; // Declaration not imported from PCH.