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::VisitDecayedType(const DecayedType *T) {
112 Writer.AddTypeRef(T->getOriginalType(), Record);
116 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
117 Writer.AddTypeRef(T->getPointeeType(), Record);
118 Code = TYPE_BLOCK_POINTER;
121 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
122 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
123 Record.push_back(T->isSpelledAsLValue());
124 Code = TYPE_LVALUE_REFERENCE;
127 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
128 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
129 Code = TYPE_RVALUE_REFERENCE;
132 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
133 Writer.AddTypeRef(T->getPointeeType(), Record);
134 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
135 Code = TYPE_MEMBER_POINTER;
138 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
139 Writer.AddTypeRef(T->getElementType(), Record);
140 Record.push_back(T->getSizeModifier()); // FIXME: stable values
141 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
144 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
146 Writer.AddAPInt(T->getSize(), Record);
147 Code = TYPE_CONSTANT_ARRAY;
150 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
152 Code = TYPE_INCOMPLETE_ARRAY;
155 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
157 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
158 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
159 Writer.AddStmt(T->getSizeExpr());
160 Code = TYPE_VARIABLE_ARRAY;
163 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
164 Writer.AddTypeRef(T->getElementType(), Record);
165 Record.push_back(T->getNumElements());
166 Record.push_back(T->getVectorKind());
170 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
172 Code = TYPE_EXT_VECTOR;
175 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
176 Writer.AddTypeRef(T->getResultType(), Record);
177 FunctionType::ExtInfo C = T->getExtInfo();
178 Record.push_back(C.getNoReturn());
179 Record.push_back(C.getHasRegParm());
180 Record.push_back(C.getRegParm());
181 // FIXME: need to stabilize encoding of calling convention...
182 Record.push_back(C.getCC());
183 Record.push_back(C.getProducesResult());
186 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
187 VisitFunctionType(T);
188 Code = TYPE_FUNCTION_NO_PROTO;
191 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
192 VisitFunctionType(T);
193 Record.push_back(T->getNumArgs());
194 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
195 Writer.AddTypeRef(T->getArgType(I), Record);
196 Record.push_back(T->isVariadic());
197 Record.push_back(T->hasTrailingReturn());
198 Record.push_back(T->getTypeQuals());
199 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
200 Record.push_back(T->getExceptionSpecType());
201 if (T->getExceptionSpecType() == EST_Dynamic) {
202 Record.push_back(T->getNumExceptions());
203 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
204 Writer.AddTypeRef(T->getExceptionType(I), Record);
205 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
206 Writer.AddStmt(T->getNoexceptExpr());
207 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
208 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
209 Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
210 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
211 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
213 Code = TYPE_FUNCTION_PROTO;
216 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
217 Writer.AddDeclRef(T->getDecl(), Record);
218 Code = TYPE_UNRESOLVED_USING;
221 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
222 Writer.AddDeclRef(T->getDecl(), Record);
223 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
224 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
228 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
229 Writer.AddStmt(T->getUnderlyingExpr());
230 Code = TYPE_TYPEOF_EXPR;
233 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
234 Writer.AddTypeRef(T->getUnderlyingType(), Record);
238 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
239 Writer.AddTypeRef(T->getUnderlyingType(), Record);
240 Writer.AddStmt(T->getUnderlyingExpr());
241 Code = TYPE_DECLTYPE;
244 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
245 Writer.AddTypeRef(T->getBaseType(), Record);
246 Writer.AddTypeRef(T->getUnderlyingType(), Record);
247 Record.push_back(T->getUTTKind());
248 Code = TYPE_UNARY_TRANSFORM;
251 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
252 Writer.AddTypeRef(T->getDeducedType(), Record);
253 Record.push_back(T->isDecltypeAuto());
254 if (T->getDeducedType().isNull())
255 Record.push_back(T->isDependentType());
259 void ASTTypeWriter::VisitTagType(const TagType *T) {
260 Record.push_back(T->isDependentType());
261 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
262 assert(!T->isBeingDefined() &&
263 "Cannot serialize in the middle of a type definition");
266 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
271 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
276 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
277 Writer.AddTypeRef(T->getModifiedType(), Record);
278 Writer.AddTypeRef(T->getEquivalentType(), Record);
279 Record.push_back(T->getAttrKind());
280 Code = TYPE_ATTRIBUTED;
284 ASTTypeWriter::VisitSubstTemplateTypeParmType(
285 const SubstTemplateTypeParmType *T) {
286 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
287 Writer.AddTypeRef(T->getReplacementType(), Record);
288 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
292 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
293 const SubstTemplateTypeParmPackType *T) {
294 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
295 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
296 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
300 ASTTypeWriter::VisitTemplateSpecializationType(
301 const TemplateSpecializationType *T) {
302 Record.push_back(T->isDependentType());
303 Writer.AddTemplateName(T->getTemplateName(), Record);
304 Record.push_back(T->getNumArgs());
305 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
306 ArgI != ArgE; ++ArgI)
307 Writer.AddTemplateArgument(*ArgI, Record);
308 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
309 T->isCanonicalUnqualified() ? QualType()
310 : T->getCanonicalTypeInternal(),
312 Code = TYPE_TEMPLATE_SPECIALIZATION;
316 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
318 Writer.AddStmt(T->getSizeExpr());
319 Writer.AddSourceRange(T->getBracketsRange(), Record);
320 Code = TYPE_DEPENDENT_SIZED_ARRAY;
324 ASTTypeWriter::VisitDependentSizedExtVectorType(
325 const DependentSizedExtVectorType *T) {
326 // FIXME: Serialize this type (C++ only)
327 llvm_unreachable("Cannot serialize dependent sized extended vector types");
331 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
332 Record.push_back(T->getDepth());
333 Record.push_back(T->getIndex());
334 Record.push_back(T->isParameterPack());
335 Writer.AddDeclRef(T->getDecl(), Record);
336 Code = TYPE_TEMPLATE_TYPE_PARM;
340 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
341 Record.push_back(T->getKeyword());
342 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
343 Writer.AddIdentifierRef(T->getIdentifier(), Record);
344 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
345 : T->getCanonicalTypeInternal(),
347 Code = TYPE_DEPENDENT_NAME;
351 ASTTypeWriter::VisitDependentTemplateSpecializationType(
352 const DependentTemplateSpecializationType *T) {
353 Record.push_back(T->getKeyword());
354 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
355 Writer.AddIdentifierRef(T->getIdentifier(), Record);
356 Record.push_back(T->getNumArgs());
357 for (DependentTemplateSpecializationType::iterator
358 I = T->begin(), E = T->end(); I != E; ++I)
359 Writer.AddTemplateArgument(*I, Record);
360 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
363 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
364 Writer.AddTypeRef(T->getPattern(), Record);
365 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
366 Record.push_back(*NumExpansions + 1);
369 Code = TYPE_PACK_EXPANSION;
372 void ASTTypeWriter::VisitParenType(const ParenType *T) {
373 Writer.AddTypeRef(T->getInnerType(), Record);
377 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
378 Record.push_back(T->getKeyword());
379 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
380 Writer.AddTypeRef(T->getNamedType(), Record);
381 Code = TYPE_ELABORATED;
384 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
385 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
386 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
387 Code = TYPE_INJECTED_CLASS_NAME;
390 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
391 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
392 Code = TYPE_OBJC_INTERFACE;
395 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
396 Writer.AddTypeRef(T->getBaseType(), Record);
397 Record.push_back(T->getNumProtocols());
398 for (ObjCObjectType::qual_iterator I = T->qual_begin(),
399 E = T->qual_end(); I != E; ++I)
400 Writer.AddDeclRef(*I, Record);
401 Code = TYPE_OBJC_OBJECT;
405 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
406 Writer.AddTypeRef(T->getPointeeType(), Record);
407 Code = TYPE_OBJC_OBJECT_POINTER;
411 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
412 Writer.AddTypeRef(T->getValueType(), Record);
418 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
420 ASTWriter::RecordDataImpl &Record;
423 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
424 : Writer(Writer), Record(Record) { }
426 #define ABSTRACT_TYPELOC(CLASS, PARENT)
427 #define TYPELOC(CLASS, PARENT) \
428 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
429 #include "clang/AST/TypeLocNodes.def"
431 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
432 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
437 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
440 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
441 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
442 if (TL.needsExtraLocalData()) {
443 Record.push_back(TL.getWrittenTypeSpec());
444 Record.push_back(TL.getWrittenSignSpec());
445 Record.push_back(TL.getWrittenWidthSpec());
446 Record.push_back(TL.hasModeAttr());
449 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
450 Writer.AddSourceLocation(TL.getNameLoc(), Record);
452 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
453 Writer.AddSourceLocation(TL.getStarLoc(), Record);
455 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
458 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
459 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
461 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
462 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
464 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
465 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
467 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
468 Writer.AddSourceLocation(TL.getStarLoc(), Record);
469 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
471 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
472 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
473 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
474 Record.push_back(TL.getSizeExpr() ? 1 : 0);
475 if (TL.getSizeExpr())
476 Writer.AddStmt(TL.getSizeExpr());
478 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
479 VisitArrayTypeLoc(TL);
481 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
482 VisitArrayTypeLoc(TL);
484 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
485 VisitArrayTypeLoc(TL);
487 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
488 DependentSizedArrayTypeLoc TL) {
489 VisitArrayTypeLoc(TL);
491 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
492 DependentSizedExtVectorTypeLoc TL) {
493 Writer.AddSourceLocation(TL.getNameLoc(), Record);
495 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
496 Writer.AddSourceLocation(TL.getNameLoc(), Record);
498 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
499 Writer.AddSourceLocation(TL.getNameLoc(), Record);
501 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
502 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
503 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
504 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
505 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
506 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
507 Writer.AddDeclRef(TL.getArg(i), Record);
509 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
510 VisitFunctionTypeLoc(TL);
512 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
513 VisitFunctionTypeLoc(TL);
515 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
516 Writer.AddSourceLocation(TL.getNameLoc(), Record);
518 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
519 Writer.AddSourceLocation(TL.getNameLoc(), Record);
521 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
522 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
523 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
524 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
526 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
527 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
528 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
529 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
530 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
532 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
533 Writer.AddSourceLocation(TL.getNameLoc(), Record);
535 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
536 Writer.AddSourceLocation(TL.getKWLoc(), Record);
537 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
538 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
539 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
541 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
542 Writer.AddSourceLocation(TL.getNameLoc(), Record);
544 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
545 Writer.AddSourceLocation(TL.getNameLoc(), Record);
547 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
548 Writer.AddSourceLocation(TL.getNameLoc(), Record);
550 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
551 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
552 if (TL.hasAttrOperand()) {
553 SourceRange range = TL.getAttrOperandParensRange();
554 Writer.AddSourceLocation(range.getBegin(), Record);
555 Writer.AddSourceLocation(range.getEnd(), Record);
557 if (TL.hasAttrExprOperand()) {
558 Expr *operand = TL.getAttrExprOperand();
559 Record.push_back(operand ? 1 : 0);
560 if (operand) Writer.AddStmt(operand);
561 } else if (TL.hasAttrEnumOperand()) {
562 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
565 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
566 Writer.AddSourceLocation(TL.getNameLoc(), Record);
568 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
569 SubstTemplateTypeParmTypeLoc TL) {
570 Writer.AddSourceLocation(TL.getNameLoc(), Record);
572 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
573 SubstTemplateTypeParmPackTypeLoc TL) {
574 Writer.AddSourceLocation(TL.getNameLoc(), Record);
576 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
577 TemplateSpecializationTypeLoc TL) {
578 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
579 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
580 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
581 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
582 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
583 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
584 TL.getArgLoc(i).getLocInfo(), Record);
586 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
587 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
588 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
590 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
591 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
592 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
594 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
595 Writer.AddSourceLocation(TL.getNameLoc(), Record);
597 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
598 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
599 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
600 Writer.AddSourceLocation(TL.getNameLoc(), Record);
602 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
603 DependentTemplateSpecializationTypeLoc TL) {
604 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
605 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
606 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
607 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
608 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
609 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
610 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
611 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
612 TL.getArgLoc(I).getLocInfo(), Record);
614 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
615 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
617 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
618 Writer.AddSourceLocation(TL.getNameLoc(), Record);
620 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
621 Record.push_back(TL.hasBaseTypeAsWritten());
622 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
623 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
624 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
625 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
627 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
628 Writer.AddSourceLocation(TL.getStarLoc(), Record);
630 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
631 Writer.AddSourceLocation(TL.getKWLoc(), Record);
632 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
633 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
636 //===----------------------------------------------------------------------===//
637 // ASTWriter Implementation
638 //===----------------------------------------------------------------------===//
640 static void EmitBlockID(unsigned ID, const char *Name,
641 llvm::BitstreamWriter &Stream,
642 ASTWriter::RecordDataImpl &Record) {
644 Record.push_back(ID);
645 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
647 // Emit the block name if present.
648 if (Name == 0 || Name[0] == 0) return;
651 Record.push_back(*Name++);
652 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
655 static void EmitRecordID(unsigned ID, const char *Name,
656 llvm::BitstreamWriter &Stream,
657 ASTWriter::RecordDataImpl &Record) {
659 Record.push_back(ID);
661 Record.push_back(*Name++);
662 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
665 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
666 ASTWriter::RecordDataImpl &Record) {
667 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
669 RECORD(STMT_NULL_PTR);
671 RECORD(STMT_COMPOUND);
673 RECORD(STMT_DEFAULT);
675 RECORD(STMT_ATTRIBUTED);
682 RECORD(STMT_INDIRECT_GOTO);
683 RECORD(STMT_CONTINUE);
689 RECORD(EXPR_PREDEFINED);
690 RECORD(EXPR_DECL_REF);
691 RECORD(EXPR_INTEGER_LITERAL);
692 RECORD(EXPR_FLOATING_LITERAL);
693 RECORD(EXPR_IMAGINARY_LITERAL);
694 RECORD(EXPR_STRING_LITERAL);
695 RECORD(EXPR_CHARACTER_LITERAL);
697 RECORD(EXPR_UNARY_OPERATOR);
698 RECORD(EXPR_SIZEOF_ALIGN_OF);
699 RECORD(EXPR_ARRAY_SUBSCRIPT);
702 RECORD(EXPR_BINARY_OPERATOR);
703 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
704 RECORD(EXPR_CONDITIONAL_OPERATOR);
705 RECORD(EXPR_IMPLICIT_CAST);
706 RECORD(EXPR_CSTYLE_CAST);
707 RECORD(EXPR_COMPOUND_LITERAL);
708 RECORD(EXPR_EXT_VECTOR_ELEMENT);
709 RECORD(EXPR_INIT_LIST);
710 RECORD(EXPR_DESIGNATED_INIT);
711 RECORD(EXPR_IMPLICIT_VALUE_INIT);
713 RECORD(EXPR_ADDR_LABEL);
716 RECORD(EXPR_GNU_NULL);
717 RECORD(EXPR_SHUFFLE_VECTOR);
719 RECORD(EXPR_GENERIC_SELECTION);
720 RECORD(EXPR_OBJC_STRING_LITERAL);
721 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
722 RECORD(EXPR_OBJC_ARRAY_LITERAL);
723 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
724 RECORD(EXPR_OBJC_ENCODE);
725 RECORD(EXPR_OBJC_SELECTOR_EXPR);
726 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
727 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
728 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
729 RECORD(EXPR_OBJC_KVC_REF_EXPR);
730 RECORD(EXPR_OBJC_MESSAGE_EXPR);
731 RECORD(STMT_OBJC_FOR_COLLECTION);
732 RECORD(STMT_OBJC_CATCH);
733 RECORD(STMT_OBJC_FINALLY);
734 RECORD(STMT_OBJC_AT_TRY);
735 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
736 RECORD(STMT_OBJC_AT_THROW);
737 RECORD(EXPR_OBJC_BOOL_LITERAL);
738 RECORD(EXPR_CXX_OPERATOR_CALL);
739 RECORD(EXPR_CXX_CONSTRUCT);
740 RECORD(EXPR_CXX_STATIC_CAST);
741 RECORD(EXPR_CXX_DYNAMIC_CAST);
742 RECORD(EXPR_CXX_REINTERPRET_CAST);
743 RECORD(EXPR_CXX_CONST_CAST);
744 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
745 RECORD(EXPR_USER_DEFINED_LITERAL);
746 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
747 RECORD(EXPR_CXX_BOOL_LITERAL);
748 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
749 RECORD(EXPR_CXX_TYPEID_EXPR);
750 RECORD(EXPR_CXX_TYPEID_TYPE);
751 RECORD(EXPR_CXX_UUIDOF_EXPR);
752 RECORD(EXPR_CXX_UUIDOF_TYPE);
753 RECORD(EXPR_CXX_THIS);
754 RECORD(EXPR_CXX_THROW);
755 RECORD(EXPR_CXX_DEFAULT_ARG);
756 RECORD(EXPR_CXX_BIND_TEMPORARY);
757 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
758 RECORD(EXPR_CXX_NEW);
759 RECORD(EXPR_CXX_DELETE);
760 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
761 RECORD(EXPR_EXPR_WITH_CLEANUPS);
762 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
763 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
764 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
765 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
766 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
767 RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
768 RECORD(EXPR_CXX_NOEXCEPT);
769 RECORD(EXPR_OPAQUE_VALUE);
770 RECORD(EXPR_BINARY_TYPE_TRAIT);
771 RECORD(EXPR_PACK_EXPANSION);
772 RECORD(EXPR_SIZEOF_PACK);
773 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
774 RECORD(EXPR_CUDA_KERNEL_CALL);
778 void ASTWriter::WriteBlockInfoBlock() {
780 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
782 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
783 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
786 BLOCK(CONTROL_BLOCK);
789 RECORD(LANGUAGE_OPTIONS);
790 RECORD(TARGET_OPTIONS);
791 RECORD(ORIGINAL_FILE);
792 RECORD(ORIGINAL_PCH_DIR);
793 RECORD(ORIGINAL_FILE_ID);
794 RECORD(INPUT_FILE_OFFSETS);
795 RECORD(DIAGNOSTIC_OPTIONS);
796 RECORD(FILE_SYSTEM_OPTIONS);
797 RECORD(HEADER_SEARCH_OPTIONS);
798 RECORD(PREPROCESSOR_OPTIONS);
800 BLOCK(INPUT_FILES_BLOCK);
803 // AST Top-Level Block.
807 RECORD(IDENTIFIER_OFFSET);
808 RECORD(IDENTIFIER_TABLE);
809 RECORD(EXTERNAL_DEFINITIONS);
810 RECORD(SPECIAL_TYPES);
812 RECORD(TENTATIVE_DEFINITIONS);
813 RECORD(UNUSED_FILESCOPED_DECLS);
814 RECORD(LOCALLY_SCOPED_EXTERN_C_DECLS);
815 RECORD(SELECTOR_OFFSETS);
817 RECORD(PP_COUNTER_VALUE);
818 RECORD(SOURCE_LOCATION_OFFSETS);
819 RECORD(SOURCE_LOCATION_PRELOADS);
820 RECORD(EXT_VECTOR_DECLS);
821 RECORD(PPD_ENTITIES_OFFSETS);
822 RECORD(REFERENCED_SELECTOR_POOL);
823 RECORD(TU_UPDATE_LEXICAL);
824 RECORD(LOCAL_REDECLARATIONS_MAP);
825 RECORD(SEMA_DECL_REFS);
826 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
827 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
828 RECORD(DECL_REPLACEMENTS);
829 RECORD(UPDATE_VISIBLE);
830 RECORD(DECL_UPDATE_OFFSETS);
831 RECORD(DECL_UPDATES);
832 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
833 RECORD(DIAG_PRAGMA_MAPPINGS);
834 RECORD(CUDA_SPECIAL_DECL_REFS);
835 RECORD(HEADER_SEARCH_TABLE);
836 RECORD(FP_PRAGMA_OPTIONS);
837 RECORD(OPENCL_EXTENSIONS);
838 RECORD(DELEGATING_CTORS);
839 RECORD(KNOWN_NAMESPACES);
840 RECORD(UNDEFINED_BUT_USED);
841 RECORD(MODULE_OFFSET_MAP);
842 RECORD(SOURCE_MANAGER_LINE_TABLE);
843 RECORD(OBJC_CATEGORIES_MAP);
844 RECORD(FILE_SORTED_DECLS);
845 RECORD(IMPORTED_MODULES);
846 RECORD(MERGED_DECLARATIONS);
847 RECORD(LOCAL_REDECLARATIONS);
848 RECORD(OBJC_CATEGORIES);
849 RECORD(MACRO_OFFSET);
851 RECORD(LATE_PARSED_TEMPLATE);
853 // SourceManager Block.
854 BLOCK(SOURCE_MANAGER_BLOCK);
855 RECORD(SM_SLOC_FILE_ENTRY);
856 RECORD(SM_SLOC_BUFFER_ENTRY);
857 RECORD(SM_SLOC_BUFFER_BLOB);
858 RECORD(SM_SLOC_EXPANSION_ENTRY);
860 // Preprocessor Block.
861 BLOCK(PREPROCESSOR_BLOCK);
862 RECORD(PP_MACRO_OBJECT_LIKE);
863 RECORD(PP_MACRO_FUNCTION_LIKE);
866 // Decls and Types block.
867 BLOCK(DECLTYPES_BLOCK);
868 RECORD(TYPE_EXT_QUAL);
869 RECORD(TYPE_COMPLEX);
870 RECORD(TYPE_POINTER);
871 RECORD(TYPE_BLOCK_POINTER);
872 RECORD(TYPE_LVALUE_REFERENCE);
873 RECORD(TYPE_RVALUE_REFERENCE);
874 RECORD(TYPE_MEMBER_POINTER);
875 RECORD(TYPE_CONSTANT_ARRAY);
876 RECORD(TYPE_INCOMPLETE_ARRAY);
877 RECORD(TYPE_VARIABLE_ARRAY);
879 RECORD(TYPE_EXT_VECTOR);
880 RECORD(TYPE_FUNCTION_PROTO);
881 RECORD(TYPE_FUNCTION_NO_PROTO);
882 RECORD(TYPE_TYPEDEF);
883 RECORD(TYPE_TYPEOF_EXPR);
887 RECORD(TYPE_OBJC_INTERFACE);
888 RECORD(TYPE_OBJC_OBJECT);
889 RECORD(TYPE_OBJC_OBJECT_POINTER);
890 RECORD(TYPE_DECLTYPE);
891 RECORD(TYPE_ELABORATED);
892 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
893 RECORD(TYPE_UNRESOLVED_USING);
894 RECORD(TYPE_INJECTED_CLASS_NAME);
895 RECORD(TYPE_OBJC_OBJECT);
896 RECORD(TYPE_TEMPLATE_TYPE_PARM);
897 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
898 RECORD(TYPE_DEPENDENT_NAME);
899 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
900 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
902 RECORD(TYPE_PACK_EXPANSION);
903 RECORD(TYPE_ATTRIBUTED);
904 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
906 RECORD(DECL_TYPEDEF);
909 RECORD(DECL_ENUM_CONSTANT);
910 RECORD(DECL_FUNCTION);
911 RECORD(DECL_OBJC_METHOD);
912 RECORD(DECL_OBJC_INTERFACE);
913 RECORD(DECL_OBJC_PROTOCOL);
914 RECORD(DECL_OBJC_IVAR);
915 RECORD(DECL_OBJC_AT_DEFS_FIELD);
916 RECORD(DECL_OBJC_CATEGORY);
917 RECORD(DECL_OBJC_CATEGORY_IMPL);
918 RECORD(DECL_OBJC_IMPLEMENTATION);
919 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
920 RECORD(DECL_OBJC_PROPERTY);
921 RECORD(DECL_OBJC_PROPERTY_IMPL);
923 RECORD(DECL_MS_PROPERTY);
925 RECORD(DECL_IMPLICIT_PARAM);
926 RECORD(DECL_PARM_VAR);
927 RECORD(DECL_FILE_SCOPE_ASM);
929 RECORD(DECL_CONTEXT_LEXICAL);
930 RECORD(DECL_CONTEXT_VISIBLE);
931 RECORD(DECL_NAMESPACE);
932 RECORD(DECL_NAMESPACE_ALIAS);
934 RECORD(DECL_USING_SHADOW);
935 RECORD(DECL_USING_DIRECTIVE);
936 RECORD(DECL_UNRESOLVED_USING_VALUE);
937 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
938 RECORD(DECL_LINKAGE_SPEC);
939 RECORD(DECL_CXX_RECORD);
940 RECORD(DECL_CXX_METHOD);
941 RECORD(DECL_CXX_CONSTRUCTOR);
942 RECORD(DECL_CXX_DESTRUCTOR);
943 RECORD(DECL_CXX_CONVERSION);
944 RECORD(DECL_ACCESS_SPEC);
946 RECORD(DECL_FRIEND_TEMPLATE);
947 RECORD(DECL_CLASS_TEMPLATE);
948 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
949 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
950 RECORD(DECL_VAR_TEMPLATE);
951 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
952 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
953 RECORD(DECL_FUNCTION_TEMPLATE);
954 RECORD(DECL_TEMPLATE_TYPE_PARM);
955 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
956 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
957 RECORD(DECL_STATIC_ASSERT);
958 RECORD(DECL_CXX_BASE_SPECIFIERS);
959 RECORD(DECL_INDIRECTFIELD);
960 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
962 // Statements and Exprs can occur in the Decls and Types block.
963 AddStmtsExprs(Stream, Record);
965 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
966 RECORD(PPD_MACRO_EXPANSION);
967 RECORD(PPD_MACRO_DEFINITION);
968 RECORD(PPD_INCLUSION_DIRECTIVE);
975 /// \brief Adjusts the given filename to only write out the portion of the
976 /// filename that is not part of the system root directory.
978 /// \param Filename the file name to adjust.
980 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
981 /// the returned filename will be adjusted by this system root.
983 /// \returns either the original filename (if it needs no adjustment) or the
984 /// adjusted filename (which points into the @p Filename parameter).
986 adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) {
987 assert(Filename && "No file name to adjust?");
989 if (isysroot.empty())
992 // Verify that the filename and the system root have the same prefix.
994 for (; Filename[Pos] && Pos < isysroot.size(); ++Pos)
995 if (Filename[Pos] != isysroot[Pos])
996 return Filename; // Prefixes don't match.
998 // We hit the end of the filename before we hit the end of the system root.
1002 // If the file name has a '/' at the current position, skip over the '/'.
1003 // We distinguish sysroot-based includes from absolute includes by the
1004 // absence of '/' at the beginning of sysroot-based includes.
1005 if (Filename[Pos] == '/')
1008 return Filename + Pos;
1011 /// \brief Write the control block.
1012 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1014 const std::string &OutputFile) {
1015 using namespace llvm;
1016 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1020 BitCodeAbbrev *MetadataAbbrev = new BitCodeAbbrev();
1021 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1022 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1023 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1024 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1025 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1026 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1027 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1028 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1029 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
1030 Record.push_back(METADATA);
1031 Record.push_back(VERSION_MAJOR);
1032 Record.push_back(VERSION_MINOR);
1033 Record.push_back(CLANG_VERSION_MAJOR);
1034 Record.push_back(CLANG_VERSION_MINOR);
1035 Record.push_back(!isysroot.empty());
1036 Record.push_back(ASTHasCompilerErrors);
1037 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1038 getClangFullRepositoryVersion());
1042 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1043 SmallVector<char, 128> ModulePaths;
1046 for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end();
1048 // Skip modules that weren't directly imported.
1049 if (!(*M)->isDirectlyImported())
1052 Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding
1053 AddSourceLocation((*M)->ImportLoc, Record);
1054 Record.push_back((*M)->File->getSize());
1055 Record.push_back((*M)->File->getModificationTime());
1056 // FIXME: This writes the absolute path for AST files we depend on.
1057 const std::string &FileName = (*M)->FileName;
1058 Record.push_back(FileName.size());
1059 Record.append(FileName.begin(), FileName.end());
1061 Stream.EmitRecord(IMPORTS, Record);
1064 // Language options.
1066 const LangOptions &LangOpts = Context.getLangOpts();
1067 #define LANGOPT(Name, Bits, Default, Description) \
1068 Record.push_back(LangOpts.Name);
1069 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1070 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1071 #include "clang/Basic/LangOptions.def"
1072 #define SANITIZER(NAME, ID) Record.push_back(LangOpts.Sanitize.ID);
1073 #include "clang/Basic/Sanitizers.def"
1075 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1076 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1078 Record.push_back(LangOpts.CurrentModule.size());
1079 Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end());
1082 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1083 for (CommentOptions::BlockCommandNamesTy::const_iterator
1084 I = LangOpts.CommentOpts.BlockCommandNames.begin(),
1085 IEnd = LangOpts.CommentOpts.BlockCommandNames.end();
1087 AddString(*I, Record);
1089 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1091 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1095 const TargetInfo &Target = Context.getTargetInfo();
1096 const TargetOptions &TargetOpts = Target.getTargetOpts();
1097 AddString(TargetOpts.Triple, Record);
1098 AddString(TargetOpts.CPU, Record);
1099 AddString(TargetOpts.ABI, Record);
1100 AddString(TargetOpts.CXXABI, Record);
1101 AddString(TargetOpts.LinkerVersion, Record);
1102 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1103 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1104 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1106 Record.push_back(TargetOpts.Features.size());
1107 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1108 AddString(TargetOpts.Features[I], Record);
1110 Stream.EmitRecord(TARGET_OPTIONS, Record);
1112 // Diagnostic options.
1114 const DiagnosticOptions &DiagOpts
1115 = Context.getDiagnostics().getDiagnosticOptions();
1116 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1117 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1118 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1119 #include "clang/Basic/DiagnosticOptions.def"
1120 Record.push_back(DiagOpts.Warnings.size());
1121 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1122 AddString(DiagOpts.Warnings[I], Record);
1123 // Note: we don't serialize the log or serialization file names, because they
1124 // are generally transient files and will almost always be overridden.
1125 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1127 // File system options.
1129 const FileSystemOptions &FSOpts
1130 = Context.getSourceManager().getFileManager().getFileSystemOptions();
1131 AddString(FSOpts.WorkingDir, Record);
1132 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1134 // Header search options.
1136 const HeaderSearchOptions &HSOpts
1137 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1138 AddString(HSOpts.Sysroot, Record);
1141 Record.push_back(HSOpts.UserEntries.size());
1142 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1143 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1144 AddString(Entry.Path, Record);
1145 Record.push_back(static_cast<unsigned>(Entry.Group));
1146 Record.push_back(Entry.IsFramework);
1147 Record.push_back(Entry.IgnoreSysRoot);
1150 // System header prefixes.
1151 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1152 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1153 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1154 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1157 AddString(HSOpts.ResourceDir, Record);
1158 AddString(HSOpts.ModuleCachePath, Record);
1159 Record.push_back(HSOpts.DisableModuleHash);
1160 Record.push_back(HSOpts.UseBuiltinIncludes);
1161 Record.push_back(HSOpts.UseStandardSystemIncludes);
1162 Record.push_back(HSOpts.UseStandardCXXIncludes);
1163 Record.push_back(HSOpts.UseLibcxx);
1164 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1166 // Preprocessor options.
1168 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1170 // Macro definitions.
1171 Record.push_back(PPOpts.Macros.size());
1172 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1173 AddString(PPOpts.Macros[I].first, Record);
1174 Record.push_back(PPOpts.Macros[I].second);
1178 Record.push_back(PPOpts.Includes.size());
1179 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1180 AddString(PPOpts.Includes[I], Record);
1183 Record.push_back(PPOpts.MacroIncludes.size());
1184 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1185 AddString(PPOpts.MacroIncludes[I], Record);
1187 Record.push_back(PPOpts.UsePredefines);
1188 // Detailed record is important since it is used for the module cache hash.
1189 Record.push_back(PPOpts.DetailedRecord);
1190 AddString(PPOpts.ImplicitPCHInclude, Record);
1191 AddString(PPOpts.ImplicitPTHInclude, Record);
1192 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1193 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1195 // Original file name and file ID
1196 SourceManager &SM = Context.getSourceManager();
1197 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1198 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
1199 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1200 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1201 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1202 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1204 SmallString<128> MainFilePath(MainFile->getName());
1206 llvm::sys::fs::make_absolute(MainFilePath);
1208 const char *MainFileNameStr = MainFilePath.c_str();
1209 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
1212 Record.push_back(ORIGINAL_FILE);
1213 Record.push_back(SM.getMainFileID().getOpaqueValue());
1214 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
1218 Record.push_back(SM.getMainFileID().getOpaqueValue());
1219 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1221 // Original PCH directory
1222 if (!OutputFile.empty() && OutputFile != "-") {
1223 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1224 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1225 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1226 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1228 SmallString<128> OutputPath(OutputFile);
1230 llvm::sys::fs::make_absolute(OutputPath);
1231 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1234 Record.push_back(ORIGINAL_PCH_DIR);
1235 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1238 WriteInputFiles(Context.SourceMgr,
1239 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1241 PP.getLangOpts().Modules);
1246 /// \brief An input file.
1247 struct InputFileEntry {
1248 const FileEntry *File;
1250 bool BufferOverridden;
1254 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1255 HeaderSearchOptions &HSOpts,
1258 using namespace llvm;
1259 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1262 // Create input-file abbreviation.
1263 BitCodeAbbrev *IFAbbrev = new BitCodeAbbrev();
1264 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1265 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1266 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1267 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1268 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1269 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1270 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1272 // Get all ContentCache objects for files, sorted by whether the file is a
1273 // system one or not. System files go at the back, users files at the front.
1274 std::deque<InputFileEntry> SortedFiles;
1275 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1276 // Get this source location entry.
1277 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1278 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1280 // We only care about file entries that were not overridden.
1281 if (!SLoc->isFile())
1283 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1284 if (!Cache->OrigEntry)
1287 InputFileEntry Entry;
1288 Entry.File = Cache->OrigEntry;
1289 Entry.IsSystemFile = Cache->IsSystemFile;
1290 Entry.BufferOverridden = Cache->BufferOverridden;
1291 if (Cache->IsSystemFile)
1292 SortedFiles.push_back(Entry);
1294 SortedFiles.push_front(Entry);
1297 // If we have an isysroot for a Darwin SDK, include its SDKSettings.plist in
1298 // the set of (non-system) input files. This is simple heuristic for
1299 // detecting whether the system headers may have changed, because it is too
1300 // expensive to stat() all of the system headers.
1301 FileManager &FileMgr = SourceMgr.getFileManager();
1302 if (!HSOpts.Sysroot.empty() && !Chain) {
1303 llvm::SmallString<128> SDKSettingsFileName(HSOpts.Sysroot);
1304 llvm::sys::path::append(SDKSettingsFileName, "SDKSettings.plist");
1305 if (const FileEntry *SDKSettingsFile = FileMgr.getFile(SDKSettingsFileName)) {
1306 InputFileEntry Entry = { SDKSettingsFile, false, false };
1307 SortedFiles.push_front(Entry);
1311 // Add the compiler's own module.map in the set of (non-system) input files.
1312 // This is a simple heuristic for detecting whether the compiler's headers
1313 // have changed, because we don't want to stat() all of them.
1314 if (Modules && !Chain) {
1315 SmallString<128> P = StringRef(HSOpts.ResourceDir);
1316 llvm::sys::path::append(P, "include");
1317 llvm::sys::path::append(P, "module.map");
1318 if (const FileEntry *ModuleMapFile = FileMgr.getFile(P)) {
1319 InputFileEntry Entry = { ModuleMapFile, false, false };
1320 SortedFiles.push_front(Entry);
1324 unsigned UserFilesNum = 0;
1325 // Write out all of the input files.
1326 std::vector<uint32_t> InputFileOffsets;
1327 for (std::deque<InputFileEntry>::iterator
1328 I = SortedFiles.begin(), E = SortedFiles.end(); I != E; ++I) {
1329 const InputFileEntry &Entry = *I;
1331 uint32_t &InputFileID = InputFileIDs[Entry.File];
1332 if (InputFileID != 0)
1333 continue; // already recorded this file.
1335 // Record this entry's offset.
1336 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1338 InputFileID = InputFileOffsets.size();
1340 if (!Entry.IsSystemFile)
1344 Record.push_back(INPUT_FILE);
1345 Record.push_back(InputFileOffsets.size());
1347 // Emit size/modification time for this file.
1348 Record.push_back(Entry.File->getSize());
1349 Record.push_back(Entry.File->getModificationTime());
1351 // Whether this file was overridden.
1352 Record.push_back(Entry.BufferOverridden);
1354 // Turn the file name into an absolute path, if it isn't already.
1355 const char *Filename = Entry.File->getName();
1356 SmallString<128> FilePath(Filename);
1358 // Ask the file manager to fixup the relative path for us. This will
1359 // honor the working directory.
1360 FileMgr.FixupRelativePath(FilePath);
1362 // FIXME: This call to make_absolute shouldn't be necessary, the
1363 // call to FixupRelativePath should always return an absolute path.
1364 llvm::sys::fs::make_absolute(FilePath);
1365 Filename = FilePath.c_str();
1367 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1369 Stream.EmitRecordWithBlob(IFAbbrevCode, Record, Filename);
1374 // Create input file offsets abbreviation.
1375 BitCodeAbbrev *OffsetsAbbrev = new BitCodeAbbrev();
1376 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1377 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1378 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1380 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1381 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1383 // Write input file offsets.
1385 Record.push_back(INPUT_FILE_OFFSETS);
1386 Record.push_back(InputFileOffsets.size());
1387 Record.push_back(UserFilesNum);
1388 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, data(InputFileOffsets));
1391 //===----------------------------------------------------------------------===//
1392 // Source Manager Serialization
1393 //===----------------------------------------------------------------------===//
1395 /// \brief Create an abbreviation for the SLocEntry that refers to a
1397 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1398 using namespace llvm;
1399 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1400 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1401 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1402 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1403 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1404 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1405 // FileEntry fields.
1406 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1407 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1408 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1409 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1410 return Stream.EmitAbbrev(Abbrev);
1413 /// \brief Create an abbreviation for the SLocEntry that refers to a
1415 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1416 using namespace llvm;
1417 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1418 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1419 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1420 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1421 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1422 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1423 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1424 return Stream.EmitAbbrev(Abbrev);
1427 /// \brief Create an abbreviation for the SLocEntry that refers to a
1429 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1430 using namespace llvm;
1431 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1432 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1433 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1434 return Stream.EmitAbbrev(Abbrev);
1437 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1439 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1440 using namespace llvm;
1441 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1442 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1443 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1444 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1445 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1446 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1447 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1448 return Stream.EmitAbbrev(Abbrev);
1452 // Trait used for the on-disk hash table of header search information.
1453 class HeaderFileInfoTrait {
1455 const HeaderSearch &HS;
1457 // Keep track of the framework names we've used during serialization.
1458 SmallVector<char, 128> FrameworkStringData;
1459 llvm::StringMap<unsigned> FrameworkNameOffset;
1462 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1463 : Writer(Writer), HS(HS) { }
1466 const FileEntry *FE;
1467 const char *Filename;
1469 typedef const key_type &key_type_ref;
1471 typedef HeaderFileInfo data_type;
1472 typedef const data_type &data_type_ref;
1474 static unsigned ComputeHash(key_type_ref key) {
1475 // The hash is based only on size/time of the file, so that the reader can
1476 // match even when symlinking or excess path elements ("foo/../", "../")
1477 // change the form of the name. However, complete path is still the key.
1478 return llvm::hash_combine(key.FE->getSize(),
1479 key.FE->getModificationTime());
1482 std::pair<unsigned,unsigned>
1483 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1484 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
1485 clang::io::Emit16(Out, KeyLen);
1486 unsigned DataLen = 1 + 2 + 4 + 4;
1487 if (Data.isModuleHeader)
1489 clang::io::Emit8(Out, DataLen);
1490 return std::make_pair(KeyLen, DataLen);
1493 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1494 clang::io::Emit64(Out, key.FE->getSize());
1496 clang::io::Emit64(Out, key.FE->getModificationTime());
1498 Out.write(key.Filename, KeyLen);
1501 void EmitData(raw_ostream &Out, key_type_ref key,
1502 data_type_ref Data, unsigned DataLen) {
1503 using namespace clang::io;
1504 uint64_t Start = Out.tell(); (void)Start;
1506 unsigned char Flags = (Data.HeaderRole << 6)
1507 | (Data.isImport << 5)
1508 | (Data.isPragmaOnce << 4)
1509 | (Data.DirInfo << 2)
1510 | (Data.Resolved << 1)
1511 | Data.IndexHeaderMapHeader;
1512 Emit8(Out, (uint8_t)Flags);
1513 Emit16(Out, (uint16_t) Data.NumIncludes);
1515 if (!Data.ControllingMacro)
1516 Emit32(Out, (uint32_t)Data.ControllingMacroID);
1518 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
1520 unsigned Offset = 0;
1521 if (!Data.Framework.empty()) {
1522 // If this header refers into a framework, save the framework name.
1523 llvm::StringMap<unsigned>::iterator Pos
1524 = FrameworkNameOffset.find(Data.Framework);
1525 if (Pos == FrameworkNameOffset.end()) {
1526 Offset = FrameworkStringData.size() + 1;
1527 FrameworkStringData.append(Data.Framework.begin(),
1528 Data.Framework.end());
1529 FrameworkStringData.push_back(0);
1531 FrameworkNameOffset[Data.Framework] = Offset;
1533 Offset = Pos->second;
1535 Emit32(Out, Offset);
1537 if (Data.isModuleHeader) {
1538 Module *Mod = HS.findModuleForHeader(key.FE).getModule();
1539 Emit32(Out, Writer.getExistingSubmoduleID(Mod));
1542 assert(Out.tell() - Start == DataLen && "Wrong data length");
1545 const char *strings_begin() const { return FrameworkStringData.begin(); }
1546 const char *strings_end() const { return FrameworkStringData.end(); }
1548 } // end anonymous namespace
1550 /// \brief Write the header search block for the list of files that
1552 /// \param HS The header search structure to save.
1553 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) {
1554 SmallVector<const FileEntry *, 16> FilesByUID;
1555 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1557 if (FilesByUID.size() > HS.header_file_size())
1558 FilesByUID.resize(HS.header_file_size());
1560 HeaderFileInfoTrait GeneratorTrait(*this, HS);
1561 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1562 SmallVector<const char *, 4> SavedStrings;
1563 unsigned NumHeaderSearchEntries = 0;
1564 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1565 const FileEntry *File = FilesByUID[UID];
1569 // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
1570 // from the external source if it was not provided already.
1571 const HeaderFileInfo &HFI = HS.getFileInfo(File);
1572 if (HFI.External && Chain)
1574 if (HFI.isModuleHeader && !HFI.isCompilingModuleHeader)
1577 // Turn the file name into an absolute path, if it isn't already.
1578 const char *Filename = File->getName();
1579 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1581 // If we performed any translation on the file name at all, we need to
1582 // save this string, since the generator will refer to it later.
1583 if (Filename != File->getName()) {
1584 Filename = strdup(Filename);
1585 SavedStrings.push_back(Filename);
1588 HeaderFileInfoTrait::key_type key = { File, Filename };
1589 Generator.insert(key, HFI, GeneratorTrait);
1590 ++NumHeaderSearchEntries;
1593 // Create the on-disk hash table in a buffer.
1594 SmallString<4096> TableData;
1595 uint32_t BucketOffset;
1597 llvm::raw_svector_ostream Out(TableData);
1598 // Make sure that no bucket is at offset 0
1599 clang::io::Emit32(Out, 0);
1600 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1603 // Create a blob abbreviation
1604 using namespace llvm;
1605 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1606 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1607 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1608 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1609 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1610 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1611 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1613 // Write the header search table
1615 Record.push_back(HEADER_SEARCH_TABLE);
1616 Record.push_back(BucketOffset);
1617 Record.push_back(NumHeaderSearchEntries);
1618 Record.push_back(TableData.size());
1619 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1620 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1622 // Free all of the strings we had to duplicate.
1623 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1624 free(const_cast<char *>(SavedStrings[I]));
1627 /// \brief Writes the block containing the serialized form of the
1630 /// TODO: We should probably use an on-disk hash table (stored in a
1631 /// blob), indexed based on the file name, so that we only create
1632 /// entries for files that we actually need. In the common case (no
1633 /// errors), we probably won't have to create file entries for any of
1634 /// the files in the AST.
1635 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1636 const Preprocessor &PP,
1637 StringRef isysroot) {
1640 // Enter the source manager block.
1641 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1643 // Abbreviations for the various kinds of source-location entries.
1644 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1645 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1646 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1647 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1649 // Write out the source location entry table. We skip the first
1650 // entry, which is always the same dummy entry.
1651 std::vector<uint32_t> SLocEntryOffsets;
1652 RecordData PreloadSLocs;
1653 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1654 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
1656 // Get this source location entry.
1657 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1658 FileID FID = FileID::get(I);
1659 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
1661 // Record the offset of this source-location entry.
1662 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1664 // Figure out which record code to use.
1666 if (SLoc->isFile()) {
1667 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1668 if (Cache->OrigEntry) {
1669 Code = SM_SLOC_FILE_ENTRY;
1671 Code = SM_SLOC_BUFFER_ENTRY;
1673 Code = SM_SLOC_EXPANSION_ENTRY;
1675 Record.push_back(Code);
1677 // Starting offset of this entry within this module, so skip the dummy.
1678 Record.push_back(SLoc->getOffset() - 2);
1679 if (SLoc->isFile()) {
1680 const SrcMgr::FileInfo &File = SLoc->getFile();
1681 Record.push_back(File.getIncludeLoc().getRawEncoding());
1682 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1683 Record.push_back(File.hasLineDirectives());
1685 const SrcMgr::ContentCache *Content = File.getContentCache();
1686 if (Content->OrigEntry) {
1687 assert(Content->OrigEntry == Content->ContentsEntry &&
1688 "Writing to AST an overridden file is not supported");
1690 // The source location entry is a file. Emit input file ID.
1691 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1692 Record.push_back(InputFileIDs[Content->OrigEntry]);
1694 Record.push_back(File.NumCreatedFIDs);
1696 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
1697 if (FDI != FileDeclIDs.end()) {
1698 Record.push_back(FDI->second->FirstDeclIndex);
1699 Record.push_back(FDI->second->DeclIDs.size());
1701 Record.push_back(0);
1702 Record.push_back(0);
1705 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1707 if (Content->BufferOverridden) {
1709 Record.push_back(SM_SLOC_BUFFER_BLOB);
1710 const llvm::MemoryBuffer *Buffer
1711 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1712 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1713 StringRef(Buffer->getBufferStart(),
1714 Buffer->getBufferSize() + 1));
1717 // The source location entry is a buffer. The blob associated
1718 // with this entry contains the contents of the buffer.
1720 // We add one to the size so that we capture the trailing NULL
1721 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1722 // the reader side).
1723 const llvm::MemoryBuffer *Buffer
1724 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1725 const char *Name = Buffer->getBufferIdentifier();
1726 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1727 StringRef(Name, strlen(Name) + 1));
1729 Record.push_back(SM_SLOC_BUFFER_BLOB);
1730 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1731 StringRef(Buffer->getBufferStart(),
1732 Buffer->getBufferSize() + 1));
1734 if (strcmp(Name, "<built-in>") == 0) {
1735 PreloadSLocs.push_back(SLocEntryOffsets.size());
1739 // The source location entry is a macro expansion.
1740 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
1741 Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
1742 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
1743 Record.push_back(Expansion.isMacroArgExpansion() ? 0
1744 : Expansion.getExpansionLocEnd().getRawEncoding());
1746 // Compute the token length for this macro expansion.
1747 unsigned NextOffset = SourceMgr.getNextLocalOffset();
1749 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
1750 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1751 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
1757 if (SLocEntryOffsets.empty())
1760 // Write the source-location offsets table into the AST block. This
1761 // table is used for lazily loading source-location information.
1762 using namespace llvm;
1763 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1764 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1765 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1766 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
1767 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1768 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1771 Record.push_back(SOURCE_LOCATION_OFFSETS);
1772 Record.push_back(SLocEntryOffsets.size());
1773 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
1774 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
1776 // Write the source location entry preloads array, telling the AST
1777 // reader which source locations entries it should load eagerly.
1778 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1780 // Write the line table. It depends on remapping working, so it must come
1781 // after the source location offsets.
1782 if (SourceMgr.hasLineTable()) {
1783 LineTableInfo &LineTable = SourceMgr.getLineTable();
1786 // Emit the file names
1787 Record.push_back(LineTable.getNumFilenames());
1788 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1789 // Emit the file name
1790 const char *Filename = LineTable.getFilename(I);
1791 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1792 unsigned FilenameLen = Filename? strlen(Filename) : 0;
1793 Record.push_back(FilenameLen);
1795 Record.insert(Record.end(), Filename, Filename + FilenameLen);
1798 // Emit the line entries
1799 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1801 // Only emit entries for local files.
1802 if (L->first.ID < 0)
1806 Record.push_back(L->first.ID);
1808 // Emit the line entries
1809 Record.push_back(L->second.size());
1810 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1811 LEEnd = L->second.end();
1812 LE != LEEnd; ++LE) {
1813 Record.push_back(LE->FileOffset);
1814 Record.push_back(LE->LineNo);
1815 Record.push_back(LE->FilenameID);
1816 Record.push_back((unsigned)LE->FileKind);
1817 Record.push_back(LE->IncludeOffset);
1820 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
1824 //===----------------------------------------------------------------------===//
1825 // Preprocessor Serialization
1826 //===----------------------------------------------------------------------===//
1829 class ASTMacroTableTrait {
1831 typedef IdentID key_type;
1832 typedef key_type key_type_ref;
1835 uint32_t MacroDirectivesOffset;
1838 typedef Data data_type;
1839 typedef const data_type &data_type_ref;
1841 static unsigned ComputeHash(IdentID IdID) {
1842 return llvm::hash_value(IdID);
1845 std::pair<unsigned,unsigned>
1846 static EmitKeyDataLength(raw_ostream& Out,
1847 key_type_ref Key, data_type_ref Data) {
1848 unsigned KeyLen = 4; // IdentID.
1849 unsigned DataLen = 4; // MacroDirectivesOffset.
1850 return std::make_pair(KeyLen, DataLen);
1853 static void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
1854 clang::io::Emit32(Out, Key);
1857 static void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
1859 clang::io::Emit32(Out, Data.MacroDirectivesOffset);
1862 } // end anonymous namespace
1864 static int compareMacroDirectives(
1865 const std::pair<const IdentifierInfo *, MacroDirective *> *X,
1866 const std::pair<const IdentifierInfo *, MacroDirective *> *Y) {
1867 return X->first->getName().compare(Y->first->getName());
1870 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
1871 const Preprocessor &PP) {
1872 if (MacroInfo *MI = MD->getMacroInfo())
1873 if (MI->isBuiltinMacro())
1877 SourceLocation Loc = MD->getLocation();
1878 if (Loc.isInvalid())
1880 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
1887 /// \brief Writes the block containing the serialized form of the
1890 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
1891 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1893 WritePreprocessorDetail(*PPRec);
1897 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1898 if (PP.getCounterValue() != 0) {
1899 Record.push_back(PP.getCounterValue());
1900 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1904 // Enter the preprocessor block.
1905 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1907 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1908 // FIXME: use diagnostics subsystem for localization etc.
1909 if (PP.SawDateOrTime())
1910 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1913 // Loop over all the macro directives that are live at the end of the file,
1914 // emitting each to the PP section.
1916 // Construct the list of macro directives that need to be serialized.
1917 SmallVector<std::pair<const IdentifierInfo *, MacroDirective *>, 2>
1919 for (Preprocessor::macro_iterator
1920 I = PP.macro_begin(/*IncludeExternalMacros=*/false),
1921 E = PP.macro_end(/*IncludeExternalMacros=*/false);
1923 MacroDirectives.push_back(std::make_pair(I->first, I->second));
1926 // Sort the set of macro definitions that need to be serialized by the
1927 // name of the macro, to provide a stable ordering.
1928 llvm::array_pod_sort(MacroDirectives.begin(), MacroDirectives.end(),
1929 &compareMacroDirectives);
1931 OnDiskChainedHashTableGenerator<ASTMacroTableTrait> Generator;
1933 // Emit the macro directives as a list and associate the offset with the
1934 // identifier they belong to.
1935 for (unsigned I = 0, N = MacroDirectives.size(); I != N; ++I) {
1936 const IdentifierInfo *Name = MacroDirectives[I].first;
1937 uint64_t MacroDirectiveOffset = Stream.GetCurrentBitNo();
1938 MacroDirective *MD = MacroDirectives[I].second;
1940 // If the macro or identifier need no updates, don't write the macro history
1942 // FIXME: Chain the macro history instead of re-writing it.
1943 if (MD->isFromPCH() &&
1944 Name->isFromAST() && !Name->hasChangedSinceDeserialization())
1947 // Emit the macro directives in reverse source order.
1948 for (; MD; MD = MD->getPrevious()) {
1951 if (shouldIgnoreMacro(MD, IsModule, PP))
1954 AddSourceLocation(MD->getLocation(), Record);
1955 Record.push_back(MD->getKind());
1956 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
1957 MacroID InfoID = getMacroRef(DefMD->getInfo(), Name);
1958 Record.push_back(InfoID);
1959 Record.push_back(DefMD->isImported());
1960 Record.push_back(DefMD->isAmbiguous());
1962 } else if (VisibilityMacroDirective *
1963 VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
1964 Record.push_back(VisMD->isPublic());
1970 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
1973 IdentMacroDirectivesOffsetMap[Name] = MacroDirectiveOffset;
1975 IdentID NameID = getIdentifierRef(Name);
1976 ASTMacroTableTrait::Data data;
1977 data.MacroDirectivesOffset = MacroDirectiveOffset;
1978 Generator.insert(NameID, data);
1981 /// \brief Offsets of each of the macros into the bitstream, indexed by
1982 /// the local macro ID
1984 /// For each identifier that is associated with a macro, this map
1985 /// provides the offset into the bitstream where that macro is
1987 std::vector<uint32_t> MacroOffsets;
1989 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
1990 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
1991 MacroInfo *MI = MacroInfosToEmit[I].MI;
1992 MacroID ID = MacroInfosToEmit[I].ID;
1994 if (ID < FirstMacroID) {
1995 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
1999 // Record the local offset of this macro.
2000 unsigned Index = ID - FirstMacroID;
2001 if (Index == MacroOffsets.size())
2002 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2004 if (Index > MacroOffsets.size())
2005 MacroOffsets.resize(Index + 1);
2007 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2010 AddIdentifierRef(Name, Record);
2011 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2012 AddSourceLocation(MI->getDefinitionLoc(), Record);
2013 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2014 Record.push_back(MI->isUsed());
2016 if (MI->isObjectLike()) {
2017 Code = PP_MACRO_OBJECT_LIKE;
2019 Code = PP_MACRO_FUNCTION_LIKE;
2021 Record.push_back(MI->isC99Varargs());
2022 Record.push_back(MI->isGNUVarargs());
2023 Record.push_back(MI->hasCommaPasting());
2024 Record.push_back(MI->getNumArgs());
2025 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
2027 AddIdentifierRef(*I, Record);
2030 // If we have a detailed preprocessing record, record the macro definition
2031 // ID that corresponds to this macro.
2033 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2035 Stream.EmitRecord(Code, Record);
2038 // Emit the tokens array.
2039 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2040 // Note that we know that the preprocessor does not have any annotation
2041 // tokens in it because they are created by the parser, and thus can't
2042 // be in a macro definition.
2043 const Token &Tok = MI->getReplacementToken(TokNo);
2044 AddToken(Tok, Record);
2045 Stream.EmitRecord(PP_TOKEN, Record);
2053 // Create the on-disk hash table in a buffer.
2054 SmallString<4096> MacroTable;
2055 uint32_t BucketOffset;
2057 llvm::raw_svector_ostream Out(MacroTable);
2058 // Make sure that no bucket is at offset 0
2059 clang::io::Emit32(Out, 0);
2060 BucketOffset = Generator.Emit(Out);
2063 // Write the macro table
2064 using namespace llvm;
2065 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2066 Abbrev->Add(BitCodeAbbrevOp(MACRO_TABLE));
2067 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2068 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2069 unsigned MacroTableAbbrev = Stream.EmitAbbrev(Abbrev);
2071 Record.push_back(MACRO_TABLE);
2072 Record.push_back(BucketOffset);
2073 Stream.EmitRecordWithBlob(MacroTableAbbrev, Record, MacroTable.str());
2076 // Write the offsets table for macro IDs.
2077 using namespace llvm;
2078 Abbrev = new BitCodeAbbrev();
2079 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2080 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2081 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2082 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2084 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2086 Record.push_back(MACRO_OFFSET);
2087 Record.push_back(MacroOffsets.size());
2088 Record.push_back(FirstMacroID - NUM_PREDEF_MACRO_IDS);
2089 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record,
2090 data(MacroOffsets));
2093 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2094 if (PPRec.local_begin() == PPRec.local_end())
2097 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2099 // Enter the preprocessor block.
2100 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2102 // If the preprocessor has a preprocessing record, emit it.
2103 unsigned NumPreprocessingRecords = 0;
2104 using namespace llvm;
2106 // Set up the abbreviation for
2107 unsigned InclusionAbbrev = 0;
2109 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2110 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2111 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2112 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2113 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2114 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2115 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2116 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2119 unsigned FirstPreprocessorEntityID
2120 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2121 + NUM_PREDEF_PP_ENTITY_IDS;
2122 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2124 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2125 EEnd = PPRec.local_end();
2127 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2130 PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(),
2131 Stream.GetCurrentBitNo()));
2133 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
2134 // Record this macro definition's ID.
2135 MacroDefinitions[MD] = NextPreprocessorEntityID;
2137 AddIdentifierRef(MD->getName(), Record);
2138 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2142 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
2143 Record.push_back(ME->isBuiltinMacro());
2144 if (ME->isBuiltinMacro())
2145 AddIdentifierRef(ME->getName(), Record);
2147 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2148 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2152 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
2153 Record.push_back(PPD_INCLUSION_DIRECTIVE);
2154 Record.push_back(ID->getFileName().size());
2155 Record.push_back(ID->wasInQuotes());
2156 Record.push_back(static_cast<unsigned>(ID->getKind()));
2157 Record.push_back(ID->importedModule());
2158 SmallString<64> Buffer;
2159 Buffer += ID->getFileName();
2160 // Check that the FileEntry is not null because it was not resolved and
2161 // we create a PCH even with compiler errors.
2163 Buffer += ID->getFile()->getName();
2164 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2168 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2172 // Write the offsets table for the preprocessing record.
2173 if (NumPreprocessingRecords > 0) {
2174 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2176 // Write the offsets table for identifier IDs.
2177 using namespace llvm;
2178 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2179 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2180 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2181 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2182 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2185 Record.push_back(PPD_ENTITIES_OFFSETS);
2186 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
2187 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2188 data(PreprocessedEntityOffsets));
2192 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2193 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2194 if (Known != SubmoduleIDs.end())
2195 return Known->second;
2197 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2200 unsigned ASTWriter::getExistingSubmoduleID(Module *Mod) const {
2204 llvm::DenseMap<Module *, unsigned>::const_iterator
2205 Known = SubmoduleIDs.find(Mod);
2206 if (Known != SubmoduleIDs.end())
2207 return Known->second;
2212 /// \brief Compute the number of modules within the given tree (including the
2214 static unsigned getNumberOfModules(Module *Mod) {
2215 unsigned ChildModules = 0;
2216 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2217 SubEnd = Mod->submodule_end();
2218 Sub != SubEnd; ++Sub)
2219 ChildModules += getNumberOfModules(*Sub);
2221 return ChildModules + 1;
2224 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2225 // Determine the dependencies of our module and each of it's submodules.
2226 // FIXME: This feels like it belongs somewhere else, but there are no
2227 // other consumers of this information.
2228 SourceManager &SrcMgr = PP->getSourceManager();
2229 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2230 for (ASTContext::import_iterator I = Context->local_import_begin(),
2231 IEnd = Context->local_import_end();
2233 if (Module *ImportedFrom
2234 = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(),
2236 ImportedFrom->Imports.push_back(I->getImportedModule());
2240 // Enter the submodule description block.
2241 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
2243 // Write the abbreviations needed for the submodules block.
2244 using namespace llvm;
2245 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2246 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2247 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2248 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2249 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2250 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2251 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2252 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2253 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2254 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2255 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2256 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2257 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2259 Abbrev = new BitCodeAbbrev();
2260 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2261 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2262 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2264 Abbrev = new BitCodeAbbrev();
2265 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2266 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2267 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2269 Abbrev = new BitCodeAbbrev();
2270 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2271 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2272 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2274 Abbrev = new BitCodeAbbrev();
2275 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2276 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2277 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2279 Abbrev = new BitCodeAbbrev();
2280 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2281 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2282 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2283 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2285 Abbrev = new BitCodeAbbrev();
2286 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2287 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2288 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2290 Abbrev = new BitCodeAbbrev();
2291 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2292 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2293 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2295 Abbrev = new BitCodeAbbrev();
2296 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2297 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2298 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2299 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2301 Abbrev = new BitCodeAbbrev();
2302 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2303 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2304 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2306 Abbrev = new BitCodeAbbrev();
2307 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2308 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2309 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2310 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2312 // Write the submodule metadata block.
2314 Record.push_back(getNumberOfModules(WritingModule));
2315 Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
2316 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2318 // Write all of the submodules.
2319 std::queue<Module *> Q;
2320 Q.push(WritingModule);
2321 while (!Q.empty()) {
2322 Module *Mod = Q.front();
2324 unsigned ID = getSubmoduleID(Mod);
2326 // Emit the definition of the block.
2328 Record.push_back(SUBMODULE_DEFINITION);
2329 Record.push_back(ID);
2331 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2332 Record.push_back(SubmoduleIDs[Mod->Parent]);
2334 Record.push_back(0);
2336 Record.push_back(Mod->IsFramework);
2337 Record.push_back(Mod->IsExplicit);
2338 Record.push_back(Mod->IsSystem);
2339 Record.push_back(Mod->InferSubmodules);
2340 Record.push_back(Mod->InferExplicitSubmodules);
2341 Record.push_back(Mod->InferExportWildcard);
2342 Record.push_back(Mod->ConfigMacrosExhaustive);
2343 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2345 // Emit the requirements.
2346 for (unsigned I = 0, N = Mod->Requirements.size(); I != N; ++I) {
2348 Record.push_back(SUBMODULE_REQUIRES);
2349 Record.push_back(Mod->Requirements[I].second);
2350 Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
2351 Mod->Requirements[I].first);
2354 // Emit the umbrella header, if there is one.
2355 if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) {
2357 Record.push_back(SUBMODULE_UMBRELLA_HEADER);
2358 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2359 UmbrellaHeader->getName());
2360 } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) {
2362 Record.push_back(SUBMODULE_UMBRELLA_DIR);
2363 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2364 UmbrellaDir->getName());
2367 // Emit the headers.
2368 for (unsigned I = 0, N = Mod->NormalHeaders.size(); I != N; ++I) {
2370 Record.push_back(SUBMODULE_HEADER);
2371 Stream.EmitRecordWithBlob(HeaderAbbrev, Record,
2372 Mod->NormalHeaders[I]->getName());
2374 // Emit the excluded headers.
2375 for (unsigned I = 0, N = Mod->ExcludedHeaders.size(); I != N; ++I) {
2377 Record.push_back(SUBMODULE_EXCLUDED_HEADER);
2378 Stream.EmitRecordWithBlob(ExcludedHeaderAbbrev, Record,
2379 Mod->ExcludedHeaders[I]->getName());
2381 // Emit the private headers.
2382 for (unsigned I = 0, N = Mod->PrivateHeaders.size(); I != N; ++I) {
2384 Record.push_back(SUBMODULE_PRIVATE_HEADER);
2385 Stream.EmitRecordWithBlob(PrivateHeaderAbbrev, Record,
2386 Mod->PrivateHeaders[I]->getName());
2388 ArrayRef<const FileEntry *>
2389 TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2390 for (unsigned I = 0, N = TopHeaders.size(); I != N; ++I) {
2392 Record.push_back(SUBMODULE_TOPHEADER);
2393 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record,
2394 TopHeaders[I]->getName());
2397 // Emit the imports.
2398 if (!Mod->Imports.empty()) {
2400 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
2401 unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
2402 assert(ImportedID && "Unknown submodule!");
2403 Record.push_back(ImportedID);
2405 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2408 // Emit the exports.
2409 if (!Mod->Exports.empty()) {
2411 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
2412 if (Module *Exported = Mod->Exports[I].getPointer()) {
2413 unsigned ExportedID = SubmoduleIDs[Exported];
2414 assert(ExportedID > 0 && "Unknown submodule ID?");
2415 Record.push_back(ExportedID);
2417 Record.push_back(0);
2420 Record.push_back(Mod->Exports[I].getInt());
2422 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2425 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2426 // Might be unnecessary as use declarations are only used to build the
2429 // Emit the link libraries.
2430 for (unsigned I = 0, N = Mod->LinkLibraries.size(); I != N; ++I) {
2432 Record.push_back(SUBMODULE_LINK_LIBRARY);
2433 Record.push_back(Mod->LinkLibraries[I].IsFramework);
2434 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record,
2435 Mod->LinkLibraries[I].Library);
2438 // Emit the conflicts.
2439 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2441 Record.push_back(SUBMODULE_CONFLICT);
2442 unsigned OtherID = getSubmoduleID(Mod->Conflicts[I].Other);
2443 assert(OtherID && "Unknown submodule!");
2444 Record.push_back(OtherID);
2445 Stream.EmitRecordWithBlob(ConflictAbbrev, Record,
2446 Mod->Conflicts[I].Message);
2449 // Emit the configuration macros.
2450 for (unsigned I = 0, N = Mod->ConfigMacros.size(); I != N; ++I) {
2452 Record.push_back(SUBMODULE_CONFIG_MACRO);
2453 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record,
2454 Mod->ConfigMacros[I]);
2457 // Queue up the submodules of this module.
2458 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2459 SubEnd = Mod->submodule_end();
2460 Sub != SubEnd; ++Sub)
2466 assert((NextSubmoduleID - FirstSubmoduleID
2467 == getNumberOfModules(WritingModule)) && "Wrong # of submodules");
2470 serialization::SubmoduleID
2471 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
2472 if (Loc.isInvalid() || !WritingModule)
2473 return 0; // No submodule
2475 // Find the module that owns this location.
2476 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2478 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
2482 // Check whether this submodule is part of our own module.
2483 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
2486 return getSubmoduleID(OwningMod);
2489 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2491 // Make sure set diagnostic pragmas don't affect the translation unit that
2492 // imports the module.
2493 // FIXME: Make diagnostic pragma sections work properly with modules.
2497 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2499 unsigned CurrID = 0;
2500 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
2502 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
2503 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2505 const DiagnosticsEngine::DiagStatePoint &point = *I;
2506 if (point.Loc.isInvalid())
2509 Record.push_back(point.Loc.getRawEncoding());
2510 unsigned &DiagStateID = DiagStateIDMap[point.State];
2511 Record.push_back(DiagStateID);
2513 if (DiagStateID == 0) {
2514 DiagStateID = ++CurrID;
2515 for (DiagnosticsEngine::DiagState::const_iterator
2516 I = point.State->begin(), E = point.State->end(); I != E; ++I) {
2517 if (I->second.isPragma()) {
2518 Record.push_back(I->first);
2519 Record.push_back(I->second.getMapping());
2522 Record.push_back(-1); // mark the end of the diag/map pairs for this
2527 if (!Record.empty())
2528 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2531 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2532 if (CXXBaseSpecifiersOffsets.empty())
2537 // Create a blob abbreviation for the C++ base specifiers offsets.
2538 using namespace llvm;
2540 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2541 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2542 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2543 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2544 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2546 // Write the base specifier offsets table.
2548 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2549 Record.push_back(CXXBaseSpecifiersOffsets.size());
2550 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
2551 data(CXXBaseSpecifiersOffsets));
2554 //===----------------------------------------------------------------------===//
2555 // Type Serialization
2556 //===----------------------------------------------------------------------===//
2558 /// \brief Write the representation of a type to the AST stream.
2559 void ASTWriter::WriteType(QualType T) {
2560 TypeIdx &Idx = TypeIdxs[T];
2561 if (Idx.getIndex() == 0) // we haven't seen this type before.
2562 Idx = TypeIdx(NextTypeID++);
2564 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2566 // Record the offset for this type.
2567 unsigned Index = Idx.getIndex() - FirstTypeID;
2568 if (TypeOffsets.size() == Index)
2569 TypeOffsets.push_back(Stream.GetCurrentBitNo());
2570 else if (TypeOffsets.size() < Index) {
2571 TypeOffsets.resize(Index + 1);
2572 TypeOffsets[Index] = Stream.GetCurrentBitNo();
2577 // Emit the type's representation.
2578 ASTTypeWriter W(*this, Record);
2580 if (T.hasLocalNonFastQualifiers()) {
2581 Qualifiers Qs = T.getLocalQualifiers();
2582 AddTypeRef(T.getLocalUnqualifiedType(), Record);
2583 Record.push_back(Qs.getAsOpaqueValue());
2584 W.Code = TYPE_EXT_QUAL;
2586 switch (T->getTypeClass()) {
2587 // For all of the concrete, non-dependent types, call the
2588 // appropriate visitor function.
2589 #define TYPE(Class, Base) \
2590 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
2591 #define ABSTRACT_TYPE(Class, Base)
2592 #include "clang/AST/TypeNodes.def"
2596 // Emit the serialized record.
2597 Stream.EmitRecord(W.Code, Record);
2599 // Flush any expressions that were written as part of this type.
2603 //===----------------------------------------------------------------------===//
2604 // Declaration Serialization
2605 //===----------------------------------------------------------------------===//
2607 /// \brief Write the block containing all of the declaration IDs
2608 /// lexically declared within the given DeclContext.
2610 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2611 /// bistream, or 0 if no block was written.
2612 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2614 if (DC->decls_empty())
2617 uint64_t Offset = Stream.GetCurrentBitNo();
2619 Record.push_back(DECL_CONTEXT_LEXICAL);
2620 SmallVector<KindDeclIDPair, 64> Decls;
2621 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
2623 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
2625 ++NumLexicalDeclContexts;
2626 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
2630 void ASTWriter::WriteTypeDeclOffsets() {
2631 using namespace llvm;
2634 // Write the type offsets array
2635 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2636 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2637 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2638 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2639 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2640 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2642 Record.push_back(TYPE_OFFSET);
2643 Record.push_back(TypeOffsets.size());
2644 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
2645 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
2647 // Write the declaration offsets array
2648 Abbrev = new BitCodeAbbrev();
2649 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2650 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2651 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2652 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2653 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2655 Record.push_back(DECL_OFFSET);
2656 Record.push_back(DeclOffsets.size());
2657 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
2658 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
2661 void ASTWriter::WriteFileDeclIDsMap() {
2662 using namespace llvm;
2665 // Join the vectors of DeclIDs from all files.
2666 SmallVector<DeclID, 256> FileSortedIDs;
2667 for (FileDeclIDsTy::iterator
2668 FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) {
2669 DeclIDInFileInfo &Info = *FI->second;
2670 Info.FirstDeclIndex = FileSortedIDs.size();
2671 for (LocDeclIDsTy::iterator
2672 DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI)
2673 FileSortedIDs.push_back(DI->second);
2676 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2677 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2678 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2679 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2680 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
2681 Record.push_back(FILE_SORTED_DECLS);
2682 Record.push_back(FileSortedIDs.size());
2683 Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs));
2686 void ASTWriter::WriteComments() {
2687 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2688 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
2690 for (ArrayRef<RawComment *>::iterator I = RawComments.begin(),
2691 E = RawComments.end();
2694 AddSourceRange((*I)->getSourceRange(), Record);
2695 Record.push_back((*I)->getKind());
2696 Record.push_back((*I)->isTrailingComment());
2697 Record.push_back((*I)->isAlmostTrailingComment());
2698 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2703 //===----------------------------------------------------------------------===//
2704 // Global Method Pool and Selector Serialization
2705 //===----------------------------------------------------------------------===//
2708 // Trait used for the on-disk hash table used in the method pool.
2709 class ASTMethodPoolTrait {
2713 typedef Selector key_type;
2714 typedef key_type key_type_ref;
2718 ObjCMethodList Instance, Factory;
2720 typedef const data_type& data_type_ref;
2722 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2724 static unsigned ComputeHash(Selector Sel) {
2725 return serialization::ComputeHash(Sel);
2728 std::pair<unsigned,unsigned>
2729 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2730 data_type_ref Methods) {
2731 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2732 clang::io::Emit16(Out, KeyLen);
2733 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2734 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2735 Method = Method->getNext())
2738 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2739 Method = Method->getNext())
2742 clang::io::Emit16(Out, DataLen);
2743 return std::make_pair(KeyLen, DataLen);
2746 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
2747 uint64_t Start = Out.tell();
2748 assert((Start >> 32) == 0 && "Selector key offset too large");
2749 Writer.SetSelectorOffset(Sel, Start);
2750 unsigned N = Sel.getNumArgs();
2751 clang::io::Emit16(Out, N);
2754 for (unsigned I = 0; I != N; ++I)
2755 clang::io::Emit32(Out,
2756 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2759 void EmitData(raw_ostream& Out, key_type_ref,
2760 data_type_ref Methods, unsigned DataLen) {
2761 uint64_t Start = Out.tell(); (void)Start;
2762 clang::io::Emit32(Out, Methods.ID);
2763 unsigned NumInstanceMethods = 0;
2764 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2765 Method = Method->getNext())
2767 ++NumInstanceMethods;
2769 unsigned NumFactoryMethods = 0;
2770 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2771 Method = Method->getNext())
2773 ++NumFactoryMethods;
2775 unsigned InstanceBits = Methods.Instance.getBits();
2776 assert(InstanceBits < 4);
2777 unsigned NumInstanceMethodsAndBits =
2778 (NumInstanceMethods << 2) | InstanceBits;
2779 unsigned FactoryBits = Methods.Factory.getBits();
2780 assert(FactoryBits < 4);
2781 unsigned NumFactoryMethodsAndBits = (NumFactoryMethods << 2) | FactoryBits;
2782 clang::io::Emit16(Out, NumInstanceMethodsAndBits);
2783 clang::io::Emit16(Out, NumFactoryMethodsAndBits);
2784 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2785 Method = Method->getNext())
2787 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2788 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2789 Method = Method->getNext())
2791 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2793 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2796 } // end anonymous namespace
2798 /// \brief Write ObjC data: selectors and the method pool.
2800 /// The method pool contains both instance and factory methods, stored
2801 /// in an on-disk hash table indexed by the selector. The hash table also
2802 /// contains an empty entry for every other selector known to Sema.
2803 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2804 using namespace llvm;
2806 // Do we have to do anything at all?
2807 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2809 unsigned NumTableEntries = 0;
2810 // Create and write out the blob that contains selectors and the method pool.
2812 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2813 ASTMethodPoolTrait Trait(*this);
2815 // Create the on-disk hash table representation. We walk through every
2816 // selector we've seen and look it up in the method pool.
2817 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2818 for (llvm::DenseMap<Selector, SelectorID>::iterator
2819 I = SelectorIDs.begin(), E = SelectorIDs.end();
2821 Selector S = I->first;
2822 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2823 ASTMethodPoolTrait::data_type Data = {
2828 if (F != SemaRef.MethodPool.end()) {
2829 Data.Instance = F->second.first;
2830 Data.Factory = F->second.second;
2832 // Only write this selector if it's not in an existing AST or something
2834 if (Chain && I->second < FirstSelectorID) {
2835 // Selector already exists. Did it change?
2836 bool changed = false;
2837 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
2839 if (!M->Method->isFromASTFile())
2842 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
2844 if (!M->Method->isFromASTFile())
2849 } else if (Data.Instance.Method || Data.Factory.Method) {
2850 // A new method pool entry.
2853 Generator.insert(S, Data, Trait);
2856 // Create the on-disk hash table in a buffer.
2857 SmallString<4096> MethodPool;
2858 uint32_t BucketOffset;
2860 ASTMethodPoolTrait Trait(*this);
2861 llvm::raw_svector_ostream Out(MethodPool);
2862 // Make sure that no bucket is at offset 0
2863 clang::io::Emit32(Out, 0);
2864 BucketOffset = Generator.Emit(Out, Trait);
2867 // Create a blob abbreviation
2868 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2869 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
2870 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2871 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2872 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2873 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
2875 // Write the method pool
2877 Record.push_back(METHOD_POOL);
2878 Record.push_back(BucketOffset);
2879 Record.push_back(NumTableEntries);
2880 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
2882 // Create a blob abbreviation for the selector table offsets.
2883 Abbrev = new BitCodeAbbrev();
2884 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
2885 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2886 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2887 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2888 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2890 // Write the selector offsets table.
2892 Record.push_back(SELECTOR_OFFSETS);
2893 Record.push_back(SelectorOffsets.size());
2894 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
2895 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
2896 data(SelectorOffsets));
2900 /// \brief Write the selectors referenced in @selector expression into AST file.
2901 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
2902 using namespace llvm;
2903 if (SemaRef.ReferencedSelectors.empty())
2908 // Note: this writes out all references even for a dependent AST. But it is
2909 // very tricky to fix, and given that @selector shouldn't really appear in
2910 // headers, probably not worth it. It's not a correctness issue.
2911 for (DenseMap<Selector, SourceLocation>::iterator S =
2912 SemaRef.ReferencedSelectors.begin(),
2913 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
2914 Selector Sel = (*S).first;
2915 SourceLocation Loc = (*S).second;
2916 AddSelectorRef(Sel, Record);
2917 AddSourceLocation(Loc, Record);
2919 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
2922 //===----------------------------------------------------------------------===//
2923 // Identifier Table Serialization
2924 //===----------------------------------------------------------------------===//
2927 class ASTIdentifierTableTrait {
2930 IdentifierResolver &IdResolver;
2933 /// \brief Determines whether this is an "interesting" identifier
2934 /// that needs a full IdentifierInfo structure written into the hash
2936 bool isInterestingIdentifier(IdentifierInfo *II, MacroDirective *&Macro) {
2937 if (II->isPoisoned() ||
2938 II->isExtensionToken() ||
2939 II->getObjCOrBuiltinID() ||
2940 II->hasRevertedTokenIDToIdentifier() ||
2941 II->getFETokenInfo<void>())
2944 return hadMacroDefinition(II, Macro);
2947 bool hadMacroDefinition(IdentifierInfo *II, MacroDirective *&Macro) {
2948 if (!II->hadMacroDefinition())
2951 if (Macro || (Macro = PP.getMacroDirectiveHistory(II))) {
2953 return !shouldIgnoreMacro(Macro, IsModule, PP);
2955 if (getFirstPublicSubmoduleMacro(Macro, ModID))
2962 DefMacroDirective *getFirstPublicSubmoduleMacro(MacroDirective *MD,
2963 SubmoduleID &ModID) {
2965 if (DefMacroDirective *DefMD = getPublicSubmoduleMacro(MD, ModID))
2966 if (!shouldIgnoreMacro(DefMD, IsModule, PP))
2971 DefMacroDirective *getNextPublicSubmoduleMacro(DefMacroDirective *MD,
2972 SubmoduleID &ModID) {
2973 if (DefMacroDirective *
2974 DefMD = getPublicSubmoduleMacro(MD->getPrevious(), ModID))
2975 if (!shouldIgnoreMacro(DefMD, IsModule, PP))
2980 /// \brief Traverses the macro directives history and returns the latest
2981 /// macro that is public and not undefined in the same submodule.
2982 /// A macro that is defined in submodule A and undefined in submodule B,
2983 /// will still be considered as defined/exported from submodule A.
2984 DefMacroDirective *getPublicSubmoduleMacro(MacroDirective *MD,
2985 SubmoduleID &ModID) {
2989 SubmoduleID OrigModID = ModID;
2990 bool isUndefined = false;
2991 Optional<bool> isPublic;
2992 for (; MD; MD = MD->getPrevious()) {
2996 SubmoduleID ThisModID = getSubmoduleID(MD);
2997 if (ThisModID == 0) {
2998 isUndefined = false;
2999 isPublic = Optional<bool>();
3002 if (ThisModID != ModID){
3004 isUndefined = false;
3005 isPublic = Optional<bool>();
3007 // We are looking for a definition in a different submodule than the one
3008 // that we started with. If a submodule has re-definitions of the same
3009 // macro, only the last definition will be used as the "exported" one.
3010 if (ModID == OrigModID)
3013 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
3014 if (!isUndefined && (!isPublic.hasValue() || isPublic.getValue()))
3019 if (isa<UndefMacroDirective>(MD)) {
3024 VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
3025 if (!isPublic.hasValue())
3026 isPublic = VisMD->isPublic();
3032 SubmoduleID getSubmoduleID(MacroDirective *MD) {
3033 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
3034 MacroInfo *MI = DefMD->getInfo();
3035 if (unsigned ID = MI->getOwningModuleID())
3037 return Writer.inferSubmoduleIDFromLocation(MI->getDefinitionLoc());
3039 return Writer.inferSubmoduleIDFromLocation(MD->getLocation());
3043 typedef IdentifierInfo* key_type;
3044 typedef key_type key_type_ref;
3046 typedef IdentID data_type;
3047 typedef data_type data_type_ref;
3049 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3050 IdentifierResolver &IdResolver, bool IsModule)
3051 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { }
3053 static unsigned ComputeHash(const IdentifierInfo* II) {
3054 return llvm::HashString(II->getName());
3057 std::pair<unsigned,unsigned>
3058 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3059 unsigned KeyLen = II->getLength() + 1;
3060 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3061 MacroDirective *Macro = 0;
3062 if (isInterestingIdentifier(II, Macro)) {
3063 DataLen += 2; // 2 bytes for builtin ID
3064 DataLen += 2; // 2 bytes for flags
3065 if (hadMacroDefinition(II, Macro)) {
3066 DataLen += 4; // MacroDirectives offset.
3069 for (DefMacroDirective *
3070 DefMD = getFirstPublicSubmoduleMacro(Macro, ModID);
3071 DefMD; DefMD = getNextPublicSubmoduleMacro(DefMD, ModID)) {
3072 DataLen += 4; // MacroInfo ID.
3078 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3079 DEnd = IdResolver.end();
3081 DataLen += sizeof(DeclID);
3083 clang::io::Emit16(Out, DataLen);
3084 // We emit the key length after the data length so that every
3085 // string is preceded by a 16-bit length. This matches the PTH
3086 // format for storing identifiers.
3087 clang::io::Emit16(Out, KeyLen);
3088 return std::make_pair(KeyLen, DataLen);
3091 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3093 // Record the location of the key data. This is used when generating
3094 // the mapping from persistent IDs to strings.
3095 Writer.SetIdentifierOffset(II, Out.tell());
3096 Out.write(II->getNameStart(), KeyLen);
3099 void EmitData(raw_ostream& Out, IdentifierInfo* II,
3100 IdentID ID, unsigned) {
3101 MacroDirective *Macro = 0;
3102 if (!isInterestingIdentifier(II, Macro)) {
3103 clang::io::Emit32(Out, ID << 1);
3107 clang::io::Emit32(Out, (ID << 1) | 0x01);
3108 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3109 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3110 clang::io::Emit16(Out, Bits);
3112 bool HadMacroDefinition = hadMacroDefinition(II, Macro);
3113 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3114 Bits = (Bits << 1) | unsigned(IsModule);
3115 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3116 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3117 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3118 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3119 clang::io::Emit16(Out, Bits);
3121 if (HadMacroDefinition) {
3122 clang::io::Emit32(Out, Writer.getMacroDirectivesOffset(II));
3124 // Write the IDs of macros coming from different submodules.
3126 for (DefMacroDirective *
3127 DefMD = getFirstPublicSubmoduleMacro(Macro, ModID);
3128 DefMD; DefMD = getNextPublicSubmoduleMacro(DefMD, ModID)) {
3129 MacroID InfoID = Writer.getMacroID(DefMD->getInfo());
3131 clang::io::Emit32(Out, InfoID);
3133 clang::io::Emit32(Out, 0);
3137 // Emit the declaration IDs in reverse order, because the
3138 // IdentifierResolver provides the declarations as they would be
3139 // visible (e.g., the function "stat" would come before the struct
3140 // "stat"), but the ASTReader adds declarations to the end of the list
3141 // (so we need to see the struct "status" before the function "status").
3142 // Only emit declarations that aren't from a chained PCH, though.
3143 SmallVector<Decl *, 16> Decls(IdResolver.begin(II),
3145 for (SmallVectorImpl<Decl *>::reverse_iterator D = Decls.rbegin(),
3146 DEnd = Decls.rend();
3148 clang::io::Emit32(Out, Writer.getDeclID(getMostRecentLocalDecl(*D)));
3151 /// \brief Returns the most recent local decl or the given decl if there are
3152 /// no local ones. The given decl is assumed to be the most recent one.
3153 Decl *getMostRecentLocalDecl(Decl *Orig) {
3154 // The only way a "from AST file" decl would be more recent from a local one
3155 // is if it came from a module.
3156 if (!PP.getLangOpts().Modules)
3159 // Look for a local in the decl chain.
3160 for (Decl *D = Orig; D; D = D->getPreviousDecl()) {
3161 if (!D->isFromASTFile())
3163 // If we come up a decl from a (chained-)PCH stop since we won't find a
3165 if (D->getOwningModuleID() == 0)
3172 } // end anonymous namespace
3174 /// \brief Write the identifier table into the AST file.
3176 /// The identifier table consists of a blob containing string data
3177 /// (the actual identifiers themselves) and a separate "offsets" index
3178 /// that maps identifier IDs to locations within the blob.
3179 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3180 IdentifierResolver &IdResolver,
3182 using namespace llvm;
3184 // Create and write out the blob that contains the identifier
3187 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3188 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
3190 // Look for any identifiers that were named while processing the
3191 // headers, but are otherwise not needed. We add these to the hash
3192 // table to enable checking of the predefines buffer in the case
3193 // where the user adds new macro definitions when building the AST
3195 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3196 IDEnd = PP.getIdentifierTable().end();
3198 getIdentifierRef(ID->second);
3200 // Create the on-disk hash table representation. We only store offsets
3201 // for identifiers that appear here for the first time.
3202 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3203 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
3204 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
3205 ID != IDEnd; ++ID) {
3206 assert(ID->first && "NULL identifier in identifier table");
3207 if (!Chain || !ID->first->isFromAST() ||
3208 ID->first->hasChangedSinceDeserialization())
3209 Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second,
3213 // Create the on-disk hash table in a buffer.
3214 SmallString<4096> IdentifierTable;
3215 uint32_t BucketOffset;
3217 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
3218 llvm::raw_svector_ostream Out(IdentifierTable);
3219 // Make sure that no bucket is at offset 0
3220 clang::io::Emit32(Out, 0);
3221 BucketOffset = Generator.Emit(Out, Trait);
3224 // Create a blob abbreviation
3225 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3226 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3227 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3228 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3229 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
3231 // Write the identifier table
3233 Record.push_back(IDENTIFIER_TABLE);
3234 Record.push_back(BucketOffset);
3235 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
3238 // Write the offsets table for identifier IDs.
3239 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3240 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3241 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3242 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3243 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3244 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3247 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3248 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3252 Record.push_back(IDENTIFIER_OFFSET);
3253 Record.push_back(IdentifierOffsets.size());
3254 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
3255 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3256 data(IdentifierOffsets));
3259 //===----------------------------------------------------------------------===//
3260 // DeclContext's Name Lookup Table Serialization
3261 //===----------------------------------------------------------------------===//
3264 // Trait used for the on-disk hash table used in the method pool.
3265 class ASTDeclContextNameLookupTrait {
3269 typedef DeclarationName key_type;
3270 typedef key_type key_type_ref;
3272 typedef DeclContext::lookup_result data_type;
3273 typedef const data_type& data_type_ref;
3275 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3277 unsigned ComputeHash(DeclarationName Name) {
3278 llvm::FoldingSetNodeID ID;
3279 ID.AddInteger(Name.getNameKind());
3281 switch (Name.getNameKind()) {
3282 case DeclarationName::Identifier:
3283 ID.AddString(Name.getAsIdentifierInfo()->getName());
3285 case DeclarationName::ObjCZeroArgSelector:
3286 case DeclarationName::ObjCOneArgSelector:
3287 case DeclarationName::ObjCMultiArgSelector:
3288 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
3290 case DeclarationName::CXXConstructorName:
3291 case DeclarationName::CXXDestructorName:
3292 case DeclarationName::CXXConversionFunctionName:
3294 case DeclarationName::CXXOperatorName:
3295 ID.AddInteger(Name.getCXXOverloadedOperator());
3297 case DeclarationName::CXXLiteralOperatorName:
3298 ID.AddString(Name.getCXXLiteralIdentifier()->getName());
3299 case DeclarationName::CXXUsingDirective:
3303 return ID.ComputeHash();
3306 std::pair<unsigned,unsigned>
3307 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
3308 data_type_ref Lookup) {
3309 unsigned KeyLen = 1;
3310 switch (Name.getNameKind()) {
3311 case DeclarationName::Identifier:
3312 case DeclarationName::ObjCZeroArgSelector:
3313 case DeclarationName::ObjCOneArgSelector:
3314 case DeclarationName::ObjCMultiArgSelector:
3315 case DeclarationName::CXXLiteralOperatorName:
3318 case DeclarationName::CXXOperatorName:
3321 case DeclarationName::CXXConstructorName:
3322 case DeclarationName::CXXDestructorName:
3323 case DeclarationName::CXXConversionFunctionName:
3324 case DeclarationName::CXXUsingDirective:
3327 clang::io::Emit16(Out, KeyLen);
3329 // 2 bytes for num of decls and 4 for each DeclID.
3330 unsigned DataLen = 2 + 4 * Lookup.size();
3331 clang::io::Emit16(Out, DataLen);
3333 return std::make_pair(KeyLen, DataLen);
3336 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
3337 using namespace clang::io;
3339 Emit8(Out, Name.getNameKind());
3340 switch (Name.getNameKind()) {
3341 case DeclarationName::Identifier:
3342 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
3344 case DeclarationName::ObjCZeroArgSelector:
3345 case DeclarationName::ObjCOneArgSelector:
3346 case DeclarationName::ObjCMultiArgSelector:
3347 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
3349 case DeclarationName::CXXOperatorName:
3350 assert(Name.getCXXOverloadedOperator() < NUM_OVERLOADED_OPERATORS &&
3351 "Invalid operator?");
3352 Emit8(Out, Name.getCXXOverloadedOperator());
3354 case DeclarationName::CXXLiteralOperatorName:
3355 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
3357 case DeclarationName::CXXConstructorName:
3358 case DeclarationName::CXXDestructorName:
3359 case DeclarationName::CXXConversionFunctionName:
3360 case DeclarationName::CXXUsingDirective:
3364 llvm_unreachable("Invalid name kind?");
3367 void EmitData(raw_ostream& Out, key_type_ref,
3368 data_type Lookup, unsigned DataLen) {
3369 uint64_t Start = Out.tell(); (void)Start;
3370 clang::io::Emit16(Out, Lookup.size());
3371 for (DeclContext::lookup_iterator I = Lookup.begin(), E = Lookup.end();
3373 clang::io::Emit32(Out, Writer.GetDeclRef(*I));
3375 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3378 } // end anonymous namespace
3380 /// \brief Write the block containing all of the declaration IDs
3381 /// visible from the given DeclContext.
3383 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3384 /// bitstream, or 0 if no block was written.
3385 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3387 if (DC->getPrimaryContext() != DC)
3390 // Since there is no name lookup into functions or methods, don't bother to
3391 // build a visible-declarations table for these entities.
3392 if (DC->isFunctionOrMethod())
3395 // If not in C++, we perform name lookup for the translation unit via the
3396 // IdentifierInfo chains, don't bother to build a visible-declarations table.
3397 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3400 // Serialize the contents of the mapping used for lookup. Note that,
3401 // although we have two very different code paths, the serialized
3402 // representation is the same for both cases: a declaration name,
3403 // followed by a size, followed by references to the visible
3404 // declarations that have that name.
3405 uint64_t Offset = Stream.GetCurrentBitNo();
3406 StoredDeclsMap *Map = DC->buildLookup();
3407 if (!Map || Map->empty())
3410 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
3411 ASTDeclContextNameLookupTrait Trait(*this);
3413 // Create the on-disk hash table representation.
3414 DeclarationName ConversionName;
3415 SmallVector<NamedDecl *, 4> ConversionDecls;
3416 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
3418 DeclarationName Name = D->first;
3419 DeclContext::lookup_result Result = D->second.getLookupResult();
3420 if (!Result.empty()) {
3421 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3422 // Hash all conversion function names to the same name. The actual
3423 // type information in conversion function name is not used in the
3424 // key (since such type information is not stable across different
3425 // modules), so the intended effect is to coalesce all of the conversion
3426 // functions under a single key.
3427 if (!ConversionName)
3428 ConversionName = Name;
3429 ConversionDecls.append(Result.begin(), Result.end());
3433 Generator.insert(Name, Result, Trait);
3437 // Add the conversion functions
3438 if (!ConversionDecls.empty()) {
3439 Generator.insert(ConversionName,
3440 DeclContext::lookup_result(ConversionDecls.begin(),
3441 ConversionDecls.end()),
3445 // Create the on-disk hash table in a buffer.
3446 SmallString<4096> LookupTable;
3447 uint32_t BucketOffset;
3449 llvm::raw_svector_ostream Out(LookupTable);
3450 // Make sure that no bucket is at offset 0
3451 clang::io::Emit32(Out, 0);
3452 BucketOffset = Generator.Emit(Out, Trait);
3455 // Write the lookup table
3457 Record.push_back(DECL_CONTEXT_VISIBLE);
3458 Record.push_back(BucketOffset);
3459 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3462 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
3463 ++NumVisibleDeclContexts;
3467 /// \brief Write an UPDATE_VISIBLE block for the given context.
3469 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3470 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3471 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3472 /// enumeration members (in C++11).
3473 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3474 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
3475 if (!Map || Map->empty())
3478 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
3479 ASTDeclContextNameLookupTrait Trait(*this);
3481 // Create the hash table.
3482 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
3484 DeclarationName Name = D->first;
3485 DeclContext::lookup_result Result = D->second.getLookupResult();
3486 // For any name that appears in this table, the results are complete, i.e.
3487 // they overwrite results from previous PCHs. Merging is always a mess.
3488 if (!Result.empty())
3489 Generator.insert(Name, Result, Trait);
3492 // Create the on-disk hash table in a buffer.
3493 SmallString<4096> LookupTable;
3494 uint32_t BucketOffset;
3496 llvm::raw_svector_ostream Out(LookupTable);
3497 // Make sure that no bucket is at offset 0
3498 clang::io::Emit32(Out, 0);
3499 BucketOffset = Generator.Emit(Out, Trait);
3502 // Write the lookup table
3504 Record.push_back(UPDATE_VISIBLE);
3505 Record.push_back(getDeclID(cast<Decl>(DC)));
3506 Record.push_back(BucketOffset);
3507 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
3510 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3511 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3513 Record.push_back(Opts.fp_contract);
3514 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3517 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3518 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3519 if (!SemaRef.Context.getLangOpts().OpenCL)
3522 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3524 #define OPENCLEXT(nm) Record.push_back(Opts.nm);
3525 #include "clang/Basic/OpenCLExtensions.def"
3526 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3529 void ASTWriter::WriteRedeclarations() {
3530 RecordData LocalRedeclChains;
3531 SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
3533 for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
3534 Decl *First = Redeclarations[I];
3535 assert(First->isFirstDecl() && "Not the first declaration?");
3537 Decl *MostRecent = First->getMostRecentDecl();
3539 // If we only have a single declaration, there is no point in storing
3540 // a redeclaration chain.
3541 if (First == MostRecent)
3544 unsigned Offset = LocalRedeclChains.size();
3546 LocalRedeclChains.push_back(0); // Placeholder for the size.
3548 // Collect the set of local redeclarations of this declaration.
3549 for (Decl *Prev = MostRecent; Prev != First;
3550 Prev = Prev->getPreviousDecl()) {
3551 if (!Prev->isFromASTFile()) {
3552 AddDeclRef(Prev, LocalRedeclChains);
3557 if (!First->isFromASTFile() && Chain) {
3558 Decl *FirstFromAST = MostRecent;
3559 for (Decl *Prev = MostRecent; Prev; Prev = Prev->getPreviousDecl()) {
3560 if (Prev->isFromASTFile())
3561 FirstFromAST = Prev;
3564 Chain->MergedDecls[FirstFromAST].push_back(getDeclID(First));
3567 LocalRedeclChains[Offset] = Size;
3569 // Reverse the set of local redeclarations, so that we store them in
3570 // order (since we found them in reverse order).
3571 std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
3573 // Add the mapping from the first ID from the AST to the set of local
3575 LocalRedeclarationsInfo Info = { getDeclID(First), Offset };
3576 LocalRedeclsMap.push_back(Info);
3578 assert(N == Redeclarations.size() &&
3579 "Deserialized a declaration we shouldn't have");
3582 if (LocalRedeclChains.empty())
3585 // Sort the local redeclarations map by the first declaration ID,
3586 // since the reader will be performing binary searches on this information.
3587 llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
3589 // Emit the local redeclarations map.
3590 using namespace llvm;
3591 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3592 Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
3593 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3594 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3595 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3598 Record.push_back(LOCAL_REDECLARATIONS_MAP);
3599 Record.push_back(LocalRedeclsMap.size());
3600 Stream.EmitRecordWithBlob(AbbrevID, Record,
3601 reinterpret_cast<char*>(LocalRedeclsMap.data()),
3602 LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
3604 // Emit the redeclaration chains.
3605 Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
3608 void ASTWriter::WriteObjCCategories() {
3609 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3610 RecordData Categories;
3612 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3614 unsigned StartIndex = Categories.size();
3616 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3618 // Allocate space for the size.
3619 Categories.push_back(0);
3621 // Add the categories.
3622 for (ObjCInterfaceDecl::known_categories_iterator
3623 Cat = Class->known_categories_begin(),
3624 CatEnd = Class->known_categories_end();
3625 Cat != CatEnd; ++Cat, ++Size) {
3626 assert(getDeclID(*Cat) != 0 && "Bogus category");
3627 AddDeclRef(*Cat, Categories);
3631 Categories[StartIndex] = Size;
3633 // Record this interface -> category map.
3634 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3635 CategoriesMap.push_back(CatInfo);
3638 // Sort the categories map by the definition ID, since the reader will be
3639 // performing binary searches on this information.
3640 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3642 // Emit the categories map.
3643 using namespace llvm;
3644 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3645 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3646 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3647 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3648 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3651 Record.push_back(OBJC_CATEGORIES_MAP);
3652 Record.push_back(CategoriesMap.size());
3653 Stream.EmitRecordWithBlob(AbbrevID, Record,
3654 reinterpret_cast<char*>(CategoriesMap.data()),
3655 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3657 // Emit the category lists.
3658 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3661 void ASTWriter::WriteMergedDecls() {
3662 if (!Chain || Chain->MergedDecls.empty())
3666 for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(),
3667 IEnd = Chain->MergedDecls.end();
3669 DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID()
3670 : getDeclID(I->first);
3671 assert(CanonID && "Merged declaration not known?");
3673 Record.push_back(CanonID);
3674 Record.push_back(I->second.size());
3675 Record.append(I->second.begin(), I->second.end());
3677 Stream.EmitRecord(MERGED_DECLARATIONS, Record);
3680 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3681 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
3687 for (Sema::LateParsedTemplateMapT::iterator It = LPTMap.begin(),
3688 ItEnd = LPTMap.end();
3689 It != ItEnd; ++It) {
3690 LateParsedTemplate *LPT = It->second;
3691 AddDeclRef(It->first, Record);
3692 AddDeclRef(LPT->D, Record);
3693 Record.push_back(LPT->Toks.size());
3695 for (CachedTokens::iterator TokIt = LPT->Toks.begin(),
3696 TokEnd = LPT->Toks.end();
3697 TokIt != TokEnd; ++TokIt) {
3698 AddToken(*TokIt, Record);
3701 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3704 //===----------------------------------------------------------------------===//
3705 // General Serialization Routines
3706 //===----------------------------------------------------------------------===//
3708 /// \brief Write a record containing the given attributes.
3709 void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
3710 RecordDataImpl &Record) {
3711 Record.push_back(Attrs.size());
3712 for (ArrayRef<const Attr *>::iterator i = Attrs.begin(),
3713 e = Attrs.end(); i != e; ++i){
3715 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
3716 AddSourceRange(A->getRange(), Record);
3718 #include "clang/Serialization/AttrPCHWrite.inc"
3723 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
3724 AddSourceLocation(Tok.getLocation(), Record);
3725 Record.push_back(Tok.getLength());
3727 // FIXME: When reading literal tokens, reconstruct the literal pointer
3729 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
3730 // FIXME: Should translate token kind to a stable encoding.
3731 Record.push_back(Tok.getKind());
3732 // FIXME: Should translate token flags to a stable encoding.
3733 Record.push_back(Tok.getFlags());
3736 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
3737 Record.push_back(Str.size());
3738 Record.insert(Record.end(), Str.begin(), Str.end());
3741 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
3742 RecordDataImpl &Record) {
3743 Record.push_back(Version.getMajor());
3744 if (Optional<unsigned> Minor = Version.getMinor())
3745 Record.push_back(*Minor + 1);
3747 Record.push_back(0);
3748 if (Optional<unsigned> Subminor = Version.getSubminor())
3749 Record.push_back(*Subminor + 1);
3751 Record.push_back(0);
3754 /// \brief Note that the identifier II occurs at the given offset
3755 /// within the identifier table.
3756 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
3757 IdentID ID = IdentifierIDs[II];
3758 // Only store offsets new to this AST file. Other identifier names are looked
3759 // up earlier in the chain and thus don't need an offset.
3760 if (ID >= FirstIdentID)
3761 IdentifierOffsets[ID - FirstIdentID] = Offset;
3764 /// \brief Note that the selector Sel occurs at the given offset
3765 /// within the method pool/selector table.
3766 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
3767 unsigned ID = SelectorIDs[Sel];
3768 assert(ID && "Unknown selector");
3769 // Don't record offsets for selectors that are also available in a different
3771 if (ID < FirstSelectorID)
3773 SelectorOffsets[ID - FirstSelectorID] = Offset;
3776 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
3777 : Stream(Stream), Context(0), PP(0), Chain(0), WritingModule(0),
3778 WritingAST(false), DoneWritingDeclsAndTypes(false),
3779 ASTHasCompilerErrors(false),
3780 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
3781 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
3782 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
3783 FirstMacroID(NUM_PREDEF_MACRO_IDS), NextMacroID(FirstMacroID),
3784 FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
3785 NextSubmoduleID(FirstSubmoduleID),
3786 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
3787 CollectedStmts(&StmtsToEmit),
3788 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
3789 NumVisibleDeclContexts(0),
3790 NextCXXBaseSpecifiersID(1),
3791 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0),
3792 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0),
3793 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0),
3794 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0),
3795 DeclTypedefAbbrev(0),
3796 DeclVarAbbrev(0), DeclFieldAbbrev(0),
3797 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0)
3801 ASTWriter::~ASTWriter() {
3802 for (FileDeclIDsTy::iterator
3803 I = FileDeclIDs.begin(), E = FileDeclIDs.end(); I != E; ++I)
3807 void ASTWriter::WriteAST(Sema &SemaRef,
3808 const std::string &OutputFile,
3809 Module *WritingModule, StringRef isysroot,
3813 ASTHasCompilerErrors = hasErrors;
3815 // Emit the file header.
3816 Stream.Emit((unsigned)'C', 8);
3817 Stream.Emit((unsigned)'P', 8);
3818 Stream.Emit((unsigned)'C', 8);
3819 Stream.Emit((unsigned)'H', 8);
3821 WriteBlockInfoBlock();
3823 Context = &SemaRef.Context;
3825 this->WritingModule = WritingModule;
3826 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
3829 this->WritingModule = 0;
3834 template<typename Vector>
3835 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
3836 ASTWriter::RecordData &Record) {
3837 for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end();
3839 Writer.AddDeclRef(*I, Record);
3843 void ASTWriter::WriteASTCore(Sema &SemaRef,
3845 const std::string &OutputFile,
3846 Module *WritingModule) {
3847 using namespace llvm;
3849 bool isModule = WritingModule != 0;
3851 // Make sure that the AST reader knows to finalize itself.
3853 Chain->finalizeForWriting();
3855 ASTContext &Context = SemaRef.Context;
3856 Preprocessor &PP = SemaRef.PP;
3858 // Set up predefined declaration IDs.
3859 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
3860 if (Context.ObjCIdDecl)
3861 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
3862 if (Context.ObjCSelDecl)
3863 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
3864 if (Context.ObjCClassDecl)
3865 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
3866 if (Context.ObjCProtocolClassDecl)
3867 DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID;
3868 if (Context.Int128Decl)
3869 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
3870 if (Context.UInt128Decl)
3871 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
3872 if (Context.ObjCInstanceTypeDecl)
3873 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
3874 if (Context.BuiltinVaListDecl)
3875 DeclIDs[Context.getBuiltinVaListDecl()] = PREDEF_DECL_BUILTIN_VA_LIST_ID;
3878 // Make sure that we emit IdentifierInfos (and any attached
3879 // declarations) for builtins. We don't need to do this when we're
3880 // emitting chained PCH files, because all of the builtins will be
3881 // in the original PCH file.
3882 // FIXME: Modules won't like this at all.
3883 IdentifierTable &Table = PP.getIdentifierTable();
3884 SmallVector<const char *, 32> BuiltinNames;
3885 if (!Context.getLangOpts().NoBuiltin) {
3886 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames);
3888 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
3889 getIdentifierRef(&Table.get(BuiltinNames[I]));
3892 // If there are any out-of-date identifiers, bring them up to date.
3893 if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) {
3894 // Find out-of-date identifiers.
3895 SmallVector<IdentifierInfo *, 4> OutOfDate;
3896 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3897 IDEnd = PP.getIdentifierTable().end();
3898 ID != IDEnd; ++ID) {
3899 if (ID->second->isOutOfDate())
3900 OutOfDate.push_back(ID->second);
3903 // Update the out-of-date identifiers.
3904 for (unsigned I = 0, N = OutOfDate.size(); I != N; ++I) {
3905 ExtSource->updateOutOfDateIdentifier(*OutOfDate[I]);
3909 // Build a record containing all of the tentative definitions in this file, in
3910 // TentativeDefinitions order. Generally, this record will be empty for
3912 RecordData TentativeDefinitions;
3913 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
3915 // Build a record containing all of the file scoped decls in this file.
3916 RecordData UnusedFileScopedDecls;
3918 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
3919 UnusedFileScopedDecls);
3921 // Build a record containing all of the delegating constructors we still need
3923 RecordData DelegatingCtorDecls;
3925 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
3927 // Write the set of weak, undeclared identifiers. We always write the
3928 // entire table, since later PCH files in a PCH chain are only interested in
3929 // the results at the end of the chain.
3930 RecordData WeakUndeclaredIdentifiers;
3931 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
3932 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
3933 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
3934 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
3935 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
3936 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
3937 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
3938 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
3942 // Build a record containing all of the locally-scoped extern "C"
3943 // declarations in this header file. Generally, this record will be
3945 RecordData LocallyScopedExternCDecls;
3946 // FIXME: This is filling in the AST file in densemap order which is
3948 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3949 TD = SemaRef.LocallyScopedExternCDecls.begin(),
3950 TDEnd = SemaRef.LocallyScopedExternCDecls.end();
3951 TD != TDEnd; ++TD) {
3952 if (!TD->second->isFromASTFile())
3953 AddDeclRef(TD->second, LocallyScopedExternCDecls);
3956 // Build a record containing all of the ext_vector declarations.
3957 RecordData ExtVectorDecls;
3958 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
3960 // Build a record containing all of the VTable uses information.
3961 RecordData VTableUses;
3962 if (!SemaRef.VTableUses.empty()) {
3963 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
3964 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
3965 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
3966 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
3970 // Build a record containing all of dynamic classes declarations.
3971 RecordData DynamicClasses;
3972 AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses);
3974 // Build a record containing all of pending implicit instantiations.
3975 RecordData PendingInstantiations;
3976 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
3977 I = SemaRef.PendingInstantiations.begin(),
3978 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
3979 AddDeclRef(I->first, PendingInstantiations);
3980 AddSourceLocation(I->second, PendingInstantiations);
3982 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
3983 "There are local ones at end of translation unit!");
3985 // Build a record containing some declaration references.
3986 RecordData SemaDeclRefs;
3987 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
3988 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
3989 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
3992 RecordData CUDASpecialDeclRefs;
3993 if (Context.getcudaConfigureCallDecl()) {
3994 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
3997 // Build a record containing all of the known namespaces.
3998 RecordData KnownNamespaces;
3999 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
4000 I = SemaRef.KnownNamespaces.begin(),
4001 IEnd = SemaRef.KnownNamespaces.end();
4004 AddDeclRef(I->first, KnownNamespaces);
4007 // Build a record of all used, undefined objects that require definitions.
4008 RecordData UndefinedButUsed;
4010 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4011 SemaRef.getUndefinedButUsed(Undefined);
4012 for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
4013 I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
4014 AddDeclRef(I->first, UndefinedButUsed);
4015 AddSourceLocation(I->second, UndefinedButUsed);
4018 // Write the control block
4019 WriteControlBlock(PP, Context, isysroot, OutputFile);
4021 // Write the remaining AST contents.
4023 Stream.EnterSubblock(AST_BLOCK_ID, 5);
4025 // This is so that older clang versions, before the introduction
4026 // of the control block, can read and reject the newer PCH format.
4028 Record.push_back(VERSION_MAJOR);
4029 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4031 // Create a lexical update block containing all of the declarations in the
4032 // translation unit that do not come from other AST files.
4033 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4034 SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
4035 for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
4036 E = TU->noload_decls_end();
4038 if (!(*I)->isFromASTFile())
4039 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
4042 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
4043 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4044 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4045 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
4047 Record.push_back(TU_UPDATE_LEXICAL);
4048 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4049 data(NewGlobalDecls));
4051 // And a visible updates block for the translation unit.
4052 Abv = new llvm::BitCodeAbbrev();
4053 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4054 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4055 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
4056 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4057 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4058 WriteDeclContextVisibleUpdate(TU);
4060 // If the translation unit has an anonymous namespace, and we don't already
4061 // have an update block for it, write it as an update block.
4062 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4063 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4064 if (Record.empty()) {
4065 Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE);
4066 Record.push_back(reinterpret_cast<uint64_t>(NS));
4070 // Make sure visible decls, added to DeclContexts previously loaded from
4071 // an AST file, are registered for serialization.
4072 for (SmallVectorImpl<const Decl *>::iterator
4073 I = UpdatingVisibleDecls.begin(),
4074 E = UpdatingVisibleDecls.end(); I != E; ++I) {
4078 // Make sure all decls associated with an identifier are registered for
4080 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
4081 IDEnd = PP.getIdentifierTable().end();
4082 ID != IDEnd; ++ID) {
4083 const IdentifierInfo *II = ID->second;
4084 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization()) {
4085 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4086 DEnd = SemaRef.IdResolver.end();
4093 // Resolve any declaration pointers within the declaration updates block.
4094 ResolveDeclUpdatesBlocks();
4096 // Form the record of special types.
4097 RecordData SpecialTypes;
4098 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4099 AddTypeRef(Context.getFILEType(), SpecialTypes);
4100 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4101 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4102 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4103 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4104 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4105 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4107 // Keep writing types and declarations until all types and
4108 // declarations have been written.
4109 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
4110 WriteDeclsBlockAbbrevs();
4111 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
4112 E = DeclsToRewrite.end();
4114 DeclTypesToEmit.push(const_cast<Decl*>(*I));
4115 while (!DeclTypesToEmit.empty()) {
4116 DeclOrType DOT = DeclTypesToEmit.front();
4117 DeclTypesToEmit.pop();
4119 WriteType(DOT.getType());
4121 WriteDecl(Context, DOT.getDecl());
4125 DoneWritingDeclsAndTypes = true;
4127 WriteFileDeclIDsMap();
4128 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
4132 // Write the mapping information describing our module dependencies and how
4133 // each of those modules were mapped into our own offset/ID space, so that
4134 // the reader can build the appropriate mapping to its own offset/ID space.
4135 // The map consists solely of a blob with the following format:
4136 // *(module-name-len:i16 module-name:len*i8
4137 // source-location-offset:i32
4138 // identifier-id:i32
4139 // preprocessed-entity-id:i32
4140 // macro-definition-id:i32
4143 // declaration-id:i32
4144 // c++-base-specifiers-id:i32
4147 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
4148 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4149 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4150 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
4151 SmallString<2048> Buffer;
4153 llvm::raw_svector_ostream Out(Buffer);
4154 for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(),
4155 MEnd = Chain->ModuleMgr.end();
4157 StringRef FileName = (*M)->FileName;
4158 io::Emit16(Out, FileName.size());
4159 Out.write(FileName.data(), FileName.size());
4160 io::Emit32(Out, (*M)->SLocEntryBaseOffset);
4161 io::Emit32(Out, (*M)->BaseIdentifierID);
4162 io::Emit32(Out, (*M)->BaseMacroID);
4163 io::Emit32(Out, (*M)->BasePreprocessedEntityID);
4164 io::Emit32(Out, (*M)->BaseSubmoduleID);
4165 io::Emit32(Out, (*M)->BaseSelectorID);
4166 io::Emit32(Out, (*M)->BaseDeclID);
4167 io::Emit32(Out, (*M)->BaseTypeIndex);
4171 Record.push_back(MODULE_OFFSET_MAP);
4172 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4173 Buffer.data(), Buffer.size());
4175 WritePreprocessor(PP, isModule);
4176 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
4177 WriteSelectors(SemaRef);
4178 WriteReferencedSelectorsPool(SemaRef);
4179 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4180 WriteFPPragmaOptions(SemaRef.getFPOptions());
4181 WriteOpenCLExtensions(SemaRef);
4183 WriteTypeDeclOffsets();
4184 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
4186 WriteCXXBaseSpecifiersOffsets();
4188 // If we're emitting a module, write out the submodule information.
4190 WriteSubmodules(WritingModule);
4192 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4194 // Write the record containing external, unnamed definitions.
4195 if (!ExternalDefinitions.empty())
4196 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
4198 // Write the record containing tentative definitions.
4199 if (!TentativeDefinitions.empty())
4200 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4202 // Write the record containing unused file scoped decls.
4203 if (!UnusedFileScopedDecls.empty())
4204 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4206 // Write the record containing weak undeclared identifiers.
4207 if (!WeakUndeclaredIdentifiers.empty())
4208 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4209 WeakUndeclaredIdentifiers);
4211 // Write the record containing locally-scoped extern "C" definitions.
4212 if (!LocallyScopedExternCDecls.empty())
4213 Stream.EmitRecord(LOCALLY_SCOPED_EXTERN_C_DECLS,
4214 LocallyScopedExternCDecls);
4216 // Write the record containing ext_vector type names.
4217 if (!ExtVectorDecls.empty())
4218 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4220 // Write the record containing VTable uses information.
4221 if (!VTableUses.empty())
4222 Stream.EmitRecord(VTABLE_USES, VTableUses);
4224 // Write the record containing dynamic classes declarations.
4225 if (!DynamicClasses.empty())
4226 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
4228 // Write the record containing pending implicit instantiations.
4229 if (!PendingInstantiations.empty())
4230 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4232 // Write the record containing declaration references of Sema.
4233 if (!SemaDeclRefs.empty())
4234 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4236 // Write the record containing CUDA-specific declaration references.
4237 if (!CUDASpecialDeclRefs.empty())
4238 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4240 // Write the delegating constructors.
4241 if (!DelegatingCtorDecls.empty())
4242 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4244 // Write the known namespaces.
4245 if (!KnownNamespaces.empty())
4246 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4248 // Write the undefined internal functions and variables, and inline functions.
4249 if (!UndefinedButUsed.empty())
4250 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4252 // Write the visible updates to DeclContexts.
4253 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
4254 I = UpdatedDeclContexts.begin(),
4255 E = UpdatedDeclContexts.end();
4257 WriteDeclContextVisibleUpdate(*I);
4259 if (!WritingModule) {
4260 // Write the submodules that were imported, if any.
4261 RecordData ImportedModules;
4262 for (ASTContext::import_iterator I = Context.local_import_begin(),
4263 IEnd = Context.local_import_end();
4265 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4266 ImportedModules.push_back(SubmoduleIDs[I->getImportedModule()]);
4268 if (!ImportedModules.empty()) {
4270 llvm::array_pod_sort(ImportedModules.begin(), ImportedModules.end());
4272 // Unique module IDs.
4273 ImportedModules.erase(std::unique(ImportedModules.begin(),
4274 ImportedModules.end()),
4275 ImportedModules.end());
4277 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4281 WriteDeclUpdatesBlocks();
4282 WriteDeclReplacementsBlock();
4283 WriteRedeclarations();
4285 WriteObjCCategories();
4286 WriteLateParsedTemplates(SemaRef);
4288 // Some simple statistics
4290 Record.push_back(NumStatements);
4291 Record.push_back(NumMacros);
4292 Record.push_back(NumLexicalDeclContexts);
4293 Record.push_back(NumVisibleDeclContexts);
4294 Stream.EmitRecord(STATISTICS, Record);
4298 /// \brief Go through the declaration update blocks and resolve declaration
4299 /// pointers into declaration IDs.
4300 void ASTWriter::ResolveDeclUpdatesBlocks() {
4301 for (DeclUpdateMap::iterator
4302 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
4303 const Decl *D = I->first;
4304 UpdateRecord &URec = I->second;
4307 continue; // The decl will be written completely
4309 unsigned Idx = 0, N = URec.size();
4311 switch ((DeclUpdateKind)URec[Idx++]) {
4312 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4313 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4314 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
4315 URec[Idx] = GetDeclRef(reinterpret_cast<Decl *>(URec[Idx]));
4319 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4320 case UPD_DECL_MARKED_USED:
4324 case UPD_CXX_DEDUCED_RETURN_TYPE:
4325 URec[Idx] = GetOrCreateTypeID(
4326 QualType::getFromOpaquePtr(reinterpret_cast<void *>(URec[Idx])));
4334 void ASTWriter::WriteDeclUpdatesBlocks() {
4335 if (DeclUpdates.empty())
4338 RecordData OffsetsRecord;
4339 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
4340 for (DeclUpdateMap::iterator
4341 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
4342 const Decl *D = I->first;
4343 UpdateRecord &URec = I->second;
4346 continue; // The decl will be written completely,no need to store updates.
4348 uint64_t Offset = Stream.GetCurrentBitNo();
4349 Stream.EmitRecord(DECL_UPDATES, URec);
4351 OffsetsRecord.push_back(GetDeclRef(D));
4352 OffsetsRecord.push_back(Offset);
4355 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
4358 void ASTWriter::WriteDeclReplacementsBlock() {
4359 if (ReplacedDecls.empty())
4363 for (SmallVectorImpl<ReplacedDeclInfo>::iterator
4364 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
4365 Record.push_back(I->ID);
4366 Record.push_back(I->Offset);
4367 Record.push_back(I->Loc);
4369 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
4372 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
4373 Record.push_back(Loc.getRawEncoding());
4376 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
4377 AddSourceLocation(Range.getBegin(), Record);
4378 AddSourceLocation(Range.getEnd(), Record);
4381 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
4382 Record.push_back(Value.getBitWidth());
4383 const uint64_t *Words = Value.getRawData();
4384 Record.append(Words, Words + Value.getNumWords());
4387 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
4388 Record.push_back(Value.isUnsigned());
4389 AddAPInt(Value, Record);
4392 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
4393 AddAPInt(Value.bitcastToAPInt(), Record);
4396 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
4397 Record.push_back(getIdentifierRef(II));
4400 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
4404 IdentID &ID = IdentifierIDs[II];
4410 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
4411 // Don't emit builtin macros like __LINE__ to the AST file unless they
4412 // have been redefined by the header (in which case they are not
4414 if (MI == 0 || MI->isBuiltinMacro())
4417 MacroID &ID = MacroIDs[MI];
4420 MacroInfoToEmitData Info = { Name, MI, ID };
4421 MacroInfosToEmit.push_back(Info);
4426 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
4427 if (MI == 0 || MI->isBuiltinMacro())
4430 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4431 return MacroIDs[MI];
4434 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
4435 assert(IdentMacroDirectivesOffsetMap[Name] && "not set!");
4436 return IdentMacroDirectivesOffsetMap[Name];
4439 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
4440 Record.push_back(getSelectorRef(SelRef));
4443 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
4444 if (Sel.getAsOpaquePtr() == 0) {
4448 SelectorID SID = SelectorIDs[Sel];
4449 if (SID == 0 && Chain) {
4450 // This might trigger a ReadSelector callback, which will set the ID for
4452 Chain->LoadSelector(Sel);
4453 SID = SelectorIDs[Sel];
4456 SID = NextSelectorID++;
4457 SelectorIDs[Sel] = SID;
4462 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
4463 AddDeclRef(Temp->getDestructor(), Record);
4466 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
4467 CXXBaseSpecifier const *BasesEnd,
4468 RecordDataImpl &Record) {
4469 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4470 CXXBaseSpecifiersToWrite.push_back(
4471 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4473 Record.push_back(NextCXXBaseSpecifiersID++);
4476 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
4477 const TemplateArgumentLocInfo &Arg,
4478 RecordDataImpl &Record) {
4480 case TemplateArgument::Expression:
4481 AddStmt(Arg.getAsExpr());
4483 case TemplateArgument::Type:
4484 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
4486 case TemplateArgument::Template:
4487 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
4488 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4490 case TemplateArgument::TemplateExpansion:
4491 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
4492 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4493 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
4495 case TemplateArgument::Null:
4496 case TemplateArgument::Integral:
4497 case TemplateArgument::Declaration:
4498 case TemplateArgument::NullPtr:
4499 case TemplateArgument::Pack:
4500 // FIXME: Is this right?
4505 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
4506 RecordDataImpl &Record) {
4507 AddTemplateArgument(Arg.getArgument(), Record);
4509 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4510 bool InfoHasSameExpr
4511 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4512 Record.push_back(InfoHasSameExpr);
4513 if (InfoHasSameExpr)
4514 return; // Avoid storing the same expr twice.
4516 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
4520 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
4521 RecordDataImpl &Record) {
4523 AddTypeRef(QualType(), Record);
4527 AddTypeLoc(TInfo->getTypeLoc(), Record);
4530 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
4531 AddTypeRef(TL.getType(), Record);
4533 TypeLocWriter TLW(*this, Record);
4534 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
4538 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
4539 Record.push_back(GetOrCreateTypeID(T));
4542 TypeID ASTWriter::GetOrCreateTypeID( QualType T) {
4544 return MakeTypeID(*Context, T,
4545 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
4548 TypeID ASTWriter::getTypeID(QualType T) const {
4550 return MakeTypeID(*Context, T,
4551 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
4554 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
4557 assert(!T.getLocalFastQualifiers());
4559 TypeIdx &Idx = TypeIdxs[T];
4560 if (Idx.getIndex() == 0) {
4561 if (DoneWritingDeclsAndTypes) {
4562 assert(0 && "New type seen after serializing all the types to emit!");
4566 // We haven't seen this type before. Assign it a new ID and put it
4567 // into the queue of types to emit.
4568 Idx = TypeIdx(NextTypeID++);
4569 DeclTypesToEmit.push(T);
4574 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
4577 assert(!T.getLocalFastQualifiers());
4579 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4580 assert(I != TypeIdxs.end() && "Type not emitted!");
4584 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
4585 Record.push_back(GetDeclRef(D));
4588 DeclID ASTWriter::GetDeclRef(const Decl *D) {
4589 assert(WritingAST && "Cannot request a declaration ID before AST writing");
4595 // If D comes from an AST file, its declaration ID is already known and
4597 if (D->isFromASTFile())
4598 return D->getGlobalID();
4600 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
4601 DeclID &ID = DeclIDs[D];
4603 if (DoneWritingDeclsAndTypes) {
4604 assert(0 && "New decl seen after serializing all the decls to emit!");
4608 // We haven't seen this declaration before. Give it a new ID and
4609 // enqueue it in the list of declarations to emit.
4611 DeclTypesToEmit.push(const_cast<Decl *>(D));
4617 DeclID ASTWriter::getDeclID(const Decl *D) {
4621 // If D comes from an AST file, its declaration ID is already known and
4623 if (D->isFromASTFile())
4624 return D->getGlobalID();
4626 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
4630 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
4634 SourceLocation Loc = D->getLocation();
4635 if (Loc.isInvalid())
4638 // We only keep track of the file-level declarations of each file.
4639 if (!D->getLexicalDeclContext()->isFileContext())
4641 // FIXME: ParmVarDecls that are part of a function type of a parameter of
4642 // a function/objc method, should not have TU as lexical context.
4643 if (isa<ParmVarDecl>(D))
4646 SourceManager &SM = Context->getSourceManager();
4647 SourceLocation FileLoc = SM.getFileLoc(Loc);
4648 assert(SM.isLocalSourceLocation(FileLoc));
4651 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
4652 if (FID.isInvalid())
4654 assert(SM.getSLocEntry(FID).isFile());
4656 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
4658 Info = new DeclIDInFileInfo();
4660 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
4661 LocDeclIDsTy &Decls = Info->DeclIDs;
4663 if (Decls.empty() || Decls.back().first <= Offset) {
4664 Decls.push_back(LocDecl);
4668 LocDeclIDsTy::iterator I =
4669 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
4671 Decls.insert(I, LocDecl);
4674 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
4675 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
4676 Record.push_back(Name.getNameKind());
4677 switch (Name.getNameKind()) {
4678 case DeclarationName::Identifier:
4679 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
4682 case DeclarationName::ObjCZeroArgSelector:
4683 case DeclarationName::ObjCOneArgSelector:
4684 case DeclarationName::ObjCMultiArgSelector:
4685 AddSelectorRef(Name.getObjCSelector(), Record);
4688 case DeclarationName::CXXConstructorName:
4689 case DeclarationName::CXXDestructorName:
4690 case DeclarationName::CXXConversionFunctionName:
4691 AddTypeRef(Name.getCXXNameType(), Record);
4694 case DeclarationName::CXXOperatorName:
4695 Record.push_back(Name.getCXXOverloadedOperator());
4698 case DeclarationName::CXXLiteralOperatorName:
4699 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
4702 case DeclarationName::CXXUsingDirective:
4703 // No extra data to emit
4708 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
4709 DeclarationName Name, RecordDataImpl &Record) {
4710 switch (Name.getNameKind()) {
4711 case DeclarationName::CXXConstructorName:
4712 case DeclarationName::CXXDestructorName:
4713 case DeclarationName::CXXConversionFunctionName:
4714 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
4717 case DeclarationName::CXXOperatorName:
4719 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
4722 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
4726 case DeclarationName::CXXLiteralOperatorName:
4728 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
4732 case DeclarationName::Identifier:
4733 case DeclarationName::ObjCZeroArgSelector:
4734 case DeclarationName::ObjCOneArgSelector:
4735 case DeclarationName::ObjCMultiArgSelector:
4736 case DeclarationName::CXXUsingDirective:
4741 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4742 RecordDataImpl &Record) {
4743 AddDeclarationName(NameInfo.getName(), Record);
4744 AddSourceLocation(NameInfo.getLoc(), Record);
4745 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
4748 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
4749 RecordDataImpl &Record) {
4750 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
4751 Record.push_back(Info.NumTemplParamLists);
4752 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
4753 AddTemplateParameterList(Info.TemplParamLists[i], Record);
4756 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
4757 RecordDataImpl &Record) {
4758 // Nested name specifiers usually aren't too long. I think that 8 would
4759 // typically accommodate the vast majority.
4760 SmallVector<NestedNameSpecifier *, 8> NestedNames;
4762 // Push each of the NNS's onto a stack for serialization in reverse order.
4764 NestedNames.push_back(NNS);
4765 NNS = NNS->getPrefix();
4768 Record.push_back(NestedNames.size());
4769 while(!NestedNames.empty()) {
4770 NNS = NestedNames.pop_back_val();
4771 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
4772 Record.push_back(Kind);
4774 case NestedNameSpecifier::Identifier:
4775 AddIdentifierRef(NNS->getAsIdentifier(), Record);
4778 case NestedNameSpecifier::Namespace:
4779 AddDeclRef(NNS->getAsNamespace(), Record);
4782 case NestedNameSpecifier::NamespaceAlias:
4783 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
4786 case NestedNameSpecifier::TypeSpec:
4787 case NestedNameSpecifier::TypeSpecWithTemplate:
4788 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
4789 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
4792 case NestedNameSpecifier::Global:
4793 // Don't need to write an associated value.
4799 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4800 RecordDataImpl &Record) {
4801 // Nested name specifiers usually aren't too long. I think that 8 would
4802 // typically accommodate the vast majority.
4803 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
4805 // Push each of the nested-name-specifiers's onto a stack for
4806 // serialization in reverse order.
4808 NestedNames.push_back(NNS);
4809 NNS = NNS.getPrefix();
4812 Record.push_back(NestedNames.size());
4813 while(!NestedNames.empty()) {
4814 NNS = NestedNames.pop_back_val();
4815 NestedNameSpecifier::SpecifierKind Kind
4816 = NNS.getNestedNameSpecifier()->getKind();
4817 Record.push_back(Kind);
4819 case NestedNameSpecifier::Identifier:
4820 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
4821 AddSourceRange(NNS.getLocalSourceRange(), Record);
4824 case NestedNameSpecifier::Namespace:
4825 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
4826 AddSourceRange(NNS.getLocalSourceRange(), Record);
4829 case NestedNameSpecifier::NamespaceAlias:
4830 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
4831 AddSourceRange(NNS.getLocalSourceRange(), Record);
4834 case NestedNameSpecifier::TypeSpec:
4835 case NestedNameSpecifier::TypeSpecWithTemplate:
4836 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
4837 AddTypeLoc(NNS.getTypeLoc(), Record);
4838 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
4841 case NestedNameSpecifier::Global:
4842 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
4848 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
4849 TemplateName::NameKind Kind = Name.getKind();
4850 Record.push_back(Kind);
4852 case TemplateName::Template:
4853 AddDeclRef(Name.getAsTemplateDecl(), Record);
4856 case TemplateName::OverloadedTemplate: {
4857 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
4858 Record.push_back(OvT->size());
4859 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
4861 AddDeclRef(*I, Record);
4865 case TemplateName::QualifiedTemplate: {
4866 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
4867 AddNestedNameSpecifier(QualT->getQualifier(), Record);
4868 Record.push_back(QualT->hasTemplateKeyword());
4869 AddDeclRef(QualT->getTemplateDecl(), Record);
4873 case TemplateName::DependentTemplate: {
4874 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
4875 AddNestedNameSpecifier(DepT->getQualifier(), Record);
4876 Record.push_back(DepT->isIdentifier());
4877 if (DepT->isIdentifier())
4878 AddIdentifierRef(DepT->getIdentifier(), Record);
4880 Record.push_back(DepT->getOperator());
4884 case TemplateName::SubstTemplateTemplateParm: {
4885 SubstTemplateTemplateParmStorage *subst
4886 = Name.getAsSubstTemplateTemplateParm();
4887 AddDeclRef(subst->getParameter(), Record);
4888 AddTemplateName(subst->getReplacement(), Record);
4892 case TemplateName::SubstTemplateTemplateParmPack: {
4893 SubstTemplateTemplateParmPackStorage *SubstPack
4894 = Name.getAsSubstTemplateTemplateParmPack();
4895 AddDeclRef(SubstPack->getParameterPack(), Record);
4896 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
4902 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
4903 RecordDataImpl &Record) {
4904 Record.push_back(Arg.getKind());
4905 switch (Arg.getKind()) {
4906 case TemplateArgument::Null:
4908 case TemplateArgument::Type:
4909 AddTypeRef(Arg.getAsType(), Record);
4911 case TemplateArgument::Declaration:
4912 AddDeclRef(Arg.getAsDecl(), Record);
4913 Record.push_back(Arg.isDeclForReferenceParam());
4915 case TemplateArgument::NullPtr:
4916 AddTypeRef(Arg.getNullPtrType(), Record);
4918 case TemplateArgument::Integral:
4919 AddAPSInt(Arg.getAsIntegral(), Record);
4920 AddTypeRef(Arg.getIntegralType(), Record);
4922 case TemplateArgument::Template:
4923 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
4925 case TemplateArgument::TemplateExpansion:
4926 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
4927 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
4928 Record.push_back(*NumExpansions + 1);
4930 Record.push_back(0);
4932 case TemplateArgument::Expression:
4933 AddStmt(Arg.getAsExpr());
4935 case TemplateArgument::Pack:
4936 Record.push_back(Arg.pack_size());
4937 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
4939 AddTemplateArgument(*I, Record);
4945 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
4946 RecordDataImpl &Record) {
4947 assert(TemplateParams && "No TemplateParams!");
4948 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
4949 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
4950 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
4951 Record.push_back(TemplateParams->size());
4952 for (TemplateParameterList::const_iterator
4953 P = TemplateParams->begin(), PEnd = TemplateParams->end();
4955 AddDeclRef(*P, Record);
4958 /// \brief Emit a template argument list.
4960 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
4961 RecordDataImpl &Record) {
4962 assert(TemplateArgs && "No TemplateArgs!");
4963 Record.push_back(TemplateArgs->size());
4964 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
4965 AddTemplateArgument(TemplateArgs->get(i), Record);
4969 ASTWriter::AddASTTemplateArgumentListInfo
4970 (const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record) {
4971 assert(ASTTemplArgList && "No ASTTemplArgList!");
4972 AddSourceLocation(ASTTemplArgList->LAngleLoc, Record);
4973 AddSourceLocation(ASTTemplArgList->RAngleLoc, Record);
4974 Record.push_back(ASTTemplArgList->NumTemplateArgs);
4975 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
4976 for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
4977 AddTemplateArgumentLoc(TemplArgs[i], Record);
4981 ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
4982 Record.push_back(Set.size());
4983 for (ASTUnresolvedSet::const_iterator
4984 I = Set.begin(), E = Set.end(); I != E; ++I) {
4985 AddDeclRef(I.getDecl(), Record);
4986 Record.push_back(I.getAccess());
4990 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
4991 RecordDataImpl &Record) {
4992 Record.push_back(Base.isVirtual());
4993 Record.push_back(Base.isBaseOfClass());
4994 Record.push_back(Base.getAccessSpecifierAsWritten());
4995 Record.push_back(Base.getInheritConstructors());
4996 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
4997 AddSourceRange(Base.getSourceRange(), Record);
4998 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5003 void ASTWriter::FlushCXXBaseSpecifiers() {
5005 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
5008 // Record the offset of this base-specifier set.
5009 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
5010 if (Index == CXXBaseSpecifiersOffsets.size())
5011 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
5013 if (Index > CXXBaseSpecifiersOffsets.size())
5014 CXXBaseSpecifiersOffsets.resize(Index + 1);
5015 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
5018 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
5019 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
5020 Record.push_back(BEnd - B);
5021 for (; B != BEnd; ++B)
5022 AddCXXBaseSpecifier(*B, Record);
5023 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
5025 // Flush any expressions that were written as part of the base specifiers.
5029 CXXBaseSpecifiersToWrite.clear();
5032 void ASTWriter::AddCXXCtorInitializers(
5033 const CXXCtorInitializer * const *CtorInitializers,
5034 unsigned NumCtorInitializers,
5035 RecordDataImpl &Record) {
5036 Record.push_back(NumCtorInitializers);
5037 for (unsigned i=0; i != NumCtorInitializers; ++i) {
5038 const CXXCtorInitializer *Init = CtorInitializers[i];
5040 if (Init->isBaseInitializer()) {
5041 Record.push_back(CTOR_INITIALIZER_BASE);
5042 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
5043 Record.push_back(Init->isBaseVirtual());
5044 } else if (Init->isDelegatingInitializer()) {
5045 Record.push_back(CTOR_INITIALIZER_DELEGATING);
5046 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
5047 } else if (Init->isMemberInitializer()){
5048 Record.push_back(CTOR_INITIALIZER_MEMBER);
5049 AddDeclRef(Init->getMember(), Record);
5051 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5052 AddDeclRef(Init->getIndirectMember(), Record);
5055 AddSourceLocation(Init->getMemberLocation(), Record);
5056 AddStmt(Init->getInit());
5057 AddSourceLocation(Init->getLParenLoc(), Record);
5058 AddSourceLocation(Init->getRParenLoc(), Record);
5059 Record.push_back(Init->isWritten());
5060 if (Init->isWritten()) {
5061 Record.push_back(Init->getSourceOrder());
5063 Record.push_back(Init->getNumArrayIndices());
5064 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
5065 AddDeclRef(Init->getArrayIndex(i), Record);
5070 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
5071 assert(D->DefinitionData);
5072 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
5073 Record.push_back(Data.IsLambda);
5074 Record.push_back(Data.UserDeclaredConstructor);
5075 Record.push_back(Data.UserDeclaredSpecialMembers);
5076 Record.push_back(Data.Aggregate);
5077 Record.push_back(Data.PlainOldData);
5078 Record.push_back(Data.Empty);
5079 Record.push_back(Data.Polymorphic);
5080 Record.push_back(Data.Abstract);
5081 Record.push_back(Data.IsStandardLayout);
5082 Record.push_back(Data.HasNoNonEmptyBases);
5083 Record.push_back(Data.HasPrivateFields);
5084 Record.push_back(Data.HasProtectedFields);
5085 Record.push_back(Data.HasPublicFields);
5086 Record.push_back(Data.HasMutableFields);
5087 Record.push_back(Data.HasOnlyCMembers);
5088 Record.push_back(Data.HasInClassInitializer);
5089 Record.push_back(Data.HasUninitializedReferenceMember);
5090 Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
5091 Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
5092 Record.push_back(Data.NeedOverloadResolutionForDestructor);
5093 Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
5094 Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
5095 Record.push_back(Data.DefaultedDestructorIsDeleted);
5096 Record.push_back(Data.HasTrivialSpecialMembers);
5097 Record.push_back(Data.HasIrrelevantDestructor);
5098 Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
5099 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5100 Record.push_back(Data.HasConstexprDefaultConstructor);
5101 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
5102 Record.push_back(Data.ComputedVisibleConversions);
5103 Record.push_back(Data.UserProvidedDefaultConstructor);
5104 Record.push_back(Data.DeclaredSpecialMembers);
5105 Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
5106 Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
5107 Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5108 Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
5109 // IsLambda bit is already saved.
5111 Record.push_back(Data.NumBases);
5112 if (Data.NumBases > 0)
5113 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
5116 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5117 Record.push_back(Data.NumVBases);
5118 if (Data.NumVBases > 0)
5119 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
5122 AddUnresolvedSet(Data.Conversions.get(*Context), Record);
5123 AddUnresolvedSet(Data.VisibleConversions.get(*Context), Record);
5124 // Data.Definition is the owning decl, no need to write it.
5125 AddDeclRef(D->getFirstFriend(), Record);
5127 // Add lambda-specific data.
5128 if (Data.IsLambda) {
5129 CXXRecordDecl::LambdaDefinitionData &Lambda = D->getLambdaData();
5130 Record.push_back(Lambda.Dependent);
5131 Record.push_back(Lambda.IsGenericLambda);
5132 Record.push_back(Lambda.CaptureDefault);
5133 Record.push_back(Lambda.NumCaptures);
5134 Record.push_back(Lambda.NumExplicitCaptures);
5135 Record.push_back(Lambda.ManglingNumber);
5136 AddDeclRef(Lambda.ContextDecl, Record);
5137 AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
5138 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5139 LambdaExpr::Capture &Capture = Lambda.Captures[I];
5140 AddSourceLocation(Capture.getLocation(), Record);
5141 Record.push_back(Capture.isImplicit());
5142 Record.push_back(Capture.getCaptureKind());
5143 switch (Capture.getCaptureKind()) {
5149 Capture.capturesVariable() ? Capture.getCapturedVar() : 0;
5150 AddDeclRef(Var, Record);
5151 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5160 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5161 assert(Reader && "Cannot remove chain");
5162 assert((!Chain || Chain == Reader) && "Cannot replace chain");
5163 assert(FirstDeclID == NextDeclID &&
5164 FirstTypeID == NextTypeID &&
5165 FirstIdentID == NextIdentID &&
5166 FirstMacroID == NextMacroID &&
5167 FirstSubmoduleID == NextSubmoduleID &&
5168 FirstSelectorID == NextSelectorID &&
5169 "Setting chain after writing has started.");
5173 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5174 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5175 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5176 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5177 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5178 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5179 NextDeclID = FirstDeclID;
5180 NextTypeID = FirstTypeID;
5181 NextIdentID = FirstIdentID;
5182 NextMacroID = FirstMacroID;
5183 NextSelectorID = FirstSelectorID;
5184 NextSubmoduleID = FirstSubmoduleID;
5187 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5188 // Always keep the highest ID. See \p TypeRead() for more information.
5189 IdentID &StoredID = IdentifierIDs[II];
5194 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5195 // Always keep the highest ID. See \p TypeRead() for more information.
5196 MacroID &StoredID = MacroIDs[MI];
5201 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5202 // Always take the highest-numbered type index. This copes with an interesting
5203 // case for chained AST writing where we schedule writing the type and then,
5204 // later, deserialize the type from another AST. In this case, we want to
5205 // keep the higher-numbered entry so that we can properly write it out to
5207 TypeIdx &StoredIdx = TypeIdxs[T];
5208 if (Idx.getIndex() >= StoredIdx.getIndex())
5212 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5213 // Always keep the highest ID. See \p TypeRead() for more information.
5214 SelectorID &StoredID = SelectorIDs[S];
5219 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5220 MacroDefinition *MD) {
5221 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5222 MacroDefinitions[MD] = ID;
5225 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5226 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5227 SubmoduleIDs[Mod] = ID;
5230 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5231 assert(D->isCompleteDefinition());
5232 assert(!WritingAST && "Already writing the AST!");
5233 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
5234 // We are interested when a PCH decl is modified.
5235 if (RD->isFromASTFile()) {
5236 // A forward reference was mutated into a definition. Rewrite it.
5237 // FIXME: This happens during template instantiation, should we
5238 // have created a new definition decl instead ?
5244 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5245 assert(!WritingAST && "Already writing the AST!");
5247 // TU and namespaces are handled elsewhere.
5248 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
5251 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
5252 return; // Not a source decl added to a DeclContext from PCH.
5254 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5255 AddUpdatedDeclContext(DC);
5256 UpdatingVisibleDecls.push_back(D);
5259 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5260 assert(!WritingAST && "Already writing the AST!");
5261 assert(D->isImplicit());
5262 if (!(!D->isFromASTFile() && RD->isFromASTFile()))
5263 return; // Not a source member added to a class from PCH.
5264 if (!isa<CXXMethodDecl>(D))
5265 return; // We are interested in lazily declared implicit methods.
5267 // A decl coming from PCH was modified.
5268 assert(RD->isCompleteDefinition());
5269 UpdateRecord &Record = DeclUpdates[RD];
5270 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
5271 Record.push_back(reinterpret_cast<uint64_t>(D));
5274 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
5275 const ClassTemplateSpecializationDecl *D) {
5276 // The specializations set is kept in the canonical template.
5277 assert(!WritingAST && "Already writing the AST!");
5278 TD = TD->getCanonicalDecl();
5279 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5280 return; // Not a source specialization added to a template from PCH.
5282 UpdateRecord &Record = DeclUpdates[TD];
5283 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
5284 Record.push_back(reinterpret_cast<uint64_t>(D));
5287 void ASTWriter::AddedCXXTemplateSpecialization(
5288 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
5289 // The specializations set is kept in the canonical template.
5290 assert(!WritingAST && "Already writing the AST!");
5291 TD = TD->getCanonicalDecl();
5292 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5293 return; // Not a source specialization added to a template from PCH.
5295 UpdateRecord &Record = DeclUpdates[TD];
5296 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
5297 Record.push_back(reinterpret_cast<uint64_t>(D));
5300 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
5301 const FunctionDecl *D) {
5302 // The specializations set is kept in the canonical template.
5303 assert(!WritingAST && "Already writing the AST!");
5304 TD = TD->getCanonicalDecl();
5305 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5306 return; // Not a source specialization added to a template from PCH.
5308 UpdateRecord &Record = DeclUpdates[TD];
5309 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
5310 Record.push_back(reinterpret_cast<uint64_t>(D));
5313 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5314 assert(!WritingAST && "Already writing the AST!");
5315 FD = FD->getCanonicalDecl();
5316 if (!FD->isFromASTFile())
5317 return; // Not a function declared in PCH and defined outside.
5319 UpdateRecord &Record = DeclUpdates[FD];
5320 Record.push_back(UPD_CXX_DEDUCED_RETURN_TYPE);
5321 Record.push_back(reinterpret_cast<uint64_t>(ReturnType.getAsOpaquePtr()));
5324 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
5325 assert(!WritingAST && "Already writing the AST!");
5326 if (!D->isFromASTFile())
5327 return; // Declaration not imported from PCH.
5329 // Implicit decl from a PCH was defined.
5330 // FIXME: Should implicit definition be a separate FunctionDecl?
5334 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
5335 assert(!WritingAST && "Already writing the AST!");
5336 if (!D->isFromASTFile())
5339 // Since the actual instantiation is delayed, this really means that we need
5340 // to update the instantiation location.
5341 UpdateRecord &Record = DeclUpdates[D];
5342 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER);
5344 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record);
5347 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5348 const ObjCInterfaceDecl *IFD) {
5349 assert(!WritingAST && "Already writing the AST!");
5350 if (!IFD->isFromASTFile())
5351 return; // Declaration not imported from PCH.
5353 assert(IFD->getDefinition() && "Category on a class without a definition?");
5354 ObjCClassesWithCategories.insert(
5355 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5359 void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
5360 const ObjCPropertyDecl *OrigProp,
5361 const ObjCCategoryDecl *ClassExt) {
5362 const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
5366 assert(!WritingAST && "Already writing the AST!");
5367 if (!D->isFromASTFile())
5368 return; // Declaration not imported from PCH.
5373 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5374 assert(!WritingAST && "Already writing the AST!");
5375 if (!D->isFromASTFile())
5378 UpdateRecord &Record = DeclUpdates[D];
5379 Record.push_back(UPD_DECL_MARKED_USED);